根据字符串值列对熊猫数据框行进行排序

时间:2020-02-03 10:25:31

标签: python string pandas sorting rows

我有以下数据框:

        month       price
0       April  102.478015
1      August   94.868053
2    December   97.278205
3    February  100.114510
4     January   99.419109
5        July   93.402928
6        June   96.114224
7       March  101.297762
8         May  102.905340
9    November   97.952169
10    October   95.606478
11  September   94.226803

我希望月份按连贯的顺序排列(第一行的1月到第12行的12月)。我该怎么办?

如有必要,您可以复制此数据框,然后执行

pd.read_clipboard(sep='\s\s+')

在Jupyter笔记本上放置数据框

1 个答案:

答案 0 :(得分:2)

将值转换为有序的categorical,因此可以使用DataFrame.sort_values

cats = ['January','February','March','April','May','June',
        'July','August','September','October','November','December']
df['month'] = pd.CategoricalIndex(df['month'], ordered=True, categories=cats)
#alternative
#df['month'] = pd.Categorical(df['month'], ordered=True, categories=cats)
df = df.sort_values('month')
print (df)
        month       price
4     January   99.419109
3    February  100.114510
7       March  101.297762
0       April  102.478015
8         May  102.905340
6        June   96.114224
5        July   93.402928
1      August   94.868053
11  September   94.226803
10    October   95.606478
9    November   97.952169
2    December   97.278205