Python pandas groupby aggregate on multiple columns, then pivot

前端 未结 3 840
野性不改
野性不改 2020-12-13 10:08

In Python, I have a pandas DataFrame similar to the following:

Item | shop1 | shop2 | shop3 | Category
------------------------------------
Shoes| 45    | 50         


        
3条回答
  •  时光取名叫无心
    2020-12-13 10:32

    df.groupby('Category').agg({'Item':'size','shop1':['sum','mean','std'],'shop2':['sum','mean','std'],'shop3':['sum','mean','std']})
    

    Or if you want it across all shops then:

    df1 = df.set_index(['Item','Category']).stack().reset_index().rename(columns={'level_2':'Shops',0:'costs'})
    df1.groupby('Category').agg({'Item':'size','costs':['sum','mean','std']})
    

提交回复
热议问题