【问题标题】:How can i hourly resample a dataframe that has a column of tweets in it? (I would like to concatenate all tweets per hour)我如何每小时重新采样包含一列推文的数据框? (我想每小时连接所有推文)
【发布时间】:2020-08-19 04:28:16
【问题描述】:

我有一个数据框,它以日期时间为索引,并在不同的列中发布推文以及其他统计信息,如喜欢的数量。我想以每小时间隔重新采样 df,这样我就可以获得所有推文和每小时所有统计信息的总和,我使用以下代码完成了这项工作:

df.resample('60min').sum()

问题是我的推文栏消失了。我需要它来进行情绪分析。 我是编程新手,提前感谢您阅读本文!

【问题讨论】:

  • df.asfreq('H')?实际上,听起来你想按小时分组:df.groupby(df.index.floor('H')).agg(...)
  • 但问题是,我不知道如何编码,以便每小时连接所有推文,同时返回其他列的总和,如 number_of_retweets。

标签: python pandas tweepy


【解决方案1】:

IIUC 你会groupby 并使用agg

import numpy as np
import pandas as pd
# sample data
np.random.seed(1)
df = pd.DataFrame(np.transpose([np.random.randint(1,10, 1489), ['abc']*1489]),
                  index=pd.date_range('2020-01-01', '2020-02-01', freq='30T'),
                  columns=['num', 'tweet'])

# groupby the index floored to hour, sum the num col 
# and join the tweets with a semi-colon or what ever you want
df.groupby(df.index.floor('H')).agg({'num': sum, 'tweet': '; '.join})

                    num     tweet
2020-01-01 00:00:00  69  abc; abc
2020-01-01 01:00:00  61  abc; abc
2020-01-01 02:00:00  12  abc; abc
2020-01-01 03:00:00  87  abc; abc
2020-01-01 04:00:00  35  abc; abc

或者,如果您只想按原样加入字符串,则将所有内容相加:

df.groupby(df.index.floor('H')).agg(sum)

                    num   tweet
2020-01-01 00:00:00  69  abcabc
2020-01-01 01:00:00  61  abcabc
2020-01-01 02:00:00  12  abcabc
2020-01-01 03:00:00  87  abcabc
2020-01-01 04:00:00  35  abcabc

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 2021-07-24
    • 2023-01-28
    • 2023-03-19
    • 2019-08-31
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    相关资源
    最近更新 更多