Categories
Python Answers

How to create a cartesian product with Python Pandas?

Spread the love

Sometimes, we want to create a cartesian product with Python Pandas.

In this article, we’ll look at how to create a cartesian product with Python Pandas.

How to create a cartesian product with Python Pandas?

To create a cartesian product with Python Pandas, we can call the merge method.

For instance, we write:

from pandas import DataFrame

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

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

to call df1.merge to merge data frtame df1 with df2.

We set how to 'cross' to create a cartesian product and assign the returned data frame to df.

Therefore, df is:

   col1  col2  col3
0     1     3     5
1     1     3     6
2     2     4     5
3     2     4     6

Conclusion

To create a cartesian product with Python Pandas, we can call the merge method.

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 *