tumbleweed
tumbleweed

Reputation: 4630

How to create all possible combinations of pandas columns?

Consider the following pandas DF:

col1 col2 col3
1    3     1
2    4     2
3    1     3
4    0     1
2    4     0
3    1     5

How can I create all the possible combination sums of all the values of each pandas dataframe? For example:

col1 col2 col3 col1_col2 col1_col3 col2_col3
1    3     1       4        2        4   
2    4     2       6        4        6
3    1     3       4        6        4
4    0     1       4        5        1
2    4     0       6        2        4
3    1     5       4        8        6

Any idea of how to get all the possible sum/column combinations values in new columns?

Upvotes: 4

Views: 535

Answers (1)

jezrael
jezrael

Reputation: 862511

Use itertools.combinations with f-strings for format of new columns names:

from  itertools import combinations

for i, j in combinations(df.columns, 2):
    df[f'{i}_{j}'] = df[i] + df[j]

print (df)
   col1  col2  col3  col1_col2  col1_col3  col2_col3
0     1     3     1          4          2          4
1     2     4     2          6          4          6
2     3     1     3          4          6          4
3     4     0     1          4          5          1
4     2     4     0          6          2          4
5     3     1     5          4          8          6

Solution with list comprehension, concat and DataFrame.join for append to original:

dfs = [(df[i] + df[j]).rename(f'{i}_{j}') for i, j in combinations(df.columns, 2)]
df = df.join(pd.concat(dfs, axis=1))
print (df)
   col1  col2  col3  col1_col2  col1_col3  col2_col3
0     1     3     1          4          2          4
1     2     4     2          6          4          6
2     3     1     3          4          6          4
3     4     0     1          4          5          1
4     2     4     0          6          2          4
5     3     1     5          4          8          6

Upvotes: 4

Related Questions