Sort a pandas's dataframe series by month name?

前端 未结 6 1726
无人及你
无人及你 2020-12-01 06:09

I have a Series object that has:

    date   price
    dec      12
    may      15
    apr      13
    ..

Problem statement:

6条回答
  •  攒了一身酷
    2020-12-01 06:40

    I would use the calender module and reindex:

    series.str.capitalize helps capitalizing the series , then we create a dictionary with the calender module and map with the series to get month number.

    Once we have the month number we can sort_values() and get the index. Then reindex .

    import calendar
    df.date=df.date.str.capitalize() #capitalizes the series
    d={i:e for e,i in enumerate(calendar.month_abbr)} #creates a dictionary
    #d={i[:3]:e for e,i in enumerate(calendar.month_name)} 
    df.reindex(df.date.map(d).sort_values().index) #map + sort_values + reindex with index
    

      date  price
    2  Apr     13
    1  May     15
    0  Dec     12
    

提交回复
热议问题