How to add column from another DataFrame in Pandas?

PythonServer Side ProgrammingProgramming

The insert() method is used to add a column from another DataFrame. At first, let us create our first DataFrame −

dataFrame1 = pd.DataFrame({"Car": ["Audi","Lamborghini", "BMW", "Lexus"],
   "Place": ["US", "UK", "India", "Australia"],
   "Units": [200, 500, 800, 1000]})

Now, let us create our second DataFrame −

dataFrame2 = pd.DataFrame({"Model": [2018, 2019, 2020, 2021], "CC": [3000, 2800, 3500, 3300]})

Car column added from DataFrame1 to DataFrame2

# Car column to be added to the second dataframe fetched_col = dataFrame1["Car"]

Example

Following is the code −

import pandas as pd

dataFrame1 = pd.DataFrame({"Car": ["Audi", "Lamborghini", "BMW", "Lexus"],
   "Place": ["US", "UK", "India", "Australia"],
   "Units": [200, 500, 800, 1000]})

print("Dataframe 1...")
print(dataFrame1)

dataFrame2 = pd.DataFrame({"Model": [2018, 2019, 2020, 2021], "CC": [3000, 2800, 3500, 3300]})
print("Dataframe 2...")
print(dataFrame2)

# Car column to be added to the second dataframe
fetched_col = dataFrame1["Car"]

dataFrame2.insert(1, "LuxuryCar", fetched_col)
print("Dataframe 2 (Updated):")
print(dataFrame2)

Output

This will produce the following output −

Dataframe 1...
           Car      Place     Units
0         Audi         US       200
1  Lamborghini         UK       500
2          BMW      India       800
3        Lexus  Australia      1000
Dataframe 2...
     CC      Model
0   3000     2018
1   2800     2019
2   3500     2020
3   3300     2021
Dataframe 2 (Updated):
     CC    LuxuryCar   Model
0   3000        Audi   2018
1   2800 Lamborghini   2019
2   3500         BMW   2020
3   3300       Lexus  2021
raja
Published on 09-Sep-2021 06:32:07
Advertisements