使用Pandas文档
http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.pct_change.html
我正在尝试创建此函数来计算percentage_change。 我把两个参数传递给它
def PCT(df,n):
d = df['Close'].pct_change(n)
即使以不同的方式重写相同的代码也会给我同样的错误
P = pd.Series(df['Close'].pct_change(n), name = 'PCT_' + str(n))
抛出错误
File "D:\Python Scripts\TA_Liabrary.py", line 15, in PCT
d = df['Close'].pct_change(n)
TypeError: 'NoneType' object has no attribute '__getitem__'
有人可以帮助我吗
示例数据
Index open high low close volume adj.
1/01/2014 54.97 54.97 54.97 54.97 0 49.31993
2/01/2014 55.1 55.95 54.86 55.08 216100 49.41862
3/01/2014 54.5 55 54.16 55 392600 49.34685
6/01/2014 54.82 55.47 54.62 55.14 344500 49.47245
7/01/2014 55.06 55.17 54.27 54.35 677400 48.76365
8/01/2014 54.64 54.88 53.87 54.38 587500 48.79057
9/01/2014 54.57 54.8 54.05 54.48 466800 48.88029
答案 0 :(得分:3)
为什么不能使用文档中的功能?
a = [10,12,13]
b = [12,11,14]
d = {'open': a, 'close': b}
df = DataFrame(data=d)
print df
close open
0 12 10
1 11 12
2 14 13
print df.pct_change(1)
使用一个函数,这将是:
def PCT(dataf,n):
return dataf.pct_change(n)
print PCT(df, 1)
两者都将返回:
close open
0 NaN NaN
1 -0.083333 0.200000
2 0.272727 0.083333
您的示例数据print PCT(df['close'], 1)
将返回:
Index close
2014-01-01 NaN
2014-02-01 0.002001
2014-03-01 -0.001452
2014-06-01 0.002545
2014-07-01 -0.014327
2014-08-01 0.000552
2014-09-01 0.001839
答案 1 :(得分:0)
pct_change
仅适用于单列,可以在多列数据框中进行如下操作
df = pd.DataFrame({
'open': [54.97,55.1,54.5,54.82],
'high': [54.97,55.95,55,55.47],
'low': [54.97,54.86,54.16,54.62],
'close': [54.97,53.08,55,55.14]},
index=['2014-01-01', '2014-02-01', '2014-03-01','2014-04-01'])
open high low close
2014-01-01 54.97 54.97 54.97 54.97
2014-02-01 55.10 55.95 54.86 53.08
2014-03-01 54.50 55.00 54.16 55.00
2014-04-01 54.82 55.47 54.62 55.14
仅将pct_change应用于“关闭”
df.close = df.close.pct_change(periods = 1)
open high low close
2014-01-01 54.97 54.97 54.97 NaN
2014-02-01 55.10 55.95 54.86 -0.034382
2014-03-01 54.50 55.00 54.16 0.036172
2014-04-01 54.82 55.47 54.62 0.002545
应用于以下多个列
# apply pct_change to 'open' and 'close'
df[['open','close']] = df[['open','close']].pct_change(periods = 1)
open high low close
2014-01-01 NaN 54.97 54.97 NaN
2014-02-01 0.002365 55.95 54.86 -0.034382
2014-03-01 -0.010889 55.00 54.16 0.036172
2014-04-01 0.005872 55.47 54.62 0.002545