按列中的唯一值分组,并将同一行中的数据连接起来。

huangapple go评论47阅读模式
英文:

Groupby unique value in column, and join data in same row

问题

我有这种类型的数据框:

我想按ID分组,并将所有下一列的信息放入同一行中,当然每个单元格都是这样的,并且如果有更多唯一值的行,就添加更多的包装:

到目前为止,我可以将所有其他列都放在一个列表中,但想按照第二张图片的顺序进行排列

df1 = df.groupby('ID').agg({'Grade':lambda x:list(np.r_[x])})

感谢帮助

英文:

I have this kind of dataframe:

按列中的唯一值分组,并将同一行中的数据连接起来。

I want to groupby ID and get all the next columns info into the same row, and of course in each cell like this and add more packs if there are more rows for unique values:

按列中的唯一值分组,并将同一行中的数据连接起来。

so far i can get all other columns in just one as list, but would like to be in proper order like second picture

df1 = df.groupby('ID').agg({'Grade':lambda x:list(np.r_[x])})

thanks for the help

答案1

得分: 0

尝试类似这样的代码:

df_out = (dfm := (df.set_index(['Name', 'ID', df.groupby('Name').cumcount()])
                 .unstack()
                 .sort_index(level=1, axis=1)))\
       .set_axis([f'{i}_{j}' for i,j in dfm.columns], axis=1)\
       .reset_index()

输出

          Name    ID Class_0  Grade_0  Score_0 Class_1  Grade_1  Score_1 Class_2  Grade_2  Score_2 Class_3  Grade_3  Score_3
    0  Gustavo  2222      LB      2.0     80.0      HD      3.0     90.0      CF      4.0     70.0     NaN      NaN      NaN
    1    Maria  3333      AD      3.0     70.0      KD      4.0     70.0      LB      5.0     70.0      CF      7.0     80.0
英文:

Try something like this:

df_out = (dfm := (df.set_index(['Name', 'ID', df.groupby('Name').cumcount()])
             .unstack()
             .sort_index(level=1, axis=1)))\
   .set_axis([f'{i}_{j}' for i,j in dfm.columns], axis=1)\
   .reset_index()

Output:

      Name    ID Class_0  Grade_0  Score_0 Class_1  Grade_1  Score_1 Class_2  Grade_2  Score_2 Class_3  Grade_3  Score_3
0  Gustavo  2222      LB      2.0     80.0      HD      3.0     90.0      CF      4.0     70.0     NaN      NaN      NaN
1    Maria  3333      AD      3.0     70.0      KD      4.0     70.0      LB      5.0     70.0      CF      7.0     80.0

huangapple
  • 本文由 发表于 2023年5月15日 05:26:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定