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

标签 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 行,则加分! :)

最佳答案

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()

enter image description here


奖励积分

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

enter image description here

关于python - 按日期时间间隔计算记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40314742/

相关文章:

python - 如何在 Python 中按日期对 DataFrame 进行排序?

python - 避免对子类进行重复验证

python - Redis时间序列与python : ResponseError: unknown command 'TS.CREATE'

python - 如何使用 Beautiful Soup 提取 "alt"的文本

python - Pyspark 窗口函数计算站点之间的公交数量

python - 具有不同 X 轴顺序的 Pandas groupby 图

python - Pandas 从一系列混合数据中找到最大值

php - mysql 组排序

python - 列表中的 Pandas groupby 值

php - mysql 组通过返回不正确的结果