15.1 C
London
Friday, July 5, 2024
HomePandas in PythonGeneral Functions in PythonPandas: Sort DataFrame by Both Index and Column

Pandas: Sort DataFrame by Both Index and Column

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to sort a pandas DataFrame by both index and column:

df = df.sort_values(by = ['column_name', 'index'], ascending = [False, True])

The following examples show how to use this syntax in practice.

Examples: Sort DataFrame by Both Index and Column

The following code shows how to sort a pandas DataFrame by the column named points and then by the index column:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6, 7, 8],
                   'points': [25, 15, 15, 14, 20, 20, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}).set_index('id')

#view first few rows
df.head()

	points	assists	rebounds
id			
1	25	5	11
2	15	7	8
3	15	7	10
4	14	9	6
5	20	12	6

#sort by points and then by index
df.sort_values(by = ['points', 'id'], ascending = [False, True])

	points	assists	rebounds
id			
8	29	4	12
1	25	5	11
7	25	9	9
5	20	12	6
6	20	9	5
2	15	7	8
3	15	7	10
4	14	9	6

The resulting DataFrame is sorted by points in descending order and then by the index in ascending order (if there happen to be two players who score the same number of points).

Note that if we don’t use the ascending argument, then each column will use ascending as the default sorting method:

#sort by points and then by index
df.sort_values(by = ['points', 'id'])

        points	assists	rebounds
id			
4	14	9	6
2	15	7	8
3	15	7	10
5	20	12	6
6	20	9	5
1	25	5	11
7	25	9	9
8	29	4	12

If the index column is currently not named, you can rename it and then sort accordingly:

#sort by points and then by index
df.rename_axis('index').sort_values(by = ['points', 'id'])

        points	assists	rebounds
id			
4	14	9	6
2	15	7	8
3	15	7	10
5	20	12	6
6	20	9	5
1	25	5	11
7	25	9	9
8	29	4	12

Additional Resources

Pandas: How to Sort Columns by Name
Pandas: Sort DataFrame by Date
Pandas: How to Drop Duplicate Rows

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories