honeymoon
honeymoon

Reputation: 2520

Pandas all possible combinations of two columns

I have such a table:

    A    B   C 
1   1    2   3 
2   5    6   7 

I want to extract all combination with two columns as separate data frame:

    A    B   
1   1    2   
2   5    6

    A    C 
1   1    3 
2   5    7 

    B   C 
1   2   3 
2   6   7 

How to accomplish that?

Upvotes: 1

Views: 664

Answers (1)

jezrael
jezrael

Reputation: 862661

Use itertools.combinations in loop with DataFrame.loc:

from  itertools import combinations

for c in combinations(df.columns, 2):
    print (df.loc[:, c])
   A  B
1  1  2
2  5  6
   A  C
1  1  3
2  5  7
   B  C
1  2  3
2  6  7

If need list of DataFrames:

L = [df.loc[:, c] for c in combinations(df.columns, 2)]
print (L)
[   A  B
1  1  2
2  5  6,    A  C
1  1  3
2  5  7,    B  C
1  2  3
2  6  7]

Or dict of DataFrames:

d = {f'{"_".join(c)}': df.loc[:, c]for c in combinations(df.columns, 2)}
print (d)
{'A_B':    A  B
1  1  2
2  5  6, 'A_C':    A  C
1  1  3
2  5  7, 'B_C':    B  C
1  2  3
2  6  7}

Upvotes: 1

Related Questions