Merging DataFrames and applying custom sorting by column in Pandas
Pandas: Custom Function Exercise-15 with Solution
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().
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.
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-with-custom-sorting-by-column.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics