按列的值映射 Pandas 数据框中的重复行?

Map duplicate rows in Pandas dataframe by vlalue of a column?

在具有 2 列的数据框中 [id][string],我需要根据列 [string] 的值知道哪些行与哪些行重复。 我的数据框有数千行但只有 2 列。

输入数据帧的样本:

id,string
0,"A B C D"
1,"D B C D E Z"
2,"A B C D"
3,"Z Z Z Z Z Z Z Z Z Z Z Z"
4,"D B C D E Z"
5,"A B C D"

在此示例中,第 0、2、5 行彼此重复。此外,行 1 和 4 彼此重复。 (id 是唯一的)

我想要以下输出:

[["0","2","5"]],["1","4"]]

我会使用 groupby 和 listcomp。

>>> df
   id                   string
0   0                  A B C D
1   1              D B C D E Z
2   2                  A B C D
3   3  Z Z Z Z Z Z Z Z Z Z Z Z
4   4              D B C D E Z
5   5                  A B C D
>>>
>>> [l for l in df.groupby('string')['id'].apply(list) if len(l) > 1]
[[0, 2, 5], [1, 4]]

如果您确实需要结果中的字符串,请使用

>>> [[str(x) for x in l] for l in df.groupby('string')['id'].apply(list) if len(l) > 1]
[['0', '2', '5'], ['1', '4']]

您可以在聚合 list per string in boolean indexing with Series.str.len 后按列表长度过滤:

s = df.assign(id = df['id'].astype(str)).groupby('string')['id'].apply(list)
out = s[s.str.len().gt(1)].tolist()

如果已经 id 是字符串:

s =  df.groupby('string')['id'].apply(list)
out = s[s.str.len().gt(1)].tolist()

另一个选项正在使用 duplicated:

>>> df[df.duplicated('string',False)].groupby('string')['id'].apply(lambda x: x.astype(str).tolist()).tolist()

# [['0', '2', '5'], ['1', '4']]

如果不需要更改 'id' 类型:

>>> df[df.duplicated('string',False)].groupby('string')['id'].apply(list).tolist()

# [[0, 2, 5], [1, 4]]