Python Pandas – Merge DataFrame with one-to-one relation

PythonServer Side ProgrammingProgramming

To merge Pandas DataFrame, use the merge() function. The one-to-one relation is implemented on both the DataFrames by setting under the “validate” parameter of the merge() function i.e. −

validate = “one-to-one”
or
validate = “1:1”

The one-to-many relation checks if merge keys are unique in both left and right dataset.

At first, let us create our 1st DataFrame −

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

Now, let us create our 2nd DataFrame −

dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
   }
)

Example

Following is the code −

#
# Merge Pandas DataFrame with one-to-one relation
#

import pandas as pd

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

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

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

   }
)

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

# merge DataFrames with "one-to-one" in "validate" parameter
mergedRes = pd.merge(dataFrame1, dataFrame2, validate ="one_to_one")
print("\nMerged dataframe with one-to-one relation...\n", mergedRes)

Output

This will produce the following output −

DataFrame1 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90

DataFrame2 ...
        Car   Reg_Price
0       BMW        7000
1     Lexus        1500
2     Tesla        5000
3   Mustang        8000
4  Mercedes        9000
5    Jaguar        6000

Merged dataframe with one-to-one relation
       Car   Units   Reg_Price
0      BMW     100        7000
1    Lexus     150        1500
2  Mustang      80        8000
3   Jaguar      90        6000
raja
Published on 01-Oct-2021 11:40:15
Advertisements