枢轴类别栏

时间:2019-10-22 15:44:56

标签: python pandas

数据框

import pandas as pd
df = pd.DataFrame({'date':['2015-01-01','2015-01-01','2015-01-01','2015-0101','2015-01-02','2015-01-02','2015-01-02','2015-01-02'],
                  'id':[1,1,2,2,1,1,2,2],
                  'kind':['min','max','min','max','min','max','min','max'],
                  'values':[1,2,3,4,5,6,7,8]})
print(df)
    date        id kind  values
0  2015-01-01   1  min       1
1  2015-01-01   1  max       2
2  2015-01-01   2  min       3
3  2015-01-01   2  max       4
4  2015-01-02   1  min       5
5  2015-01-02   1  max       6
6  2015-01-02   2  min       7
7  2015-01-02   2  max       8

包含日期和ID的每种(唯一)组合的最小值和最大值。

如何旋转种类列,以使结果数据框看起来像

   date        id min max  
0  2015-01-01   1  1  2
1  2015-01-01   2  3  4
2  2015-01-02   1  5  6
3  2015-01-02   2  7  8

df.pivot(columns='kind')无法产生理想的结果。

1 个答案:

答案 0 :(得分:2)

您可以尝试

df.set_index(['date','id','kind'])['values'].unstack().reset_index()
Out[94]: 
kind        date  id  max  min
0     2015-01-01   1    2    1
1     2015-01-01   2    4    3
2     2015-01-02   1    6    5
3     2015-01-02   2    8    7

df.pivot_table(index=['date','id'],columns='kind',values='values')