JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Pandas DataFrame sort_index() Function

Author:JIYIK Last Updated:2025/05/01 Views:

This tutorial explains how to use pandas.DataFrame.sort_index()the sort method to sort a Pandas DataFrame based on its index.

We will use the DataFrame shown in the above example to explain how to sort a Pandas DataFrame based on the index values.

import pandas as pd

pets_df = pd.DataFrame(
    {
        "Pet": ["Dog", "Cat", "Rabbit", "Fish"],
        "Name": ["Rocky", "Luna", "Coco", "Finley"],
        "Age(Years)": [3, 5, 5, 4],
    },
    index=["4", "2", "1", "3"],
)

print(pets_df)

Output:

      Pet    Name  Age(Years)
4     Dog   Rocky           3
2     Cat    Luna           5
1  Rabbit    Coco           5
3    Fish  Finley           4

pandas.DataFrame.sort_index()method

grammar

DataFrame.sort_index(
    axis=0,
    level=None,
    ascending=True,
    inplace=False,
    kind="quicksort",
    na_position="last",
    sort_remaining=True,
    by=None,
)

parameter

axis Sort along rows ( axis=0) or columns ( )axis=1
level Integer or list. Sort by the value at the specified index level.
ascending Sort in ascending order ( ascending=True) or descending order ( ascending=False)
inplace Boolean. If true True, modify the caller's DataFrame in-place.
kind Which sorting algorithm to use. Default value:quicksort
na_position Place NaNthe value at the beginning ( na_position=first) or end ( na_position=last).
sort_remaining Boolean. If true True, after index=multilevelsorting by the specified level of , also sort by other levels (in order).
ignore_index Boolean. If True, the labels of the resulting axis will be 0, 1, … n-1.
key A callable object. If Not None, this function is applied to the index values ​​before sorting key.

return

Return a DataFrame sorted by index along the specified axis if inplaceTrue True, otherwise None.

By default, we set axis=0, which means the DataFrame will be sorted along the row axis or by index values. If we set axis=1, the columns of the DataFrame will be sorted. By default, this method will sort the DataFrame in ascending order. If you want to sort the DataFrame in descending order, we set ascending=False.


Example: sort_index()Sort a Pandas DataFrame by Index using the

import pandas as pd

pets_df = pd.DataFrame(
    {
        "Pet": ["Dog", "Cat", "Rabbit", "Fish"],
        "Name": ["Rocky", "Luna", "Coco", "Finley"],
        "Age(Years)": [3, 5, 5, 4],
    },
    index=["4", "2", "1", "3"],
)

sorted_df = pets_df.sort_index()

print("Initial DataFrame:")
print(pets_df, "\n")

print("DataFrame Sorted by Index Values:")
print(sorted_df)

Output:

Initial DataFrame:
      Pet    Name Age(Years)
4     Dog   Rocky           3
2     Cat    Luna           5
1 Rabbit    Coco           5
3    Fish Finley           4

DataFrame Sorted by Index Values:
      Pet    Name Age(Years)
1 Rabbit    Coco           5
2     Cat    Luna           5
3    Fish Finley           4
4     Dog   Rocky           3

It sorts the DataFrame in ascending order based on the index values pet_df. To sort the DataFrame based on the index values, we need to specify indexthe parameter. By default, axisthe value of is 0, which sorts the rows of the DataFrame, i.e., it sorts the DataFrame based on the index values.

To sort the DataFrame in descending order based on the index values, we sort_index()set the method ascending=False.

import pandas as pd

pets_df = pd.DataFrame(
    {
        "Pet": ["Dog", "Cat", "Rabbit", "Fish"],
        "Name": ["Rocky", "Luna", "Coco", "Finley"],
        "Age(Years)": [3, 5, 5, 4],
    },
    index=["4", "2", "1", "3"],
)

sorted_df = pets_df.sort_index(ascending=False)

print("Initial DataFrame:")
print(pets_df, "\n")

print("DataFrame Sorted in Descending order based Index Values:")
print(sorted_df)

Output:

Initial DataFrame:
      Pet    Name Age(Years)
4     Dog   Rocky           3
2     Cat    Luna           5
1 Rabbit    Coco           5
3    Fish Finley           4

DataFrame Sorted in Descending order based Index Values:
      Pet    Name Age(Years)
4     Dog   Rocky           3
3    Fish Finley           4
2     Cat    Luna           5
1 Rabbit    Coco           5

pets_dfIt sorts the DataFrame in descending order based on the index values .


Example: sort_index()Sort columns of a Pandas DataFrame using the

To sort the columns of a Pandas DataFrame, we sort_index()set the sorting method axis=1.

import pandas as pd

pets_df = pd.DataFrame(
    {
        "Pet": ["Dog", "Cat", "Rabbit", "Fish"],
        "Name": ["Rocky", "Luna", "Coco", "Finley"],
        "Age(Years)": [3, 5, 5, 4],
    },
    index=["4", "2", "1", "3"],
)

sorted_df = pets_df.sort_index(axis=1)

print("Initial DataFrame:")
print(pets_df, "\n")

print("DataFrame with sorted Columns:")
print(sorted_df)

Output:

Initial DataFrame:
      Pet    Name  Age(Years)
4     Dog   Rocky           3
2     Cat    Luna           5
1  Rabbit    Coco           5
3    Fish  Finley           4

DataFrame with sorted Columns:
   Age(Years)    Name     Pet
4           3   Rocky     Dog
2           5    Luna     Cat
1           5    Coco  Rabbit
3           4  Finley    Fish

It pets_dfsorts the columns of the DataFrame in ascending order by column name.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Pandas DataFrame.astype() Function

Publish Date:2025/05/01 Views:160 Category:Python

Python Pandas DataFrame.astype() function changes the data type of an object to the specified data type. pandas.DataFrame.astype() grammar DataFrame . astype(dtype, copy = True , errors = "raise" ) parameter dtype The data type we want to a

Pandas cut function

Publish Date:2025/05/01 Views:165 Category:Python

pandas.cut() The function can distribute the given data into a range, which can also be called bins . We will use the following DataFrame in this article. import pandas as pd df = pd . DataFrame( { "Name" : [ "Anish" , "Birat" , "Chirag" ,

Appending to an Empty DataFrame in Pandas

Publish Date:2025/05/01 Views:54 Category:Python

As we learned earlier, Pandas in Python is an open source module that we can use for data analysis and making machine learning models. It is Numpy used along with another package called as they go hand in hand to support multidimensional ar

Pandas DataFrame DataFrame.query() function

Publish Date:2025/04/30 Views:108 Category:Python

The pandas.DataFrame.query() method filters the rows of the caller DataFrame using the given query expression. pandas.DataFrame.query() grammar DataFrame . query(expr, inplace = False , ** kwargs) parameter expr Filter rows based on query e

Pandas DataFrame DataFrame.min() function

Publish Date:2025/04/30 Views:162 Category:Python

Python Pandas DataFrame.min() function gets the minimum value of the DataFrame object along the specified axis. pandas.DataFrame.min() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = None , ** kwargs) pa

Pandas DataFrame DataFrame.mean() function

Publish Date:2025/04/30 Views:86 Category:Python

Python Pandas DataFrame.mean() function calculates the mean of the values ​​of the DataFrame object over the specified axis. pandas.DataFrame.mean() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = No

Pandas DataFrame DataFrame.isin() function

Publish Date:2025/04/30 Views:133 Category:Python

The pandas.DataFrame.isin(values) function checks whether each element in the caller DataFrame contains values the value specified in the input . pandas.DataFrame.isin(values) grammar DataFrame . isin(values) parameter values iterable - lis

Pandas DataFrame DataFrame.groupby() function

Publish Date:2025/04/30 Views:161 Category:Python

pandas.DataFrame.groupby() takes a DataFrame as input and divides the DataFrame into groups based on a given criterion. We can use groupby() the method to easily process large datasets. pandas.DataFrame.groupby() grammar DataFrame . groupby

Pandas DataFrame DataFrame.fillna() function

Publish Date:2025/04/30 Views:61 Category:Python

The pandas.DataFrame.fillna() function replaces the values DataFrame ​​in NaN with a certain value. pandas.DataFrame.fillna() grammar DataFrame . fillna( value = None , method = None , axis = None , inplace = False , limit = None , down

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial