Update Index After Sorting Pandas DataFrame

Given a Pandas DataFrame, we have to update index after sorting.
Submitted by Pranit Sharma, on June 28, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mainly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data. The Data inside the DataFrame can be of any type.

To update after sorting DataFrame, we will first use the sort() method to sort the DataFrame and then we will use reset_index() method to update the index after sorting.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python code to update index after sorting pandas dataframe

# Importing pandas package
import pandas as pd

# Creating dictionary
d = {
    'X':[7,12,2001,2001,123,7],
    'Y':['d','o','b','d','o','b']
}

# Creating dataframe
df = pd.DataFrame(d)

# Display DataFrames
print("Created DataFrame:\n",df,"\n")

# Sorting DataFrame
result = df.sort_values(["X", "Y"])

# Display result
print("Sorted DataFrame:\n",result)

# Resetting index
result = result.reset_index(drop=True)

# Display
print("Resetted index:\n",result)

Output

The output of the above program is:

Example: Update Index After Sorting Pandas DataFrame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.