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.