Performant cartesian product (CROSS JOIN) with pandas

Learn, how to performant cartesian product (CROSS JOIN) with pandas in Python? By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Cartesian product

Cartesian product is a special product where each row value of one array is multiplied by each column of another array, but in pandas, each element from a row will be added to a new DataFrame column-wise.

Cartesian product (CROSS JOIN)

Cartesian product (CROSS JOIN) is that which is performed when we have data in form of rows and columns.

Performing performant cartesian product (CROSS JOIN)

We can perform cartesian product or Cross Join in pandas by using the merge() method with a required parameter called 'how=cross'.

Let us understand with the help of an example,

Python program to performance performant cartesian product (CROSS JOIN) with pandas

# Importing pandas package
import pandas as pd

# Creating a dictionary
d= {'one':[10,20,30],'two':[40,50,60]}

d2 = {'three':[1,2,3]}

# Creating two Dataframes
df1 = pd.DataFrame(d)

df2 = pd.DataFrame(d2)

# Display DataFrames
print("DataFrame 1:\n",df1,"\n")

print("DataFrame 1:\n",df2,"\n")

# Cartesian product
result = df1.merge(df2, how='cross')

# Display result
print("Cartesian product:\n",result)


The output of the above program is:

Example: Performant cartesian product (CROSS JOIN) with pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.