Sorting data is a common operation in data analysis and manipulation, and the Pandas library in Python provides a variety of ways to sort data. Below are ten examples that demonstrate different sorting operations using Pandas:
Preparation: Import Pandas and Create DataFrames
First, let’s import the Pandas library and create some example DataFrames:
Python
import pandas as pd
import numpy as np
# Create DataFrame from dictionary
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Age': [34, 45, 23, 47, 29],
'Salary': [50000, 60000, 70000, 80000, 90000]
})
# Create DataFrame with random numbers
df_random = pd.DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'])
Example 1: Sort by Index (Ascending)
Python
sorted_df = df.sort_index()
Example 2: Sort by Index (Descending)
Python
sorted_df = df.sort_index(ascending=False)
Example 3: Sort by Single Column (Ascending)
Python
sorted_df = df.sort_values(by='Age')
Example 4: Sort by Single Column (Descending)
Python
sorted_df = df.sort_values(by='Age', ascending=False)
Example 5: Sort by Multiple Columns
Python
sorted_df = df.sort_values(by=['Age', 'Salary'])
Example 6: Sort by Multiple Columns with Different Sort Orders
Python
sorted_df = df.sort_values(by=['Age', 'Salary'], ascending=[True, False])
Example 7: Sort and Reset Index
Python
sorted_df = df.sort_values(by='Age').reset_index(drop=True)
Example 8: Sort by Column In-Place
Python
df.sort_values(by='Age', inplace=True)
Example 9: Sort a Series
Python
sorted_series = df['Age'].sort_values()
Example 10: Sort by Row Values Along Columns
Python
sorted_df = df_random.sort_values(by=2, axis=1)
These are just a few of the many sorting operations you can perform with Pandas. Each of these examples addresses a different need you might encounter when working with data.