PYTHON FOR AI • LESSON 3

Sorting Data

Sorting means arranging your data in a specific order. With Pandas, you can sort numbers from smallest to largest, largest to smallest, or sort text alphabetically. Sorting makes large datasets much easier to understand and analyze.

CORE IDEA

Sorting changes the order of rows, not the actual data.

For example, if student scores are 85, 90, 78, and 92, sorting by score can arrange them from lowest to highest or highest to lowest.

01

Start With a DataFrame

We will use a simple student dataset.

import pandas as pd

students = pd.DataFrame({
    "Name": ["Raj", "John", "Sarah", "David", "Emma"],
    "Age": [29, 32, 27, 30, 25],
    "Score": [85, 90, 78, 92, 65],
    "City": [
        "Hyderabad",
        "London",
        "New York",
        "Hyderabad",
        "London"
    ]
})

print(students)
    Name  Age  Score       City
0    Raj   29     85  Hyderabad
1   John   32     90     London
2  Sarah   27     78   New York
3  David   30     92  Hyderabad
4   Emma   25     65     London

Notice that the scores are not currently arranged in any particular order.

02

Sort From Smallest to Largest

Pandas provides the sort_values() method for sorting rows.

Let's sort students by their score.

result = students.sort_values(
    by="Score"
)

print(result)
    Name  Age  Score       City
4   Emma   25     65     London
2  Sarah   27     78   New York
0    Raj   29     85  Hyderabad
1   John   32     90     London
3  David   30     92  Hyderabad

By default, Pandas sorts in ascending order.

65
78
85
90
92
03

Sort From Largest to Smallest

To sort in descending order, use:

ascending=False

Example:

result = students.sort_values(
    by="Score",
    ascending=False
)

print(result)
    Name  Age  Score       City
3  David   30     92  Hyderabad
1   John   32     90     London
0    Raj   29     85  Hyderabad
2  Sarah   27     78   New York
4   Emma   25     65     London

Now the highest score appears first.

04

Understand sort_values()

The most important argument is by.

students.sort_values(
    by="Score"
)

Think of it as:

sort_values()
      ↓
Which column?
      ↓
by="Score"
      ↓
How should it be ordered?
      ↓
ascending=True / False

So this:

students.sort_values(
    by="Score",
    ascending=False
)

simply means: "Sort the rows using Score, with the highest score first."

05

Sort Text Values

You can also sort text columns alphabetically.

For example, sort students by name.

result = students.sort_values(
    by="Name"
)

print(result)
    Name  Age  Score       City
3  David   30     92  Hyderabad
4   Emma   25     65     London
1   John   32     90     London
0    Raj   29     85  Hyderabad
2  Sarah   27     78   New York

Pandas sorts the names alphabetically:

David
Emma
John
Raj
Sarah
06

Reverse the Text Order

The same ascending=False option works with text.

result = students.sort_values(
    by="Name",
    ascending=False
)

print(result)
    Name  Age  Score       City
2  Sarah   27     78   New York
0    Raj   29     85  Hyderabad
1   John   32     90     London
4   Emma   25     65     London
3  David   30     92  Hyderabad
07

Sort by Another Column

You can sort by any column in the DataFrame.

result = students.sort_values(
    by="Age"
)

print(result)
    Name  Age  Score       City
4   Emma   25     65     London
2  Sarah   27     78   New York
0    Raj   29     85  Hyderabad
3  David   30     92  Hyderabad
1   John   32     90     London
08

Sort by Multiple Columns

This becomes useful when multiple rows have the same value.

For example, first sort by City and then by Score.

result = students.sort_values(
    by=["City", "Score"]
)

print(result)
    Name  Age  Score       City
0    Raj   29     85  Hyderabad
3  David   30     92  Hyderabad
4   Emma   25     65     London
1   John   32     90     London
2  Sarah   27     78   New York

Pandas first groups the rows by City, then sorts the rows inside each city using Score.

09

Different Sort Directions

When sorting multiple columns, you can control the direction of each column separately.

result = students.sort_values(
    by=["City", "Score"],
    ascending=[True, False]
)

print(result)

This means:

City  → ascending
Score → descending
    Name  Age  Score       City
3  David   30     92  Hyderabad
0    Raj   29     85  Hyderabad
1   John   32     90     London
4   Emma   25     65     London
2  Sarah   27     78   New York

Notice that Hyderabad comes alphabetically first, but within Hyderabad the highest score comes first.

10

Does Sorting Change the Original Data?

This is an important concept.

When you do this:

result = students.sort_values(
    by="Score"
)

Pandas creates a sorted result and stores it in result. The original students DataFrame remains unchanged.

print(students)

print(result)

This is useful because you can keep your original data and create different sorted versions when needed.

11

Save the Sorted Data

If you want the sorted DataFrame to become your main DataFrame, assign it back.

students = students.sort_values(
    by="Score",
    ascending=False
)

print(students)

Now the variable students points to the sorted DataFrame.

12

What Happens to the Index?

Notice something in the previous results:

3  David
1  John
0  Raj
2  Sarah
4  Emma

The rows are sorted, but the original index numbers are preserved.

If you want a fresh index, use reset_index().

result = students.sort_values(
    by="Score",
    ascending=False
).reset_index(drop=True)

print(result)
    Name  Age  Score       City
0  David   30     92  Hyderabad
1   John   32     90     London
2    Raj   29     85  Hyderabad
3  Sarah   27     78   New York
4   Emma   25     65     London

Now the index starts again from 0.

13

Sort by Index

There is also a difference between sorting by a column and sorting by the DataFrame index.

students.sort_index()

This sorts the rows according to their index numbers.

Remember:

sort_values()
→ Sort using column values

sort_index()
→ Sort using index values
14

Real-World AI Example

Imagine you have customer purchase data.

Customer    Purchases    Spending
Raj            12          1500
John            5           400
Sarah          20          2500
David          15          1800
Emma            8           700

If you want to find your highest-spending customers, sort by Spending in descending order.

customers.sort_values(
    by="Spending",
    ascending=False
)

This can help you quickly identify the most valuable customers before performing further analysis.

15

Combine Filtering and Sorting

Filtering and sorting are often used together.

For example:

Find students with scores above 80 and show the highest score first.
result = students[
    students["Score"] > 80
].sort_values(
    by="Score",
    ascending=False
)

print(result)
    Name  Age  Score       City
3  David   30     92  Hyderabad
1   John   32     90     London
0    Raj   29     85  Hyderabad

The workflow is:

DataFrame
    ↓
Filter rows
    ↓
Keep Score > 80
    ↓
Sort by Score
    ↓
Highest score first
16

Simple Mental Model

Think of sorting like arranging a classroom

Imagine students standing randomly in a line. Sorting tells them how to arrange themselves.

Random order:

Raj     85
John    90
Sarah   78
David   92
Emma    65


Sort by Score ↓

David   92
John    90
Raj     85
Sarah   78
Emma    65

Nothing about the students changed. Only their order changed.

KEY TAKEAWAY

sort_values() arranges DataFrame rows using column values.

Use sort_values() to sort data by one or more columns. By default, sorting is ascending. Use ascending=False for descending order. You can sort numbers, text, or multiple columns, and you can combine filtering and sorting to answer more useful questions about your dataset.