Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by two columns at once

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])
like image 254
Thirst for Knowledge Avatar asked Jan 27 '17 19:01

Thirst for Knowledge


People also ask

Can we use order by for 2 columns?

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.

How do you sort values in two columns?

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.

How do I sort data by one column in Excel?

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...

How to sort multiple columns independently in an ascending order?

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:

How to sort multiple rows independently in Excel VBA?

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.

How do you sort records by order in a list?

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.


1 Answers

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
like image 144
jezrael Avatar answered Sep 21 '22 04:09

jezrael