sorting data with a column of data needs to be grouped in python

Convert Date column to datetimes and Name to ordered Categiricals for correct order in output DataFrame:

df['Date'] = pd.to_datetime(df['Date'], format='%b %y')

df['Name'] = pd.Categorical(df['Name'], ordered=True, categories=df['Name'].unique())

df = df.sort_values(['Name','Date'])
print (df)
   ID       Date Name
0   1 2019-01-01    B
3   4 2019-04-01    B
1   2 2019-03-01    A
5   6 2019-06-01    A
2   3 2019-04-01    C
4   5 2019-05-01    C

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top