I have a df with a month column which is string:
Month Value Details
January 10 H12
April 12 J11
June 13 K03
May 08 Y21
I need to arrange the month in from April to March
model. Which is the easiest way to do this? Desired result:
Month Value Details
April 12 J11
May 08 Y21
June 13 K03
January 10 H12
If need solution which working correctly if missing some months and all months in list of dictionary use Series.map
with Series.argsort
and then change order by 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
Or use 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
You can use df.loc
or 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.