Why does my Pandas DataFrame not display new order using `sort_values`?

Learn, why does my Pandas DataFrame not display new order using `sort_values` in Python? By Pranit Sharma Last updated : October 06, 2023

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

Solution for pandas DataFrame not display new order using `sort_values` Issue?

Sorting refers to rearranging a series or a sequence in a particular fashion (ascending, descending, or in any specific pattern). Sorting in pandas DataFrame is required for effective analysis of the data.

Pandas dataframe sort values method is used to sort the values along either Axis that is either row-wise or column-wise.

Many times, users face this problem when they apply the sort_values() method on their dataframe but it does not display the new order. This is because of an important property of this method which we need to understand.

The important point about this method is it returns a sorted dataframe but it does not update the dataframe in place. Hence, if we are using this method, we have to do it explicitly that we need to store the result in another variable or the dataframe variable itself otherwise it will not update the data frame in place.

Let us understand with the help of an example,

Python program to fix Pandas DataFrame not display new order using `sort_values`

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating DataFrame
df = pd.DataFrame({
    'date':['07/12/2001','07/12/2000','05/10/1999','05/10/1998','03/08/1997'],
    'Values':[21,22,23,24,25]
})

# Display Original dataframe
print("Original DataFrame:\n",df,"\n")

# Sorting values of values column
res = df['Values'].sort_values()

# Print result
print("Result:\n",res)

Output

The output of the above program is:

Example: Why does my Pandas DataFrame not display new order using `sort_values`?

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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