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.
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
You could make your own wrapper for this
def sort_values(df, *args, **kwargs):
if len(args) < 2 and "ascending" not in kwargs:
kwargs["ascending"] = False
return df.sort_values(*args, **kwargs)
But you will have to use it as a function. (You can pass other parameters after 1st agument (dataframe).
print(sort_values(my_df, data))
You cannot modify the pandas function. but a good alternative would be to wrap it in your own function.
def sort_values(df, sort_by):
return df.sort_values(ascending=False, by=sort_by)
sort_values(data, ['col1']
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
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.