Categories
Python Answers

How to create a cartesian product in Python Pandas?

Spread the love

To create a cartesian product in Python Pandas, we call the data frame merge method with how set to 'cross'.

For instance, we write

from pandas import DataFrame
df1 = DataFrame({'col1':[1,2],'col2':[3,4]})
df2 = DataFrame({'col3':[5,6]})    

df1.merge(df2, how='cross')

to call df1.merge with df2 and the how argument set to 'cross' to return cartesian product between df1 and df2.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *