简体   繁体   中英

Why does my pandas dataframe not sort with sort_values?

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.

排序尝试后的结果图片

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)

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM