问题描述
我有一个股票/股票代码的价格历史数据框,有多个列,包括“Adj Close”。我正在创建一个新的数据框,其中包含该代码的每日百分比变化。 我希望新数据框中的列标题是“每日返回”,而不是“调整关闭”。我可以用 .rename 做到这一点。
在创建新数据框的语句中是否有更简洁的方法来执行此操作?
这是起始数据框:
print(daily_df)
输出:
Open High ... Adj Close Volume
Date ...
2002-12-30 875.400024 882.099976 ... 879.390015 1057800000
2002-12-31 879.390015 881.929993 ... 879.820007 1088500000
2003-01-02 879.820007 909.030029 ... 909.030029 1229200000
2003-01-03 909.030029 911.250000 ... 908.590027 1130800000
2003-01-06 908.590027 931.770020 ... 929.010010 1435900000
... ... ... ... ...
2010-12-27 1254.660034 1258.430054 ... 1257.540039 1992470000
2010-12-28 1259.099976 1259.900024 ... 1258.510010 2478450000
2010-12-29 1258.780029 1262.599976 ... 1259.780029 2214380000
2010-12-30 1259.439941 1261.089966 ... 1257.880005 1970720000
2010-12-31 1256.760010 1259.339966 ... 1257.640015 1799770000
[2017 rows x 6 columns]
这是创建每日百分比变化的新数据框:
daily_df = pd.DataFrame(history_df['Adj Close'].pct_change()[1:])
print(daily_df)
输出:
Adj Close
Date
2002-12-31 0.000489
2003-01-02 0.033200
2003-01-03 -0.000484
2003-01-06 0.022474
2003-01-07 -0.006545
...
2010-12-27 0.000613
2010-12-28 0.000771
2010-12-29 0.001009
2010-12-30 -0.001508
2010-12-31 -0.000191
[2016 rows x 1 columns]
使用 .rename 更改列名:
daily_df.rename(columns={'Adj Close': 'Daily Return'},inplace=True)
输出:
Daily Return
Date
2002-12-31 0.000489
2003-01-02 0.033200
2003-01-03 -0.000484
2003-01-06 0.022474
2003-01-07 -0.006545
...
2010-12-27 0.000613
2010-12-28 0.000771
2010-12-29 0.001009
2010-12-30 -0.001508
2010-12-31 -0.000191
[2016 rows x 1 columns]
但是,如果我尝试在创建新数据框期间定义列名:
daily_df = pd.DataFrame(history_df['Adj Close'].pct_change()[1:],['Daily Return'])
我收到此错误:
TypeError: Only valid with DatetimeIndex,timedeltaIndex or Periodindex,but got an instance of 'Index'
没有 .rename 有没有办法做到这一点?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)