Sorting Data

Python · Pandas Basics

Theory

df.sort_values('amount') returns the rows ordered by a column, smallest first; ascending=False reverses it. To sort by several keys pass lists: df.sort_values(['city', 'amount'], ascending=[True, False]) orders by city A-Z and, inside each city, by amount high to low - exactly SQL's ORDER BY city ASC, amount DESC. Missing values go last unless na_position='first'. The index labels travel with their rows, so add .reset_index(drop=True) if you want 0, 1, 2 again.

df.sort_index() sorts by the row labels instead (handy after a groupby or set_index), and sort_index(axis=1) sorts column names. For 'top n' questions, df.nlargest(3, 'amount') and df.nsmallest(3, 'amount') are shortcuts that are clearer, and on large data faster, than sorting everything and taking head(3).

Why we use it

Sorted output is easier to read and is required for many tasks: top-N lists, reports in a fixed order, running totals and lag comparisons that depend on row order.

When to use it

Use sort_values for ordering by data, sort_index for ordering by labels, and nlargest/nsmallest for a quick top or bottom n. Do not sort just to find a max - idxmax() or max() is enough.

How it works

  1. df.sort_values(['city', 'amount'], ascending=[True, False])
  2. Order rows by the first key, city A-Z
  3. Two rows have the same city? Yes: Break the tie with amount, high to low. No: Keep the city order.
  4. Place NaN rows according to na_position
  5. Sorted DataFrame (original index labels kept)

Syntax

df.sort_values(by, ascending=True, na_position='last')
df.sort_values(['a', 'b'], ascending=[True, False])
df.sort_index()
df.nlargest(n, 'col')

Example

print(df.sort_values(['city', 'amount'], ascending=[True, False]))
print(df.nlargest(2, 'amount'))

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic