按日期时间间隔

时间:2016-10-29 00:08:56

标签: python pandas group-by pandas-groupby

我将一些数据加载到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")

奖励积分如果您还可以帮助我弄清楚如何将“打字”划分为3个单独的行! :)

1 个答案:

答案 0 :(得分:6)

大熊猫0.19

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

张贴大熊猫0.19

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

enter image description here

获得奖励积分

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

enter image description here