how to sort pandas dataframe from one column

后端 未结 6 1174
感情败类
感情败类 2020-11-22 06:35

I have a data frame like this:

print(df)

        0          1     2
0   354.7      April   4.0
1    55.4     August   8.0
2   176.5   December  12.0
3    9         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 07:22

    Just as another solution:

    Instead of creating the second column, you can categorize your string data(month name) and sort by that like this:

    df.rename(columns={1:'month'},inplace=True)
    df['month'] = pd.Categorical(df['month'],categories=['December','November','October','September','August','July','June','May','April','March','February','January'],ordered=True)
    df = df.sort_values('month',ascending=False)
    

    It will give you the ordered data by month name as you specified while creating the Categorical object.

提交回复
热议问题