Python:如何更改设置为索引的 pandas 中的日期

标签 python pandas datetime

我需要将最后日期设置为今天日期。示例: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/

相关文章:

python - 使用 "Pandas"和 "Seaborn"在 PyCharm 中键入错误

python - 如何用最常见的值替换 pandas 列的值

java - 用Java计算时差

sql - 在 SQL Server 中获取日期范围内的所有日期

python - 如何静态加载 python 模块(如 scipy)?

python - Python中的中餐厅流程实现

python - 使用 beautifulsoup 高效解析字符串

python - 在 Python 中熔化和旋转数据框?

datetime - Snowflake 外部表无法将变量值 NULL 转换为 DATETIME/TIMESTAMP_NTZ 类型

python - 如何在 Python 中使用列名检索 SQL 结果列值?