Categories
Python Answers

How to create a cartesian product in Python Pandas?

Spread the love

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

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

How to create a cartesian product in Python Pandas?

To create a cartesian product in Python Pandas, we can use the pd.MultiIndex.from_product method.

For instance, we write

a = [1, 2, 3]
b = ["a", "b", "c"]

index = pd.MultiIndex.from_product([a, b], names = ["a", "b"])

df = pd.DataFrame(index = index).reset_index()

to call pd.MultiIndex.from_product with lists a and b in a list.

And then we name the column names a and b.

Next, we create a data frame with the DataFrame class with the index returned from from_product.

And then we call reset_index to reset the indexes so that they’re set according to the rows in the new data frame.

Conclusion

To create a cartesian product in Python Pandas, we can use the pd.MultiIndex.from_product 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 *