【发布时间】:2015-09-09 15:27:35
【问题描述】:
我的 Pandas 数据框代码
import pandas as pd
df = pd.DataFrame({'Impressions': [92964, 91282, 88143,272389], 'Clicks': [3128, 3131, 2580, 8839]}, index=pd.to_datetime(['6/1/2015', '6/8/2015', '6/15/2015', '1/1/2020']))
df.index.name = 'Date'
生产
Clicks Impressions
Date
2015-06-01 3128 92964
2015-06-08 3131 91282
2015-06-15 2580 88143
2020-01-01 8839 272389
如何将2020-01-01 更改为显示Total 的字符串?
我想要实现的是:
Clicks Impressions
Date
2015-06-01 3128 92964
2015-06-08 3131 91282
2015-06-15 2580 88143
Total 8839 272389
更多上下文
df.index.dtype 的数据类型为 dtype('<M8[ns]')
我想我可以通过这个df.index[-1] 访问索引行标签,它告诉我这是一个Timestamp('2020-01-01 00:00:00')。
但是如果我尝试做这样的事情,它就行不通:
df.index[-1] = 'Total'
错误:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
df.index[-1] = 'Total'
File "C:\Python34\lib\site-packages\pandas\core\index.py", line 922, in __setitem__
raise TypeError("Indexes does not support mutable operations")
TypeError: Indexes does not support mutable operations
【问题讨论】:
-
这个帖子好像有你要找的东西:stackoverflow.com/questions/19851005/…
-
感谢您的提示。最终,
df.rename(index={df.index[-1]: 'Total'})确实将我在问题中发布的示例数据的索引值更改为Total。但是,当我尝试在我正在开发的主要应用程序中使用它时,它对我不起作用。我认为@bleh 是正确的,问题是在同一个数组中处理多种数据类型。不过还是谢谢。
标签: python datetime indexing pandas dataframe