[英]How to get index for all the duplicates in a dataframe (pandas - python)
我有一个包含多列的数据框,我想在其中一些列中找到重复项。 我的列从A到Z.我想知道哪些行在A,D,F,K,L和G列中具有相同的值。
我试过了:
df = df[df.duplicated(keep=False)]
df = df.groupby(df.columns.tolist()).apply(lambda x: tuple(x.index)).tolist()
但是,这会使用所有列。
我也试过了
print(df[df.duplicated(['A', 'D', 'F', 'K', 'L', 'P'])])
这只返回重复的索引。 我希望两行的索引具有相同的值。
你的最后一次尝试很接近。 不要使用所有列进行分组,只需使用您要考虑的列表:
df = pd.DataFrame({'A': [1, 1, 1, 2, 2, 2],
'B': [3, 3, 3, 4, 4, 5],
'C': [6, 7, 8, 9, 10, 11]})
res = df.groupby(['A', 'B']).apply(lambda x: (x.index).tolist()).reset_index()
print(res)
# A B 0
# 0 1 3 [0, 1, 2]
# 1 2 4 [3, 4]
# 2 2 5 [5]
groupby
不同布局
df.index.to_series().groupby([df['A'],df['B']]).apply(list)
Out[449]:
A B
1 3 [0, 1, 2]
2 4 [3, 4]
5 [5]
dtype: object
你可以让.groupby
返回一个dict
,键是组标签(多列的元组),值是索引
df.groupby(['A', 'B']).groups
#{(1, 3): Int64Index([0, 1, 2], dtype='int64'),
# (2, 4): Int64Index([3, 4], dtype='int64'),
# (2, 5): Int64Index([5], dtype='int64')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.