简体   繁体   English

熊猫:如何按日期时间对组数据进行排序?

[英]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: 作为对Pandas问题的扩展:按A列对数据进行分组,按B列的现有值过滤A,我的数据现在具有每个值的日期时间,如下所示:

2011-10-01 20:24:21

EDIT : at first the time data had the right structure, but was from dtype: object. 编辑 :起初,数据具有正确的结构,但来自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. ->我已经检查了datatime是否具有dtype:datetime,但是当我尝试对其进行排序(升序)时,并非所有datetime在组中的顺序都正确。 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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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