Pandas - how to properly sort week and year numbers formatted as strings?

Naveen Kumar :

I have a pandas dataframe like this, which sorted like:

>>> weekly_count.sort_values(by='date_in_weeks', inplace=True)
>>> weekly_count.loc[:9,:]

  date_in_weeks count
0   1-2013      362
1   1-2014      378
2   1-2015      201
3   1-2016      294
4   1-2017      300
5   1-2018      297
6   10-2013     329
7   10-2014     314
8   10-2015     324
9   10-2016     322

in above data, first column, all rows of date_in_weeks are simply "week number of a year - year". I now want to sort it like this:

  date_in_weeks count
0   1-2013      362
6   10-2013     329
1   1-2014      378
7   10-2014     314
2   1-2015      201
8   10-2015     324
3   1-2016      294
9   10-2016     322
4   1-2017      300
5   1-2018      297

How do i do this?

jezrael :

Use Series.argsort with converted to datetimes with format %W week number of the year, link:

df = df.iloc[pd.to_datetime(df['date_in_weeks'] + '-0',format='%W-%Y-%w').argsort()]
print (df)
  date_in_weeks  count
0        1-2013    362
6       10-2013    329
1        1-2014    378
7       10-2014    314
2        1-2015    201
8       10-2015    324
3        1-2016    294
9       10-2016    322
4        1-2017    300
5        1-2018    297

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3957&siteId=1