首页 > 解决方案 > 创建转置和 GroupBy 矩阵数据框 Python Pandas

问题描述

我有下表,其中列名 ID、STORE 和 PUSH 可用。

使用每一行的 PUSH 值(在这种情况下,我只有一个 ID,但表包含更多),我想创建第二个表(图中的黄色)。

那么目标是:为每个 STORE(列出 7 adh,ayc,maeg,rot,witz,mar,bud)创建新列,其中每个商店将接收来自 PUSH 列的值。

预期的结果是我将添加到用于生成 ID、STORE、PUSH 表的同一数据框中的黄色表。

任何帮助将不胜感激!

the code I tried was:
df['ADH'] = combined_sf2.groupby('PNO') 
['Push'].transform() 
df['AYC'] = combined_sf2.groupby('PNO') 
['Push'].transform()
df['ADH'] = combined_sf2.groupby('PNO') 
['Push'].transform()
df['MAEG'] = combined_sf2.groupby('PNO') 
['Push'].transform()
df['ROT'] = combined_sf2.groupby('PNO') 
['Push'].transform()
df['WITZ'] = combined_sf2.groupby('PNO') 
['Push'].transform()
df['BUD'] = combined_sf2.groupby('PNO') 
['Push'].transform()
df['MAR'] = combined_sf2.groupby('PNO') 
['Push'].transform()

但是只为所有行重新调整 1 个值

在此处输入图像描述

标签: pythonpandastransformtranspose

解决方案


# pivot to get the right table format (ID as index, STORE as column
# and PUSH as values).
# the second part (with the loc) is here to repeat the lines according
# to each ID.

pd.pivot(df, index='ID', columns='STORE', values='PUSH').loc[df.ID]

推荐阅读