簡體   English   中英

如何計算所有可能的列組合的總數

[英]How to calculate totals of all possible combinations of columns

我有以下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]})

在此處輸入圖像描述

我想從這 4 列中生成總計的組合,等於 4 x 3 x 2 = 24 個總計組合減去重復項。 我想要相同的df中的結果。

我想要看起來像這樣的東西(顯示部分結果):

在此處輸入圖像描述

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)

需要一些循環,但不是在 dataframe 本身上,而是在組合上。 我們得到 2, 3, ..., N-1'th 列名組合,其中 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM