gpt4 book ai didi

python - 在 pandas DataFrame 中查找重复行的索引

转载 作者:太空狗 更新时间:2023-10-29 21:30:33 25 4
gpt4 key购买 nike

pandas 在给定 DataFrame 中查找相同行的索引而不迭代单个行的方法是什么?

虽然可以使用 unique = df[df.duplicated()] 找到所有唯一行,然后使用 unique.iterrows() 迭代唯一条目并借助 pd.where() 提取相等条目的索引,pandas 的做法是什么?

示例:给定以下结构的 DataFrame:

  | param_a | param_b | param_c
1 | 0 | 0 | 0
2 | 0 | 2 | 1
3 | 2 | 1 | 1
4 | 0 | 2 | 1
5 | 2 | 1 | 1
6 | 0 | 0 | 0

输出:

[(1, 6), (2, 4), (3, 5)]

最佳答案

使用参数duplicated对所有重复行使用 keep=False 然后按所有列进行 groupby 并将索引值转换为元组,最后将输出 Series 转换为 列表:

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

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

如果您还想查看重复值:

df1 = (df.groupby(df.columns.tolist())
.apply(lambda x: tuple(x.index))
.reset_index(name='idx'))
print (df1)
param_a param_b param_c idx
0 0 0 0 (1, 6)
1 0 2 1 (2, 4)
2 2 1 1 (3, 5)

关于python - 在 pandas DataFrame 中查找重复行的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629518/

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