Pandas, k of n combinations with product sum

Viewed 52

this is my dummy df:

     A    B   C    D    E
0  0.4  0.3  0.5  0.2  0.5
1  0.2  0.6  0.4  0.1  0.8

I want to pick 3 out of 5 columns and calculate the product of them. Like row 0: A x B x C = 0.06 and A x B x D = 0.024 and so on... Therer are 10 different kombinations of picking 3 out of 5, and i want to get the sum of all product calclulations. Is there a way to to this i Pandas?

1 Answers

Use list comprehnsion with DataFrame.prod, rename each Series and join by concat:

from  itertools import combinations

df1 = pd.concat([df[list(x)].prod(axis=1).rename('_'.join(x)) 
                                 for x in combinations(df.columns, 3)], axis=1)
print (df1)
   A_B_C  A_B_D  A_B_E  A_C_D  A_C_E  A_D_E  B_C_D  B_C_E  B_D_E  C_D_E
0  0.060  0.024  0.060  0.040  0.100  0.040  0.030  0.075  0.030  0.050
1  0.048  0.012  0.096  0.008  0.064  0.016  0.024  0.192  0.048  0.032

EDIT: If want filter columns names and specify in list:

from  itertools import combinations

cols = ['B','C','D','E']
df1 = pd.concat([df[list(x)].prod(axis=1).rename('_'.join(x)) 
                                 for x in combinations(cols, 3)], axis=1)
print (df1)
   B_C_D  B_C_E  B_D_E  C_D_E
0  0.030  0.075  0.030  0.050
1  0.024  0.192  0.048  0.032
Related