Reputation: 8628
I need to order rows by date and time grouping them by ID
:
df =
ID TYPE DATETIME
1 A 12/18/2015 23:02:00
1 A 12/17/2015 12:00:09
1 A 12/18/2015 18:04:08
2 B 12/20/2015 15:03:05
2 B 12/18/2015 14:02:07
The result should be this one:
result =
ID TYPE DATETIME
1 A 12/17/2015 12:00:09
1 A 12/18/2015 18:04:08
1 A 12/18/2015 23:02:00
2 B 12/18/2015 14:02:07
2 B 12/20/2015 15:03:05
How can I do it?
df.groupby("ID").sort(...)
Upvotes: 1
Views: 60
Reputation: 862611
You can use sort_values
and specify columns by parameter by
, ascending
can be omit if need default ascending sorting:
#if df['DATETIME'].dtype != datetime, convert first
df.DATETIME = pd.to_datetime(df.DATETIME)
df = df.sort_values(by=['ID','TYPE','DATETIME'])
print (df)
ID TYPE DATETIME
1 1 A 2015-12-17 12:00:09
2 1 A 2015-12-18 18:04:08
0 1 A 2015-12-18 23:02:00
4 2 B 2015-12-18 14:02:07
3 2 B 2015-12-20 15:03:05
Upvotes: 1
Reputation: 940
You could try:
df.sort_values(['ID', 'DATETIME'], ascending=[True, True])
(I think df.sort() is now deprecated)
Upvotes: 1