按日期时间间隔计算记录数

Count number of records by datetime interval

我将一些数据加载到 Pandas DataFrame 中,我想将这些数据聚合到日期时间间隔中并计算每个间隔内的记录数。问题是我发现聚合到日期时间间隔并计算每个间隔内的记录数的方法似乎相当笨拙,而且可能不是最有效的。更改我要分组的间隔以计算推文数量也很痛苦。

data = [[Timestamp('2016-10-26 18:47:53'), 'mention'],
        [Timestamp('2016-10-26 20:28:35'), 'retweet'],
        [Timestamp('2016-10-26 20:57:38'), 'tweet'],
        [Timestamp('2016-10-26 21:36:37'), 'mention'],
        [Timestamp('2016-10-26 22:49:08'), 'tweet'],
        [Timestamp('2016-10-27 00:10:19'), 'tweet'],
        [Timestamp('2016-10-27 01:14:46'), 'tweet'],
        [Timestamp('2016-10-27 01:45:03'), 'retweet'],
        [Timestamp('2016-10-27 02:33:03'), 'tweet'],
        [Timestamp('2016-10-27 05:55:52'), 'retweet'],
        [Timestamp('2016-10-27 14:26:57'), 'mention'],
        [Timestamp('2016-10-27 17:46:42'), 'tweet'],
        [Timestamp('2016-10-27 17:53:33'), 'retweet'],
        [Timestamp('2016-10-27 18:53:38'), 'tweet'],
        [Timestamp('2016-10-27 21:02:00'), 'retweet'],
        [Timestamp('2016-10-27 21:23:50'), 'retweet'],
        [Timestamp('2016-10-27 22:21:01'), 'retweet'],
        [Timestamp('2016-10-28 05:30:02'), 'retweet'],
        [Timestamp('2016-10-28 13:11:01'), 'retweet'],
        [Timestamp('2016-10-28 16:55:13'), 'retweet'],
        [Timestamp('2016-10-28 18:25:02'), 'retweet'],
        [Timestamp('2016-10-28 18:54:44'), 'retweet'],
        [Timestamp('2016-10-28 19:22:14'), 'tweet'],
        [Timestamp('2016-10-28 19:23:20'), 'tweet'],
        [Timestamp('2016-10-28 22:33:03'), 'tweet']]

df = pd.DataFrame(data, columns=['datetime', 'type'])

df['type'].groupby([df.datetime.dt.month, df.datetime.dt.day,df.datetime.dt.hour]).count().plot(kind="line")

如果你也能帮我弄清楚如何将 'type' 分成 3 行,加分加分! :)

pre pandas 0.19

df.set_index('datetime').resample('H').type.count().plot()

post pandas 0.19

df.resample('H', on='datetime').type.count().plot()


为了加分

df.set_index('datetime').groupby('type') \
    .resample('H').size().unstack(0, fill_value=0) \
    .plot()