gpt4 book ai didi

python - Python Pandas 中的排列和组合

转载 作者:行者123 更新时间:2023-12-01 09:17:00 24 4
gpt4 key购买 nike

我想找到在 Pandas DataFrame 上进行搜索的最优化方式

例如

我想寻找值(value)

aaa = 9 in the dataframe df

df

  index Column  value
1 aaa 1
2 aaa 3
3 aaa 5
4 aaa -3
5 aaa 3
6 aaa 0

结果应该如下

Answer: Combinations of Index locations (1,2,3), (1,2,3,4,5),(1,2,3,6),(1,2,3,4,5,6), (1,3,5), (1,3,5,6) 

因为它们的总和为9

我避免对所有组合运行排列循环 n^n 次。任何捷径都将受到高度赞赏

最佳答案

这是使用 itertools.combinations 的强力方法。您可以使用生成器进行优化,并在值总计超过 9 时停止求和。

from itertools import combinations

d = df.set_index('index')['value'].to_dict()

n = len(d)
res = [i for j in range(n) for i in combinations(d, j) if sum(map(d.get, i)) == 9]

print(res)

[(1, 2, 3), (1, 3, 5), (1, 2, 3, 6), (1, 3, 5, 6), (1, 2, 3, 4, 5)]

关于python - Python Pandas 中的排列和组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51155238/

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