Python:将datetime64 [ns]替换为pandas中的索引

时间:2017-06-06 03:57:42

标签: python pandas datetime dataframe

我想将2017-06-18的最后一个日期(索引)替换为datetime64格式的date_replace。但是,当我更换它时出现错误,代码如下:

>>> date_replace
0   2017-06-19
Name: trading_day, dtype: datetime64[ns]


           Stock      Open      High       Low     Close Adj Close  Volume
Date                                                                      
2017-06-13   AD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2017-06-16   AD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2017-06-17   AD  5.210000  5.560000  5.210000  5.560000  5.560000    200
2017-06-18   AD  5.200000  5.250000  5.200000  5.250000  5.250000    9000  

>>> df.index[-1] = date_replace
TypeError: Index does not support mutable operations

>>> import datetime
>>> df.rename({df.index[-1]: datetime.date.date_replace()}, inplace = True)
AttributeError: type object 'datetime.date' has no attribute 'date_replace'

我想要的输出:

           Stock      Open      High       Low     Close Adj Close  Volume
Date                                                                      
2017-06-13   AD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2017-06-16   AD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2017-06-17   AD  5.210000  5.560000  5.210000  5.560000  5.560000    200
2017-06-19   AD  5.200000  5.250000  5.200000  5.250000  5.250000    9000  

那么如何优雅地更换日期,没有错误和格式相同?

1 个答案:

答案 0 :(得分:3)

使用pd.DataFrame.rename。您可以将字典传递给index参数,以指定将哪些索引重命名为什么。

df.rename(index={df.index[-1]: date_replace[0]})

           Stock  Open  High   Low  Close  Adj Close  Volume
Date                                                        
2017-06-13    AD  5.23  5.26  5.20   5.26       5.26    5000
2017-06-16    AD  5.22  5.26  5.22   5.26       5.26    6000
2017-06-17    AD  5.21  5.56  5.21   5.56       5.56     200
2017-06-19    AD  5.20  5.25  5.20   5.25       5.25    9000

​