Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to add column from another DataFrame in Pandas?
In Pandas, you can add a column from one DataFrame to another using several methods. The most common approaches are using insert(), direct assignment, or assign().
Using insert() Method
The insert() method allows you to add a column at a specific position in the DataFrame.
Syntax
DataFrame.insert(loc, column, value)
Parameters:
- loc − Position where to insert the column
- column − Name of the new column
- value − Values for the new column
Example
Let's create two DataFrames and add a column from one to another ?
import pandas as pd
# Create first DataFrame
dataFrame1 = pd.DataFrame({
"Car": ["Audi", "Lamborghini", "BMW", "Lexus"],
"Place": ["US", "UK", "India", "Australia"],
"Units": [200, 500, 800, 1000]
})
print("DataFrame 1:")
print(dataFrame1)
# Create second DataFrame
dataFrame2 = pd.DataFrame({
"Model": [2018, 2019, 2020, 2021],
"CC": [3000, 2800, 3500, 3300]
})
print("\nDataFrame 2:")
print(dataFrame2)
# Add Car column from DataFrame1 to DataFrame2
fetched_col = dataFrame1["Car"]
dataFrame2.insert(1, "LuxuryCar", fetched_col)
print("\nDataFrame 2 (Updated):")
print(dataFrame2)
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
Using Direct Assignment
You can also add a column using direct assignment, which appends the column at the end ?
import pandas as pd
# Create DataFrames
df1 = pd.DataFrame({"Name": ["Alice", "Bob", "Charlie"], "Age": [25, 30, 35]})
df2 = pd.DataFrame({"Salary": [50000, 60000, 70000]})
print("Original df2:")
print(df2)
# Add Name column from df1 to df2
df2["Name"] = df1["Name"]
print("\nUpdated df2:")
print(df2)
Original df2: Salary 0 50000 1 60000 2 70000 Updated df2: Salary Name 0 50000 Alice 1 60000 Bob 2 70000 Charlie
Comparison
| Method | Position Control | Modifies Original | Best For |
|---|---|---|---|
insert() |
Yes | Yes | Specific column position |
| Direct Assignment | No (end only) | Yes | Simple column addition |
assign() |
No (end only) | No | Immutable operations |
Conclusion
Use insert() when you need to place the column at a specific position. Use direct assignment for simple column addition at the end. Both methods require DataFrames to have the same number of rows.
Advertisements
