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

时间:2015-06-23 17:23:05

标签: python datetime indexing pandas dataframe

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

2 个答案:

答案 0 :(得分:1)

这是一种方法:

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类型。

答案 1 :(得分:0)

几年后,事后看来,我在不知道Pandas数据透视表有一个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

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

要解决这个问题,您可以执行以下操作:

DatetimeIndex

结果

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