Search code examples
pythonpandascartesian-productcross-product

cross product/ cartesian product in python


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


Solution

  • 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