英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论