gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:01:37 25 4
gpt4 key购买 nike

从这样的数据框开始:

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

关于python - 如何获取一列中所有唯一的值组合,这些值在另一列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70536663/

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