将具有相同值的多行合并为pandas中的一行

Posted

技术标签:

【中文标题】将具有相同值的多行合并为pandas中的一行【英文标题】:Merge multiple rows with same value into one row in pandas 【发布时间】:2016-01-07 12:27:12 【问题描述】:

我看到有类似的问题,但答案并不完全符合我的确切需求。我有一个数据框,其中包含具有不同值的行。然而,一些行具有完全相同的值。

     Column1 Column2 Column3
0       a       x       x
1       a       x       x
2       a       x       x
3       d       y       y
4       d       y       y

我想要的是:

     Column1 Column2 Column3
0       a       x       x
1       d       y       y

所以基本上我想将所有列中具有相同值的所有行合并为一行。在 python 中最体面的方法是什么?

提前谢谢你!

【问题讨论】:

【参考方案1】:

致电drop_duplicates:

In [214]:
df.drop_duplicates()

Out[214]:
  Column1 Column2 Column3
0       a       x       x
3       d       y       y

【讨论】:

以上是关于将具有相同值的多行合并为pandas中的一行的主要内容,如果未能解决你的问题,请参考以下文章