I have this:
A B C
1 4 string1
2 11 string2
1 13 string3
2 43 string4
And, I want to sort by both A and B at once, to get this:
A B C
1 4 string1
1 13 string3
2 11 string2
2 43 string4
Using the following didn't do the sort
data = data.sort_values(by=['A','B'], ascending=[True,True])
Discussion: If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query.
You can sort pandas DataFrame by one or multiple (one or more) columns using sort_values() method and by ascending or descending order. To specify the order, you have to use ascending boolean property; False for descending and True for ascending.
To sort by one column, you can use the SORT function or SORTBY function . In the example shown, data is sorted by the Group column. The formula in F5 is: = SORT ( B5:D14 , 3 ) Notice data is sorted in ascending order (A-Z) by default. How this...
To sort multiple columns independently in an ascending order, the following VBA code may help you, please do as this: 1. Hold down the ALT + F11keys to open theMicrosoft Visual Basic for Applicationswindow. 2. Click Insert> Module, and paste the following code in theModuleWindow. VBA code: Sort multiple columns independently at once:
If you want to sort multiple rows independently, here also is a VBA code for you. 1. Select the data that you want to sort based on each rows. 2. Hold down the ALT + F11 keys to open the Microsoft Visual Basic for Applications window.
After the ORDER BY keyword, add the name of the column by which you’d like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name ). You can modify the sorting order (ascending or descending) separately for each column.
I think you need assign output to new DataFrame
, parameter ascending
can be omit, because ascending=True
is default value in DataFrame.sort_values
:
data = data.sort_values(by=['A','B'])
print (data)
A B C
0 1 4 string1
2 1 13 string3
1 2 11 string2
3 2 43 string4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With