Home > database >  Why does my pandas dataframe not sort with sort_values?
Why does my pandas dataframe not sort with sort_values?

Time:09-14

I tried sorting my dataframe by multiple columns where I would like 1 column to descend. I have used the following code to try to do so:

officeSuppliesDf.sort_values(
    by=['Region', 'Total'],
    ascending = [True, False],
    inplace = True,
)

Where officeSuppliesDf is my dataframe with data read from a csv file and The Total column should be descending.

However when I print my datadrame I get the result where Region is sorted, however, The Total column seems random.

Any help would be appreciated.

Picture of result after sort attempt

CodePudding user response:

Did you check the data type of the 'Total' column? Is it perhaps a string and not a float?

You can check the datatypes using the .dtypes: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dtypes.html

Try:

df['Total'] = df['Total'].astype(float)

CodePudding user response:

You have a Comma , after inplace=True. You should remove this.

Try this:

officeSuppliesDf.sort_values( ['Region', 'Total'],
                               ascending = [True, False],
                               inplace = True)
  • Related