gpt4 book ai didi

python - 如何计算所有可能的列组合的总和

转载 作者:行者123 更新时间:2023-12-05 03:18:00 25 4
gpt4 key购买 nike

我有以下 df:

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

enter image description here

我想生成这 4 列的总计组合,等于 4 x 3 x 2 = 24 总组合减去重复项。我想要相同 df 中的结果。

我想要这样的东西(显示部分结果):

enter image description here

a_b 的组合与 b_a 相同,因此我不想要这样的计算,因为它是重复的。

有没有办法计算所有的组合并排除重复的总数?

最佳答案

import itertools as it

orig_cols = df.columns
for r in range(2, df.shape[1] + 1):
for cols in it.combinations(orig_cols, r):
df["_".join(cols)] = df.loc[:, cols].sum(axis=1)

需要一些循环,但不是在数据帧本身上,而是在组合上。我们得到列名的第 2、3、...、N-1 种组合,其中 N 是列数。然后形成新的 _-joined 列作为总和。

In [11]: df
Out[11]:
a b c d a_b a_c a_d b_c b_d c_d a_b_c a_b_d a_c_d b_c_d a_b_c_d
0 1 3 1 3 4 2 4 4 6 4 5 7 5 7 8
1 2 4 2 2 6 4 4 6 6 4 8 8 6 8 10
2 3 1 3 4 4 6 7 4 5 7 7 8 10 8 11
3 4 0 1 1 4 5 5 1 1 2 5 5 6 2 6
4 2 4 0 4 6 2 6 4 8 4 6 10 6 8 10

关于python - 如何计算所有可能的列组合的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73872851/

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