Merging DataFrames and applying custom sorting by column in Pandas
15. Merge with Custom Sorting
Write a Pandas program to merge DataFrames with custom sorting.
This exercise demonstrates how to merge two DataFrames and sort the result by a specific column.
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': [2, 3, 1],
'Age': [30, 22, 25]
})
# Merge the DataFrames on the 'ID' column
merged_df = pd.merge(df1, df2, on='ID')
# Sort the result by 'Age' column
sorted_df = merged_df.sort_values(by='Age')
# Output the result
print(sorted_df)
Output:
ID Name Age 2 3 Caeso 22 0 1 Selena 25 1 2 Annabel 30
Explanation:
- Created two DataFrames df1 and df2.
- Merged them on the 'ID' column using pd.merge().
- Sorted the resulting DataFrame by the 'Age' column using sort_values().
For more Practice: Solve these Related Problems:
- Write a Pandas program to merge two DataFrames and then sort the merged DataFrame based on a custom list of column priorities.
- Write a Pandas program to merge two DataFrames and then apply custom sorting based on a date column in descending order.
- Write a Pandas program to merge two DataFrames and then sort the result by multiple columns with different sort orders.
- Write a Pandas program to merge two DataFrames with custom sorting that first groups by a categorical column then sorts each group by a numeric column.
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.