首页 > 解决方案 > Pandas 将不同类型的多行转换为 1 行,每种类型多列

问题描述

鉴于以下情况df

Account contract_date   type    item_id quantity    price   tax net_amount
ABC123  2020-06-17  P   1409    1000    0.355   10  400
ABC123  2020-06-17  S   1409    2000    0.053   15  150
ABC123  2020-06-17  C   1409    500 0.25    5   180
ABC123  2020-06-17  S   1370    5000    0.17    30  900
DEF456  2020-06-18  P   7214    3000    0.1793  20  600

我想转df,按 Account、contract_date 和 item_id 分组。然后将不同类型的值拆分到不同的列中。预期结果如下。我可以用 for loop/apply 做到这一点,但想寻求关于 groupby 或 pivot 或任何矢量化/pythonic 解决方案的建议。预期结果如下:

Account contract_date   item_id quantity_P  quantity_S  quantity_C  price_P price_S price_C tax_P tax_S tax_C   net_amount_P    net_amount_S    net_amount_C
ABC123  2020-06-17  1409    1000    2000    500 0.355   0.053   0.25    10  15  5   400 150 180
ABC123  2020-06-17  1370    0   5000    0   0   0.17    0   0   30  0   0   900 0
DEF456  2020-06-18  7214    3000    0   0   0.1793  0   0   20  0   0   600 0   0

*虽然对齐看起来有点不对劲,但您可以复制df并使用df = pd.read_clipboard()来阅读表格。感谢你的帮助。谢谢你。

编辑:我正在使用的错误df.pivot(index=['Account', 'contract_date', 'item_id'], columns=['type'])

在此处输入图像描述

标签: pythonpandaspandas-groupby

解决方案


使用df.pivot

In [1660]: df.pivot(index=['Account', 'contract_date', 'item_id'], columns=['type'])
Out[1660]: 
                              quantity                 price                 tax             net_amount              
type                                 C       P       S     C       P      S    C     P     S          C      P      S
Account contract_date item_id                                                                                        
ABC123  2020-06-17    1370         NaN     NaN  5000.0   NaN     NaN  0.170  NaN   NaN  30.0        NaN    NaN  900.0
                      1409       500.0  1000.0  2000.0  0.25  0.3550  0.053  5.0  10.0  15.0      180.0  400.0  150.0
DEF456  2020-06-18    7214         NaN  3000.0     NaN   NaN  0.1793    NaN  NaN  20.0   NaN        NaN  600.0    NaN

推荐阅读