使用 pandas 数据透视索引作为列

Use the pandas pivot index as column

在下面的代码中,我使用索引 date 旋转数据框。在数据透视之后,我需要从列 date 中获取月份。这是我的尝试:

df = pd.DataFrame({
    'date' : [datetime(2021,3,11), datetime(2021,3,11), datetime(2021,3,11), 
              datetime(2021,3,12), datetime(2021,3,12), datetime(2021,3,12), 
              datetime(2021,3,13), datetime(2021,3,13), datetime(2021,3,13)],
    'field': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
    'value': [150, 140, 1, 130, 280, 2, 260, 120, 4]
})

print(df)


    date      field value
0   2021-03-11  A   150
1   2021-03-11  B   140
2   2021-03-11  C   1
3   2021-03-12  A   130
4   2021-03-12  B   280
5   2021-03-12  C   2
6   2021-03-13  A   260
7   2021-03-13  B   120
8   2021-03-13  C   4


df_pivoted = df.pivot(index='date', columns='field', values='value')
print(df_pivoted)

field       A     B   C
date            
2021-03-11  150  140  1
2021-03-12  130  280  2
2021-03-13  260  120  4

df_pivoted['month'] = df_pivoted['date'].apply(lambda x: x.month)

我收到错误消息,因为 date 字段不是列,但我需要使用它:

KeyError: 'date'

为什么我不能使用同时也是索引的列?

date是索引,所以你必须从索引中得到月份:

df_pivoted['month'] = df_pivoted.index.month

输出:

field         A    B  C  month
date                          
2021-03-11  150  140  1      3
2021-03-12  130  280  2      3
2021-03-13  260  120  4      3

另一种方式

先提取月份,设置索引,入栈和出栈

df['month']=df.date.dt.month
df.set_index(['date','field','month']).stack().unstack('field', 'month').droplevel(level=2).reset_index()df['month']=df.date.dt.month

df['month']=df.date.dt.month

df_pivoted = df.pivot(index=['date','month'], columns=['field'], values='value').reset_index()

两种情况的结果

field       date  month    A    B  C
0     2021-03-11      3  150  140  1
1     2021-03-12      3  130  280  2
2     2021-03-13      3  260  120  4