2014-09-17 2 views
0

Я работаю через Learn Python Hard Way и просматриваю код на Git Hub, прежде чем двигаться дальше. Мне просто интересно, что делает .N на линии с «tm.N = 1000» и как она относится к концу кода.Что означает .N в этом блоке кода Python?

import matplotlib.pyplot as plt 

import random 
import pandas.util.testing as tm 
tm.N = 1000 
df = tm.makeTimeDataFrame() 
import string 
foo = list(string.letters[:5]) * 200 
df['indic'] = list(string.letters[:5]) * 200 
random.shuffle(foo) 
df['indic2'] = foo 
df.boxplot(by=['indic', 'indic2'], fontsize=8, rot=90) 

plt.show() 
+2

Видимо ' tm' - объект с свойством 'N'. –

+0

https://github.com/pydata/pandas/blob/master/pandas/util/testing.py – alex

+0

Спасибо всем за объяснения. – user3099345

ответ

2

N является глобальным в модуле testing.py, который используется по всему модулю для тестирования массивов и других вещей. Его значение по умолчанию равно 30. Например.

np.arange(N * K).reshape((N, K)) 
Series(randn(N), index=index) 

В коде вы проводки он имеет плохое использование, потому что makeTimeDataFrame можно кормить с параметром nper, что в конечном итоге замещен N если nper не предусмотрено. Это правильное использование, что бы не запутать вас:

df = tm.makeTimeDataFrame(nper=1000) 
2

В предыдущей строке, , импортирует модуль pandas.util.testing и, для удобства, дает ему имя tm. Таким образом, tm впоследствии ссылается на этот модуль, и поэтому tm.N ссылается на объект с именем «N» (независимо от того, что есть) в модуле.

1

Источник: https://github.com/pydata/pandas/blob/master/pandas/util/testing.py

Н является переменной в библиотеке pandas.util.testing (импортируемого в tm). Он используется в некоторых из функций, определенных в этой библиотеке, в том числе функции makeTimeSeries называется в getTimeSeriesData, который в свою очередь, вызывается в функции makeTimeDataFrame, что вы звоните с df = tm.makeTimeDataFrame()

1

Вы можете получить информацию о pandas.util.testing.N от docstring а type() функция:

>>> tm.N.__doc__ 
'int(x[, base]) -> integer\n\nConvert a string or number to an integer, if possible. A floating point\nargument will be truncated towards zero (this does not include a string\nrepresentation of a floating point number!) When converting a string, use\nthe optional base. It is an error to supply a base when converting a\nnon-string. If base is zero, the proper base is guessed based on the\nstring content. If the argument is outside the integer range a\nlong object will be returned instead.' 
>>> print(tm.N.__doc__) 
int(x[, base]) -> integer 

Convert a string or number to an integer, if possible. A floating point 
argument will be truncated towards zero (this does not include a string 
representation of a floating point number!) When converting a string, use 
the optional base. It is an error to supply a base when converting a 
non-string. If base is zero, the proper base is guessed based on the 
string content. If the argument is outside the integer range a 
long object will be returned instead. 
>>> type(tm.N) 
<type 'int'> 
1

Это делает таймсерий длиной 1000.

>>> df.head() 
Out[7]: 
        A   B   C   D 
2000-01-03 -0.734093 -0.843961 -0.879394 0.415565 
2000-01-04 0.028562 -1.098165 1.292156 0.512677 
2000-01-05 1.135995 -0.864060 1.297646 -0.166932 
2000-01-06 -0.738651 0.426662 0.505882 -0.124671 
2000-01-07 -1.242401 0.225207 0.053541 -0.234740 
>>> len(df) 
Out[8]: 1000 
1

В панде в модуле pandas.util.testing свойства N означает TimeSeries См this ссылки в разделе:

We could alternatively have used the unit testing function to create a TimeSeries of length 20: 


>>>> pandas.util.testing.N = 20 
>>>> ts = pandas.util.testing.makeTimeSeries() 
Смежные вопросы