w3resource

Merging DataFrames and Selecting Specific Columns in Pandas

Pandas: Custom Function Exercise-20 with Solution

Write a Pandas program that merges DataFrames and select specific columns after merge.

This exercise demonstrates how to merge two DataFrames and then select specific columns from the resulting DataFrame.

Sample Solution :

Code :

import pandas as pd

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

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')

# Select specific columns from the merged DataFrame
selected_columns_df = merged_df[['Name', 'Salary']]

# Output the result
print(selected_columns_df)

Output:

      Name  Salary
0    David   50000
1  Annabel   60000
2  Charlie   70000

Explanation:

  • Created two DataFrames df1 and df2.
  • Merged them on the 'ID' column using pd.merge().
  • Selected only the 'Name' and 'Salary' columns from the resulting DataFrame.

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://w3resource.com/python-exercises/pandas/pandas-merge-dataframes-and-select-specific-columns.php