Python Pandas数据采样/聚合

时间:2016-09-20 02:43:19

标签: python python-2.7 pandas aggregate pandas-groupby

我有一个巨大的逗号分隔日期时间,unique_id数据集,如下所示。

datetime, unique_id
2016-09-01 19:50:01, bca8ca1c91d283212faaade44c6185956265cc09 
2016-09-01 19:50:02, ddd20611d47597435412739db48b0cb04599e340 
2016-09-01 19:50:10, 5b8776d7dc0b83f9bd9ad70a403a5f605e37d4d4 
2016-09-01 19:50:14, 2b8a2d7179fe08f8c87d125ad5bc41b5eb79d06f 
2016-09-01 19:50:20, 902c4428e08f4324a70a5a4bbfabb657c4a9ffc3 
2016-09-01 19:50:23, bca8ca1c91d283212faaade44c6185956265cc09 
2016-09-01 19:51:10, a2e6521c66e7207398ffe3d4e5bab449f75e616d 
2016-09-01 19:51:11, a2e6521c66e7207398ffe3d4e5bab449f75e616d 
2016-09-01 19:51:20, f7cfa02eeb3feed2a0f616185312925e4190c66b 
2016-09-01 19:51:30, 0bb21868b55b832f1315438ccdb9c508cf37b8b4 
2016-09-01 19:51:40, cb3cfe7bc2fa40d20db23ddc209d2062e10c2ce3 
2016-09-01 19:51:50, 2b8a2d7179fe08f8c87d125ad5bc41b5eb79d06f 
2016-09-01 19:51:55, 099ba09cd602f9d9bb20f5ebc195686dc133b464 
2016-09-01 19:52:00, c300e6a54013ee56facab294e326aa523cd4c60a 
2016-09-01 19:53:01, bca8ca1c91d283212faaade44c6185956265cc09 
2016-09-01 19:53:04, 902c4428e08f4324a70a5a4bbfabb657c4a9ffc3 
2016-09-01 19:53:10, 5b8776d7dc0b83f9bd9ad70a403a5f605e37d4d4 
2016-09-01 19:53:11, 2b8a2d7179fe08f8c87d125ad5bc41b5eb79d06f 
2016-09-01 19:53:17, bca8ca1c91d283212faaade44c6185956265cc09 
2016-09-01 19:53:20, 0fe1560c790c78b960b66e7d7336dd76d2ea12cf 
2016-09-01 19:53:40, ddd20611d47597435412739db48b0cb04599e340 

使用Python Pandas,我希望每unique ids计算minute。 对于前。

datetime, count(unique_id)
2016-09-01 19:50:00, 5 
2016-09-01 19:51:00, 6 
2016-09-01 19:52:00, 1 
2016-09-01 19:53:00, 6 

我尝试使用pandas.DataFrame.resample,但看起来这不是解决此问题的方法。

resampled_data = raw_df.set_index(pd.DatetimeIndex(raw_df["datetime"])).resample("1T")

2 个答案:

答案 0 :(得分:2)

您可以将日期时间设置为索引,并使用pandas.TimeGrouper创建组变量,该变量可以按时间对指定的频率对数据框进行分组,然后计算唯一ID的数量:

import pandas as pd
df.set_index(pd.to_datetime(df.datetime)).groupby(pd.TimeGrouper(freq = "min"))['unique_id'].nunique()

#           datetime
#2016-09-01 19:50:00    5
#2016-09-01 19:51:00    6
#2016-09-01 19:52:00    1
#2016-09-01 19:53:00    6
#Freq: T, Name: unique_id, dtype: int64

答案 1 :(得分:2)

我认为您需要指定Series - ['unique_id']并添加Resampler.nunique

resampled_data = raw_df.set_index(pd.DatetimeIndex(raw_df["datetime"]))
                       .resample("1T")['unique_id']
                       .nunique()
print (resampled_data)
2016-09-01 19:50:00    5
2016-09-01 19:51:00    6
2016-09-01 19:52:00    1
2016-09-01 19:53:00    6
Freq: T, Name: unique_id, dtype: int64