简体   繁体   English

将 pandas group by 从行格式更改为列格式

[英]Change pandas group by from row to column format

My grouped data looks like我的分组数据看起来像

df.groupby(['product', 'quarter']).agg('total_amount':'sum','unit_sold' : 'count' )
product quarter total_amount  unit_sold
A1      Q1      100           7
        Q2      250           11
B1      Q1      300           17
        Q2       50           6
C1      Q1      750           80
        Q2      900           80

I want to extract grouped data in below format我想提取以下格式的分组数据

quater           Q1                       Q2
product total_amount  unit_sold   total_amount  unit_sold
A1              10       7             250         11
B1              300      17             50          6
C1              750      80            900         80

Kindly assist me by changing output format.请通过更改 output 格式来帮助我。

You want to unstack your data:你想解开你的数据:

(df
 .groupby(['product', 'quarter'])
 .agg('total_amount':'sum','unit_sold' : 'count' )
 .unstack(level=-1))

Read more detail here: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html在此处阅读更多详细信息: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html

Let us do unstack with swaplevel and sort_index让我们使用unstackswaplevel进行sort_index

#df1=df.groupby(['product', 'quarter']).agg('total_amount':'sum','unit_sold' : 'count' )

s=df1.unstack().swaplevel(0,1,axis=1).sort_index(level=0,axis=1)
Out[20]: 
quarter           Q1                     Q2          
        total_amount unit_sold total_amount unit_sold
product                                              
A1               100         7          250        11
B1               300        17           50         6
C1               750        80          900        80

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM