创建转置和分组矩阵数据帧

2024-09-30 14:19:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

对于每行的PUSH值(在本例中,我只有一个ID,但表中包含更多),我想创建第二个表(图中的黄色表)

那么目标是: 为每个商店创建新列(列出7 adh、ayc、maeg、rot、witz、mar、bud),每个商店将从推送列接收值

预期的结果是黄色表,我将把它添加到用于生成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个值

enter image description here


Tags: store名称iddftransformpush商店groupby
1条回答
网友
1楼 · 发布于 2024-09-30 14:19:09
# 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]

相关问题 更多 >