gpt4 book ai didi

python - 列值的 pct_change

转载 作者:行者123 更新时间:2023-11-28 20:18:34 29 4
gpt4 key购买 nike

Using Pandas documentation

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))
  1. 数据框
  2. 我希望百分比变化的窗口

它抛出错误

  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

最佳答案

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

关于python - 列值的 pct_change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36218337/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com