gpt4 book ai didi

python - 查找 Pandas 数据框中的所有重复行

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:24 26 4
gpt4 key购买 nike

我希望能够在事先不知道名称和列数的情况下获取数据集中重复行的所有实例的索引。所以假设我有这个:

     col
1 | 1
2 | 2
3 | 1
4 | 1
5 | 2

我希望能够得到 [1, 3, 4][2, 5]。有什么办法可以做到这一点?这听起来很简单,但由于我事先不知道这些列,所以我无法执行类似 df[col == x...] 的操作。

最佳答案

首先过滤所有duplicated行然后 groupby使用apply 或转换index to_series :

df = df[df.col.duplicated(keep=False)]

a = df.groupby('col').apply(lambda x: list(x.index))
print (a)
col
1 [1, 3, 4]
2 [2, 5]
dtype: object

a = df.index.to_series().groupby(df.col).apply(list)
print (a)
col
1 [1, 3, 4]
2 [2, 5]
dtype: object

如果需要嵌套列表:

L = df.groupby('col').apply(lambda x: list(x.index)).tolist()
print (L)
[[1, 3, 4], [2, 5]]

如果只需要使用第一列,可以使用 iloc 按位置选择:

a = df[df.iloc[:,0].duplicated(keep=False)]
.groupby(df.iloc[:,0]).apply(lambda x: list(x.index))
print (a)
col
1 [1, 3, 4]
2 [2, 5]
dtype: object

关于python - 查找 Pandas 数据框中的所有重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42903945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com