Python - Merge DataFrames of different length

PythonServer Side ProgrammingProgramming

To merge dataframes of different length, we need to use the merge() method. Let’s say the following is our 1st DataFrame with length 4 −

dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Jaguar']
   }
)

print("DataFrame1 ...
",dataFrame1) print("DataFrame1 length = ", len(dataFrame1))

Following is our 2nd DataFrame with length 6 −

dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley']
   }
)

print("
DataFrame2 ...
",dataFrame2) print("DataFrame2 length = ", len(dataFrame2))

Now, merge DataFrames using the merge() −

mergedRes = dataFrame2.merge(dataFrame1, how='left')

Example

Following is the code −

import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Jaguar']
   }
)
print("DataFrame1 ...
",dataFrame1) # Find length of DataFrame1 print("DataFrame1 length = ", len(dataFrame1)) # Create DataFrame2 dataFrame2 = pd.DataFrame(    {       "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'] } ) print("
DataFrame2 ...
",dataFrame2) # Find length of DataFrame2 print("DataFrame2 length = ", len(dataFrame2)) # merge DataFrames mergedRes = dataFrame2.merge(dataFrame1, how='left') print("
Merged data frame...
", mergedRes)

Output

This will produce the following output −

DataFrame1 ...
      Car
0     BMW
1   Lexus
2    Audi
3  Jaguar
DataFrame1 length = 4

DataFrame2 ...
        Car
0       BMW
1     Lexus
2      Audi
3  Mercedes
4    Jaguar
5   Bentley
DataFrame2 length = 6

Merged data frame...
        Car
0       BMW
1     Lexus
2      Audi
3  Mercedes
4    Jaguar
5   Bentley
raja
Updated on 23-Feb-2022 13:20:27

Advertisements