w3resource

Merging DataFrames and Renaming Columns in Pandas


18. Merge and Rename Columns

Write a Pandas program to merge DataFrames and rename columns after merge.

This exercise shows how to merge DataFrames and rename specific columns in the resulting DataFrame.

Sample Solution :

Code :

import pandas as pd

# Create two sample DataFrames
df1 = pd.DataFrame({
    'ID': [1, 2, 3],
    'Name': ['Selena', 'Annabel', 'Caeso']
})

df2 = pd.DataFrame({
    'ID': [1, 2, 3],
    'Salary': [50000, 60000, 70000]
})

# Merge the DataFrames on the 'ID' column
merged_df = pd.merge(df1, df2, on='ID')

# Rename the 'Salary' column to 'Annual_Income'
merged_df.rename(columns={'Salary': 'Annual_Income'}, inplace=True)

# Output the result
print(merged_df)

Output:

   ID     Name  Annual_Income
0   1   Selena          50000
1   2  Annabel          60000
2   3    Caeso          70000

Explanation:

  • Created two DataFrames df1 and df2.
  • Merged them on the 'ID' column using pd.merge().
  • Renamed the 'Salary' column to 'Annual_Income' using rename().

For more Practice: Solve these Related Problems:

  • Write a Pandas program to merge two DataFrames and then rename columns based on a provided mapping dictionary.
  • Write a Pandas program to merge two DataFrames and rename duplicate columns by appending a suffix that indicates their origin.
  • Write a Pandas program to merge two DataFrames and then rename the key column to a standardized name across multiple DataFrames.
  • Write a Pandas program to merge two DataFrames and then convert all column names to uppercase after merging.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.