0
votes

I have a question about sorting a dataframe in Pandas.
For example I have a dataframe 'df_cars' with the columns 'Year','Model','Mileage','Price'.
And I want to display the dataframe ordered by 'Year' (desc) and 'Mileage' (asc).
I know how to sort by multiple colulmns but the same order (asc/or desc):
print(df_cars.sort_values(by=['Year','Price'], inplace = False, ascending = True)

The values for 'Year' and 'Price' will be both ordered in ascending way.
But if I have several values for the same year, and want to see the years in ascending order and the prices in descending order.
What should I do?
Thanks in advance.

2
Specify a list of bool that matches the list of by for the ascending parameter. - Nathan Furnal
use a list ascending = [True, False] - David Erickson

2 Answers

0
votes

Try:

print(df_cars.sort_values(by=['Year','Price'], inplace = False, ascending = (0,1))
0
votes

I will try. By myself I did:

print(df_cars.sort_values(by=['Year','Price'],
                          inplace = False, 
                          ascending = (False,True))

I suppose it is the same as your suggestion. I tried both versions and got the same output.

Thank you.