简体   繁体   中英

Pandas: How to sort group data by datetime?

as an extension to the question Pandas: Group Data by column A, Filter A by existing values of column B my data has now a datetime for each value, which looks like this:

2011-10-01 20:24:21

EDIT : at first the time data had the right structure, but was from dtype: object. I changed it by using:

dataset['Date']= pd.to_datetime(dataset['Date'])

Is this correct?

So at the moment, I have a dataset which structure looks like this:

_Group, Value, Date:_

A 2  **2011-10-01 20:24:21**

A 1   **2011-10-01 20:27:21**

A 3   **2011-10-01 20:25:21**

B 1   **2011-10-01 20:23:21**

B 2 **2011-10-01 20:26:21**

B 3 **2011-10-01 20:24:21**

B 3 **2011-10-01 20:25:21**

I want to order the values of each group depending on the datetime.

--> I already checked, that the datatime has the dtype: datetime, but when I try to order it (ascending), not all the datetimes are in the right order within a group. When I tried to order just the dates, then it works fine.

I tried the following code:

  dataset.sort_values('Date').sort_index(level='Group')

As a result, the dates are in the right order, but sometimes they aren't regarding the hours and seconds. Where is my mistake?

I'm thankful for any help!

您可以使用多个级别进行排序:

dataset.sort_values(['Group', 'Date'])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM