Sorting

Pandas Basics

1 min read

Published Sep 29 2025, updated Aug 17 2026


21
0
0
0

PandasPython

Sorting allows you to reorder rows based on column values.


Sample data for the examples:

import pandas as pddf = pd.DataFrame({    "Name": ["Alice", "Bob", "Charlie", "David"],    "Age": [25, 30, 35, 40],    "Salary": [50000, 60000, 75000, 80000]})



Sort by Single Column

# Sort by Age ascending (default)df.sort_values("Age", inplace=True)



Sort Descending

df.sort_values("Salary", ascending=False, inplace=True)



Sort by Multiple Columns

# Sort by Age ascending, then Salary descendingdf.sort_values(["Age", "Salary"], ascending=[True, False], inplace=True)



Resetting Index after Sorting

After filtering or sorting, the index may be non-sequential:

filtered_df = df.sort_values(["Age", "Salary"], ascending=[True, False],).reset_index(drop=True)

drop=True removes the old index.




Limit the sorted results

  • .head(n) shows the first n rows (default 5).
  • .tail(n) shows the last n rows.
df.sort_values("Salary", ascending=False, inplace=True).head(2)

Sorts salary descending and returns just the top 2 rows.

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact
Pandas Basics | Sorting | SimpleSteps.guide