在熊猫中排列字符串月份行的最简单方法是什么

时间:2020-06-08 10:33:52

标签: python pandas

我有一个带月份列的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

2 个答案:

答案 0 :(得分:2)

如果需要解决方案,如果缺少字典中的某些月份和所有月份,则可以正常工作,请使用Series.mapSeries.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

或使用ordered categoricals

#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

答案 1 :(得分:1)

您可以使用df.locdf.reindex

In [2048]: new_order = ['April','May','June','January']

In [2051]: df.set_index('Month', inplace=True)

In [2071]: df.loc[new_order].reset_index()    
Out[2071]: 
     Month  Value Details
0    April     12     J11
1      May      8     Y21
2     June     13     K03
3  January     10     H12

OR

In [2051]: df.reindex(new_order, axis=0).reset_index() 
Out[2071]: 
         Month  Value Details
    0    April     12     J11
    1      May      8     Y21
    2     June     13     K03
    3  January     10     H12