Home > Enterprise >  Set to Set cross join conversion
Set to Set cross join conversion

Time:10-25

I was trying to find cross join of two set. I am currently doing the code below:

import itertools
a={1,2,3}
b={4,5,6}
itertools.product(a,b)
list(itertools.product(a,b))

itertools.product(b,a)
list(itertools.product(b,a))

Is there any other way to find out all possible cross join in a single code? and i need to convert the output to data frame?

CodePudding user response:

You need to compute both products separately, you can chain them using itertools for efficiency:

out = pd.DataFrame(itertools.chain(itertools.product(a,b),
                                   itertools.product(b,a)),
                    columns=['a', 'b'])

Output:

    a  b
0   1  4
1   1  5
2   1  6
3   2  4
4   2  5
5   2  6
6   3  4
7   3  5
8   3  6
9   4  1
10  4  2
11  4  3
12  5  1
13  5  2
14  5  3
15  6  1
16  6  2
17  6  3

CodePudding user response:

Use:

df = pd.DataFrame(list(itertools.product(a,b))   list(itertools.product(b,a)), 
                  columns=['a','b'])

print (df)
    a  b
0   1  4
1   1  5
2   1  6
3   2  4
4   2  5
5   2  6
6   3  4
7   3  5
8   3  6
9   4  1
10  4  2
11  4  3
12  5  1
13  5  2
14  5  3
15  6  1
16  6  2
17  6  3
  • Related