Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe sort_values set default ascending=False

Tags:

python

pandas

Could be possible to define a property to always set sort_values(ascending=False)? Using it quite often in descending order then would like to set the default behavior.

like image 409
Luis R. Gonzalez Avatar asked Mar 06 '26 19:03

Luis R. Gonzalez


2 Answers

You can subclass the standard pd.DataFrame and redefine just the .sort_values method:

class MyDataFrame(pd.DataFrame):
    def sort_values(self,by,axis=0,ascending=False,inplace=False, 
                    kind='quicksort',na_position='last'):
        return super().sort_values(by,axis,ascending,inplace,kind)

foo = MyDataFrame({'z': [1,2,3,4]})
foo.sort_values('z')
#   z
#3  4
#2  3
#1  2
#0  1
foo.sort_values('z',ascending=True)
#   z
#0  1
#1  2
#2  3
#3  4
like image 141
DYZ Avatar answered Mar 08 '26 10:03

DYZ


Another option would be to declare the settings you often use in the beginning of your code and pass them as kwargs.

Personally I would, however, write it out every time.

import pandas as pd
p = {"ascending":False, "inplace":True}


df = pd.DataFrame({
    'col1': [1,6,2,5,9,3]
})

df.sort_values(by='col1', **p)

print(df)

Returns:

   col1
4     9
1     6
3     5
5     3
2     2
0     1
like image 37
Anton vBR Avatar answered Mar 08 '26 10:03

Anton vBR