简体   繁体   English

熊猫groupby日期每天选择最早

[英]pandas groupby date select earliest per day

I have the following dataset: 我有以下数据集:

            value            timestamp
0            Fire  2017-10-03 14:33:52
1           Water  2017-10-04 14:33:48
2            Fire  2017-10-04 14:33:45
3            Fire  2017-10-05 14:33:30
4           Water  2017-10-03 14:33:40
5           Water  2017-10-05 14:32:13
6           Water  2017-10-04 14:32:01
7            Fire  2017-10-03 14:31:55

I want to group this set by timestamp per day and then only select the earliest row per day. 我想按每天的timestamp将此集合分组,然后仅选择每天最早的行。 For the above example the following should be the result: 对于上面的示例,结果应为:

            value            timestamp
1           Water  2017-10-05 14:32:13
2           Water  2017-10-04 14:32:01
3            Fire  2017-10-03 14:31:55

For example, for the day 2017-10-03 there are 3 entries but I only want the earliest on that day. 例如,对于2017-10-03 3日这一天,有3个条目,但是我只希望最早的那一天。

If you have unique index, you can use idxmin on timestamp to find out the indices of the minimum timestamp and extract them with loc : 如果您有唯一索引,则可以在timestamp上使用idxmin来找出最小时间戳的索引,并使用loc提取它们:

df.timestamp = pd.to_datetime(df.timestamp)
df.loc[df.groupby(df.timestamp.dt.date, as_index=False).timestamp.idxmin()]

#   value             timestamp
#7   Fire   2017-10-03 14:31:55
#6  Water   2017-10-04 14:32:01
#5  Water   2017-10-05 14:32:13

Just Making Sure 只是确定

df.timestamp = pd.to_datetime(df.timestamp)

Solution

d1 = df.sort_values('timestamp')
d1[~d1.timestamp.dt.date.duplicated()]

   value           timestamp
7   Fire 2017-10-03 14:31:55
6  Water 2017-10-04 14:32:01
5  Water 2017-10-05 14:32:13

Use dt.floor and head : 使用dt.floorhead

df.sort_values('timestamp').groupby(df['timestamp'].dt.floor('D')).head(1)

Output: 输出:

   value           timestamp
7   Fire 2017-10-03 14:31:55
6  Water 2017-10-04 14:32:01
5  Water 2017-10-05 14:32:13

Or 要么

df.groupby(df.timestamp.dt.date).apply(lambda x:x[x.timestamp==min(x.timestamp)])
Out[714]: 
              value           timestamp
timestamp                              
2017-10-03 7   Fire 2017-10-03 14:31:55
2017-10-04 6  Water 2017-10-04 14:32:01
2017-10-05 5  Water 2017-10-05 14:32:13

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

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