pandas 如何在单个数据框中合并具有相同索引的行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33424203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to merge rows with same index on a single data frame?
提问by ChiefsCreation
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
And I want this to become:
我希望这变成:
A B C
1 1234,2345 Win
2 1987 Loss
3 3456,4567 Win
Note: C values always have the same value for the same index.
注意:对于相同的索引,C 值始终具有相同的值。
Anyone can help? Thanks!
任何人都可以帮忙吗?谢谢!
回答by EdChum
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:
您可以groupby
在 'A' 和 'C' 上看到它们的关系是相同的,将 'B' 列转换为 str 并join
使用逗号:
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