Pandas — Sorting
Sort by values
import pandas as pd
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35]})
# Sort ascending
print(df.sort_values('age'))
# Sort descending
print(df.sort_values('age', ascending=False))
# Multiple columns
print(df.sort_values(['age', 'name'], ascending=[True, False]))
Sort by index
df = df.set_index('name')
print(df.sort_index())
Nlargest/Nsmallest
print(df.nlargest(2, 'age'))
print(df.nsmallest(2, 'age'))
Mini Practice
- Sort by column
- Sort descending
- Sort by index
- Use nlargest/nsmallest
Up Next
Continue with String - String operations.
Related Topics
Frequently Asked Questions about Sorting
What is Sorting in Pandas?
Sorting is a fundamental concept in Pandas. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Sorting?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sorting.
Why is Sorting important in Pandas?
Sorting is essential for Pandas development. Understanding this concept will help you write better code and solve real-world problems more effectively.