如何获取一列中所有唯一的值组合,这些值在另一列中

How to get all unique combinations of values in one column that are in another column

从这样的数据框开始:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['a', 'b', 'b', 'b', 'a']})
   A  B
0  1  a
1  2  b
2  3  b
3  4  b
4  5  a

获取这样的数据框的最佳方式是什么?

pd.DataFrame({'source': [1, 2, 2, 3], 'target': [5, 3, 4, 4]})
   source  target
0       1       5
1       2       3
2       2       4
3       3       4

每当 A 列中的一行在 B 列中的值与 A 列中的另一行的值相同时,我想将该关系的唯一实例保存在新数据框中。

这非常接近:

df.groupby('B')['A'].unique()
B
a       [1, 5]
b    [2, 3, 4]
Name: A, dtype: object

但我现在最好将其转换为单个数据帧,我的大脑已经崩溃了。

在你的情况下,你可以itertools.combinations

import itertools
s = df.groupby('B')['A'].apply(lambda x : set(list(itertools.combinations(x, 2)))).explode().tolist()
out = pd.DataFrame(s,columns=['source','target'])
out
Out[312]: 
   source  target
0       1       5
1       3       4
2       2       3
3       2       4

使用合并功能

df.merge(df, how = "outer", on = ["B"]).query("A_x < A_y")