w3resource

Merging DataFrames and Renaming Columns in Pandas

Pandas: Custom Function Exercise-18 with Solution

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().

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/pandas-merge-dataframes-and-rename-columns-after-merge.php