1

I want to sort the values in column C in ascending order and values in column B in order "April","August","December" and any remaining values e.g NaN in current example. Can anyone help.

before

      A         B         C
0   354.7      April      4
1   278.8      NaN        4 
2   283.5      December   2
3  249.6       NaN        2
4    95.5      April      2
5    85.6      August     2
6    55.4      August     4
7   176.5      December   4
8   104.8      August     8
9   278.8      NaN        10
10   238.7     April      8
11  278.8      April      5
12    152      December   8

After :

      A         B       C
0    95.5     April     2
1    85.6     August    2
2   283.5     December  2
3  249.6      NaN       2
4   354.7     April     4
5    55.4     August    4
6   176.5     December  4
7   278.8     NaN       4  
8   278.8     April     5
9   238.7     April     8
10   104.8    August    8
11    152     December  8
12  278.8      NaN      10

1 Answer 1

4

Is this what you need ?

df.B=pd.Categorical(df.B,['December','April','August'])
df.sort_values(['C','B'])
Out[284]: 
        A         B   C
2   283.5  December   2
4    95.5     April   2
5    85.6    August   2
3   249.6       NaN   2
7   176.5  December   4
0   354.7     April   4
6    55.4    August   4
1   278.8       NaN   4
11  278.8     April   5
12  152.0  December   8
10  238.7     April   8
8   104.8    August   8
9   278.8       NaN  10
Sign up to request clarification or add additional context in comments.

2 Comments

sorting the values in column B alphabetically is not what i want. Is there a way to specify the order i want to use to sort values in column B. example - if i want "December" first, then "May" and then "August".
this is exactly what i wanted. Thanks for your help.

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.