Jeroen
Jeroen

Reputation: 841

Pandas sort sorted indices by datetime

I have the following dataframe:

               latitude  longitude       timestamp
name                                                  
testschip-1   51.822872   4.905615 2019-08-01 00:00:00
testschip-1   51.822876   4.905613 2019-08-01 00:00:57
testschip-1   51.822872   4.905613 2019-08-01 00:00:20
testschip-1   51.822880   4.905627 2019-08-01 00:00:27
testschip-1   51.822872   4.905613 2019-08-01 00:00:09
testschip-1   51.822872   4.905613 2019-08-01 00:00:39
testschip-1   51.822876   4.905613 2019-08-01 00:00:38
testschip-10  51.824749   4.965562 2019-08-01 00:00:56
testschip-10  51.827072   4.952107 2019-08-01 00:00:47
testschip-10  51.826794   4.954065 2019-08-01 00:00:19
testschip-10  51.826702   4.954648 2019-08-01 00:00:08
testschip-11  51.819588   4.962135 2019-08-01 00:00:57
testschip-11  51.819584   4.962165 2019-08-01 00:00:38
testschip-11  51.819588   4.962172 2019-08-01 00:00:08
testschip-11  51.819588   4.962122 2019-08-01 00:00:17

Per name (on the index) I would like to get the timestamp hierachically sorted. If I do:

df = df.sort_values(by='timestamp',ascending=True)

I sort by time, but I lose my sorted names on the indices. How do I keep my sorted indices and sort these indices by time?

Upvotes: 1

Views: 39

Answers (1)

bartonstanley
bartonstanley

Reputation: 1303

df = df.sort_values(by=['name', 'timestamp'], ascending=True)

The by parameter can either be a string or a list of strings, see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html

Upvotes: 1

Related Questions