user3133136
user3133136

Reputation: 37

Pandas - how to sort a DataFrame via custom sorting of a column?

Below is the output for my DataFrame. I would like to sort the DataFrame by the column animals and subsequently by day. How can I sort animals in the following order: dogs, pigs, cats? Thanks.

index     animals     day     number 
0          dogs        1         3
1          cats        2         1
2          dogs        3         4
3          pigs        4         0
4          pigs        5         6
5          cats        6         1

Upvotes: 0

Views: 725

Answers (1)

Shashank Agarwal
Shashank Agarwal

Reputation: 2804

You can pass the columns to sort by as a list -

In [30]: df.sort(['animals', 'day'])
Out[30]: 
  animals  day  number
1    cats    2       1
5    cats    6       1
0    dogs    1       3
2    dogs    3       4
3    pigs    4       0
4    pigs    5       6

The order of columns determines how the dataframe gets sorted first, and how ties are broken.

Upvotes: 3

Related Questions