Python Pandas Dataframe 将特定日期时间行标签设置为索引中的字符串?

Python Pandas Dataframe Set specific datetime row label to string in index?

我的 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

这是一种方法:

In [154]: %paste
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'

## -- End pasted text --

In [155]: df = df.reset_index()

In [156]: df['Date'] = df['Date'].astype(object)

In [157]: df['Date'] = df.Date.dt.date

In [158]: df.ix[3,0] = 'Total'

In [159]: df.index = df.Date

In [160]: df.drop(['Date'], axis=1, inplace=True)

In [161]: df
Out[161]: 
            Clicks  Impressions
Date                           
2015-06-01    3128        92964
2015-06-08    3131        91282
2015-06-15    2580        88143
Total         8839       272389

问题在于试图处理同一数组中的多种数据类型。您需要将该系列转换为 object 类型。

几年后,事后看来,我在解决这个问题时并不知道 Pandas pivot table 有一个 margins 参数,可以添加像 "total" 这样的标签并提供总计行。

df.head(3).pivot_table(['Impressions', 'Clicks'], index=df.index[:-1],
                       aggfunc='sum', margins=True, margins_name='Total')

                     Clicks  Impressions
Date                                    
2015-06-01 00:00:00    3128        92964
2015-06-08 00:00:00    3131        91282
2015-06-15 00:00:00    2580        88143
Total                  8839       272389

但要更准确地回答“如何将特定标签分配给特定行的日期时间索引”的问题,您基本上不能,因为整个索引是DatetimeIndex 的数据类型,因此所有元素都必须是这种类型。

要解决这个问题,您可以这样做:

idx = df.index.strftime('%Y-%m-%d')
idx.values[-1] = 'Total'
df.index = idx

结果

            Impressions  Clicks
2015-06-01        92964    3128
2015-06-08        91282    3131
2015-06-15        88143    2580
Total            272389    8839