首页 > 解决方案 > 在 Pandas 中排列字符串 Month 行的最简单方法是什么

问题描述

我有一个带有月份列的df,它是字符串:

Month      Value     Details
January      10        H12
April        12        J11
June         13        K03
May          08        Y21

April to March我需要从模型中安排月份。哪种方法最简单?期望的结果:

Month      Value     Details
April        12        J11
May          08        Y21
June         13        K03
January      10        H12

标签: pythonpandas

解决方案


如果需要在字典列表中缺少某些月份和所有月份的情况下正常工作的解决方案,请使用Series.map以下Series.argsort命令更改顺序DataFrame.iloc

d = {'April':1,'May':2,'June':3,'July':4,'January':12}

df = df.iloc[df['Month'].map(d).argsort()]
print (df)
     Month  Value Details
1    April     12     J11
3      May      8     Y21
2     June     13     K03
0  January     10     H12

或使用有序分类

#add another months
c = ['April','May','June','July','January']
df['Month'] = pd.Categorical(df['Month'], categories=c, ordered=True)

df = df.sort_values('Month')
print (df)
     Month  Value Details
1    April     12     J11
3      May      8     Y21
2     June     13     K03
0  January     10     H12

推荐阅读