[英]Python: Replace datetime64[ns] into a index in pandas
I want to replace the last Date (which is index) from 2017-06-18
to date_replace
which is in datetime64 format. 我想将
2017-06-18
的最后一个Date(即索引) 2017-06-18
为datetime64格式的date_replace
。 However, I get error when I replace it, the code is as below: 但是,替换时出现错误,代码如下:
>>> 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'
The output I want: 我想要的输出:
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
SO how to replace the date elegantly with no error and same format? 那么如何优雅地替换日期而没有错误和相同的格式?
use pd.DataFrame.rename
. 使用
pd.DataFrame.rename
。 You can pass a dictionary to the index
parameter to specify which indices get renamed to what. 您可以将字典传递给
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.