Python Pandas – Merge and create cartesian product from both the DataFrames

PythonServer Side ProgrammingProgramming

To merge Pandas DataFrame, use the merge() function. The cartesian product is implemented on both the DataFrames by setting under the “how” parameter of the merge() function i.e. −

how = “cross”

At first, let us import the pandas library with an alias −

import pandas as pd

Create DataFrame1 −

dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 120]
   }
)

Create DataFrame2

dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Tesla', 'Jaguar'],"Reg_Price": [7000, 8000, 9000]

   }
)

Next, merge DataFrames with "cross" in "how" parameter i.e. Cartesian Product −

mergedRes = pd.merge(dataFrame1, dataFrame2, how ="cross")

Example

Following is the code

import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 120]
   }
)

print("DataFrame1 ...\n",dataFrame1)

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Tesla', 'Jaguar'],"Reg_Price": [7000, 8000, 9000]

   }
)

print("\nDataFrame2 ...\n",dataFrame2)

# merge DataFrames with "cross" in "how" parameter i.e Cartesian Product
mergedRes = pd.merge(dataFrame1, dataFrame2, how ="cross")
print("\nMerged dataframe with cartesian product...\n", mergedRes)

Output

This will produce the following output −

DataFrame1 ...
       Car   Units
0      BMW     100
1  Mustang     150
2  Bentley     110
3   Jaguar     120
DataFrame2 ...
      Car   Reg_Price
0     BMW        7000
1   Tesla        8000
2  Jaguar        9000

Merged dataframe with cartesian product...
       Car   Units   Car_y   Reg_Price
0      BMW     100     BMW        7000
1      BMW     100   Tesla        8000
2      BMW     180  Jaguar        9000
3  Mustang     150     BMW        7000
4  Mustang     150   Tesla        8000
5  Mustang     150  Jaguar        9000
6  Bentley     110     BMW        7000
7  Bentley     110   Tesla        8000
8  Bentley     110  Jaguar        9000
9   Jaguar     120     BMW        7000
10  Jaguar     120   Tesla        8000
11  Jaguar     120  Jaguar        9000
raja
Published on 29-Sep-2021 07:21:01
Advertisements