cross product/ cartesian product in python

110 Views Asked by At

I want to get a cartesian product of dates. I have following dates ( months) in data set

201801 201802

as an output i want as

enter image description here

1

There are 1 best solutions below

6
On BEST ANSWER

You can use itertools.product. Let L be your column df['dates'] for example -

from itertools import product

l = [201801,201802]
out = pd.DataFrame(list(product(l,l)))
print(out)
        0       1
0  201801  201801
1  201802  201801
2  201801  201802
3  201802  201802

Or you could simply use a list comprehension to iterate l 2 times.

out = pd.DataFrame([(j,i) for i in l for j in l])
print(out)
        0       1
0  201801  201801
1  201802  201801
2  201801  201802
3  201802  201802