AtomLearnAtomLearn
DashboardGoalsPathAchievementsReviewSign In
DashboardpandasSorting a DataFrame
pandasNot Started

Sorting a DataFrame

Order rows by one or more column values

0%
Knowledge0%
Learn & Drill
Fluency0%
Drill & Speed
Retention0%
Mastery & Review
Confidence0%
All modes
Practice

Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.

Upgrade
Knowledge
Fluency
Retention

Knowledge Debt detected

You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.

Explanation

sort_values() sorts rows by column values:

python
# Sort by salary (ascending by default)
df.sort_values('salary')

# Sort descending
df.sort_values('salary', ascending=False)

# Sort by multiple columns
df.sort_values(['department', 'salary'], ascending=[True, False])
# Sorts by department A-Z, then by salary high-to-low within each dept

# Reset the index after sorting
df.sort_values('salary').reset_index(drop=True)

sort_index() sorts by the row index: ``python df.sort_index() # ascending index df.sort_index(ascending=False)

nlargest() / nsmallest() — get top/bottom N rows: ``python df.nlargest(5, 'salary') # top 5 salaries df.nsmallest(3, 'age') # 3 youngest

Note: Like most pandas operations, sort_values() returns a new DataFrame unless you use inplace=True.

Examples

Multi-column sort

ascending=[True,False] means first col asc, second col desc

import pandas as pd

df = pd.DataFrame({'dept':['Eng','Mkt','Eng','Mkt','Eng'],'name':['Alice','Bob','Carol','Dave','Eve'],'salary':[80,65,90,70,75]})

# Sort by dept, then by salary descending within dept
result = df.sort_values(['dept','salary'], ascending=[True,False])
print(result)
# Eng: Carol(90), Eve(75), Alice(80)... wait:
# dept A-Z: Eng first, then Mkt
# within Eng: 90, 80, 75

How well did you understand this?

Next in pandas

Applying Functions to Columns

Continue