Sorting
sort_values
import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Leo", "Mei", "Raj", "Zoe", "Ana"],
"course": ["Python", "SQL", "Python", "Java", "SQL", "Java"],
"score": [92, 78, 85, 88, 95, 81],
})
print(df.sort_values("score")) # lowest first
print(df.sort_values("score", ascending=False)) # highest firstSorting returns a new DataFrame; df itself is unchanged unless you assign the result back: df = df.sort_values("score").
Sorting by several columns
import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Leo", "Mei", "Raj", "Zoe", "Ana"],
"course": ["Python", "SQL", "Python", "Java", "SQL", "Java"],
"score": [92, 78, 85, 88, 95, 81],
})
print(df.sort_values(["course", "score"], ascending=[True, False]))Courses alphabetically, and within each course, the highest score first. ascending takes one value per column.
Text and missing values
import numpy as np
import pandas as pd
df = pd.DataFrame({"name": ["mei", "Asha", "leo", "Zoe"], "score": [85, np.nan, 78, 95]})
print(df.sort_values("name")) # capitals sort before lower case
print(df.sort_values("name", key=lambda s: s.str.lower())) # case-insensitive
print(df.sort_values("score", na_position="first")) # missing values firstPlain text sorting puts every capital letter before every lower-case one. A key function transforms the values just for the comparison. Missing values go last unless you say otherwise.
Sorting by the index
import pandas as pd
scores = pd.DataFrame({"score": [92, 78, 85]}, index=["Mei", "Asha", "Leo"])
print(scores.sort_index()) # alphabetical by label
print(scores.sort_index(ascending=False))Top and bottom rows
import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Leo", "Mei", "Raj", "Zoe", "Ana"],
"score": [92, 78, 85, 88, 95, 81],
})
print(df.nlargest(3, "score")) # the top three
print(df.nsmallest(2, "score")) # the bottom twonlargest and nsmallest read more clearly than sorting and taking head, and are faster on big tables.
Ranking
import pandas as pd
scores = pd.Series([95, 88, 88, 72], index=["Zoe", "Raj", "Ana", "Leo"])
print(pd.DataFrame({
"score": scores,
"min": scores.rank(ascending=False, method="min"),
"dense": scores.rank(ascending=False, method="dense"),
"average": scores.rank(ascending=False),
}))A rank says where each value stands. Ties need a rule: min gives tied values the best rank they share (1, 2, 2, 4, like sports tables), dense leaves no gaps (1, 2, 2, 3), and the default, average, gives each the mean of their positions (2.5).
Renumbering: reset_index
import pandas as pd
df = pd.DataFrame({"name": ["Asha", "Leo", "Mei"], "score": [92, 78, 85]})
ranked = df.sort_values("score", ascending=False)
print(ranked) # the index still has the old row numbers
print(ranked.reset_index(drop=True)) # renumbered from 0After sorting or filtering, the index keeps the original labels. reset_index(drop=True) renumbers the rows from 0 and throws the old index away.