gpt4 book ai didi

python - 使用 Pandas 检查 2 个系列中的一对值的最有效方法?

转载 作者:行者123 更新时间:2023-11-28 21:11:21 24 4
gpt4 key购买 nike

假设我有一个系列/数据框 A 看起来像

A = [3,2,1,5,4,...

A 也可以排序,因为这对我来说无关紧要。我想创建一个新系列来跟踪可能的配对。也就是说,我希望结果看起来像

B = [3_1, 3_2, 3_4, ..., 2_1, 2_4, ..., 1_4, 1_5,...

也就是说,我想排除 2_3,因为 3_2 已经存在。我想我可以使用类似

的方法在 B 中创建每个元素
for i in A:
for j in A:
s = A[i].astype(str) + '_' + A[j].astype(str)
B.append(pd.Series([s]))

但我不确定如何确保 (i,j) 配对不存在,例如确保 2_3 没有像我上面提到的那样被添加

处理此问题的最有效方法是什么?

最佳答案

from itertools import combinations

s = pd.Series([1, 2, 3, 4])
s2 = pd.Series("_".join([str(a), str(b)]) for a, b in combinations(s, 2))

>>> s2
0 1_2
1 1_3
2 1_4
3 2_3
4 2_4
5 3_4
dtype: object

关于python - 使用 Pandas 检查 2 个系列中的一对值的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35493105/

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