pandas按多列排序

时间:2018-04-11 04:37:17

标签: pandas

我想按升序对C列中的值进行排序,并按顺序排列B列中的值" 4月"," 8月"," 12月"和当前例子中的任何剩余值,例如NaN。任何人都可以提供帮助。

之前

      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

之后:

      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 个答案:

答案 0 :(得分:2)

这是你需要的吗?

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