在Python Pivot表中需要帮助

时间:2018-11-21 06:51:17

标签: python pivot pandas-groupby

我有一个类似于以下结构的数据框: image1

我需要使其看起来像这样: image2

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您可以将groupby()函数与列表一起使用,并在agg()中附加汇总函数。

import pandas as pd


df = pd.DataFrame({'customer': [1,2,1,3,1,2,3], 
                   "group_code": ['111', '111', '222', '111', '111', '111', '333'],
                  "ind_code": ['A', 'B', 'AA', 'A', 'AAA', 'C', 'BBB'],
                  "amount": [100, 200, 140, 400, 225, 125, 600],
                  "card": ['XXX', 'YYY', 'YYY', 'XXX', 'XXX', 'YYY', 'XXX']})

df_groupby = df.groupby(['customer', 'group_code', 'ind_code']).agg(['count', 'mean'])