如何在单个数据帧上合并具有相同索引的行? [英] How to merge rows with same index on a single data frame?

查看:34
本文介绍了如何在单个数据帧上合并具有相同索引的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

I have a dataframe that looks like this:

A          B           C
1          1234        Win
1          2345        Win
2          1987        Loss
3          3456        Win
3          4567        Win

我希望它成为:

A          B           C
1          1234,2345   Win
2          1987        Loss
3          3456,4567   Win

注意:对于相同的索引,C值始终具有相同的值.

Note: C values always have the same value for the same index.

任何人都可以帮忙吗?谢谢!

Anyone can help? Thanks!

推荐答案

您可以在'A'和'C'上groupby看到它们的关系相同,将'B'列强制转换为str和join加上逗号:

You can groupby on 'A' and 'C' seeing as their relationship is the same, cast the 'B' column to str and join with a comma:

In [23]:
df.groupby(['A','C'])['B'].apply(lambda x: ','.join(x.astype(str))).reset_index()

Out[23]:
   A     C          B
0  1   Win  1234,2345
1  2  Loss       1987
2  3   Win  3456,4567

这篇关于如何在单个数据帧上合并具有相同索引的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆