0

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
1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. How would it be done if I wanted to order or the animals column to be dogs, pigs, cats?
@user3133136: dogs-pigs-cats is not a natural ordering, so the sort function won't handle that (unless you map those values to the ordering you desire). You can use the ascending option to change the order - df.sort(['animals', 'day'], ascending=[False, True]), if you want animals to be reverse sorted and day to be incrementally sorted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.