panda在groupby之后将列转换为新行

2024-10-03 23:26:42 发布

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

我有一个熊猫数据帧。我需要把一些列转换成行。数据帧的前两列中每3行有相同的数据。所以,我还需要6列,正如您在预期的数据帧中看到的那样。 我有以下数据帧:

shopCode    Product   Code  Score
    111      Apple    123    0.70
    111      Apple    456    0.75
    111      Apple    789    0.80
    222      Orange   142    0.66
    222      Orange   136    0.83
    222      Orange   623    0.76

我期望的数据帧是:

^{pr2}$

我试着用 df.pivot(index=['shopCode', 'Product'], columns=['Code1', 'Code2', 'Code3', 'Score1', 'Score2', 'Score3'], values=['Code', 'Score']) 但它不起作用。在


Tags: columns数据appledfindexcodeproductpivot
2条回答

可以通过pandas groupby和字典合并实现。在

df.groupby(['shopCode', 'Product']).apply(lambda x: pd.Series(
                               {
                                **{'Code'+str(i+1): t for i,t in enumerate(x.Code)},
                                **{'Score'+str(i+1): t for i,t in enumerate(x.Score)}
                               }
                             )).reset_index()

我们使用pivot_table

df=pd.pivot_table(df,index=['shopCode','Product'],columns=df.groupby(['shopCode','Product']).cumcount().add(1),values=['Code','Score'],aggfunc='sum')
df.columns=df.columns.map('{0[0]}{0[1]}'.format) 
df
Out[112]: 
                  Code1  Code2  Code3  Score1  Score2  Score3
shopCode Product                                             
111      Apple      123    456    789    0.70    0.75    0.80
222      Orange     142    136    623    0.66    0.83    0.76

reset_index之后

^{pr2}$

相关问题 更多 >