w3resource

Merging DataFrames and Selecting Specific Columns in Pandas


20. Merge and Select Columns

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to merge two DataFrames and then select only a subset of columns based on a provided list.
  • Write a Pandas program to merge two DataFrames and then re-order the resulting columns in a specific sequence.
  • Write a Pandas program to merge two DataFrames, select specific columns, and rename them for clarity.
  • Write a Pandas program to merge two DataFrames and then create a new DataFrame containing only the columns that match a given pattern.

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.