我有一个带月份列的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
答案 0 :(得分:2)
如果需要解决方案,如果缺少字典中的某些月份和所有月份,则可以正常工作,请使用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
答案 1 :(得分:1)
您可以使用df.loc
或df.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