我需要将最后日期设置为今天日期。示例:2016-05-18 至 2017-06-05。
但是,当我执行 df.index[-1] = Today
时,它会返回此错误
类型错误:索引不支持可变操作
>>> today
0 2017-06-05
Name: trading_day, dtype: datetime64[ns]
Stock Open High Low Close Adj Close Volume
Date
2016-05-13 AAD 5.230000 5.260000 5.200000 5.260000 5.260000 5000
2016-05-16 AAD 5.220000 5.260000 5.220000 5.260000 5.260000 6000
2016-05-17 AAD 5.210000 5.260000 5.210000 5.260000 5.260000 2000
2016-05-18 AAD 5.200000 5.250000 5.200000 5.250000 5.250000 3000
>>> df.index[-1] = today
TypeError: Index does not support mutable operations
我需要的是
Stock Open High Low Close Adj Close Volume
Date
2016-05-13 AAD 5.230000 5.260000 5.200000 5.260000 5.260000 5000
2016-05-16 AAD 5.220000 5.260000 5.220000 5.260000 5.260000 6000
2016-05-17 AAD 5.210000 5.260000 5.210000 5.260000 5.260000 2000
2017-06-05 AAD 5.200000 5.250000 5.200000 5.250000 5.250000 3000
仅更改最后日期。
最佳答案
您可以使用重命名
df.rename({df.index[-1]: 'today'}, inplace = True)
你得到了
Stock Open High Low Close Adj Close.1 Volume
Date
2016-05-13 AAD 5.23 5.26 5.20 5.26 5.26 5000
2016-05-16 AAD 5.22 5.26 5.22 5.26 5.26 6000
2016-05-17 AAD 5.21 5.26 5.21 5.26 5.26 2000
today AAD 5.20 5.25 5.20 5.25 5.25 3000
将代码更改为
import datetime as dt
df.rename({df.index[-1]: dt.date.today()}, inplace = True)
你会得到
Stock Open High Low Close Adj Close.1 Volume
Date
2016-05-13 AAD 5.23 5.26 5.20 5.26 5.26 5000
2016-05-16 AAD 5.22 5.26 5.22 5.26 5.26 6000
2016-05-17 AAD 5.21 5.26 5.21 5.26 5.26 2000
2016-06-05 AAD 5.20 5.25 5.20 5.25 5.25 3000
关于Python:如何更改设置为索引的 pandas 中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44370063/