我有一个数据框架,以日期时间为索引,在不同的列中有推文以及其他统计,如喜欢的数量。我想用每小时的时间间隔重新取样df,这样我就可以得到所有的推文和每小时所有统计的总和,我已经用下面的代码完成了。
df.resample('60min').sum()
问题是我的推文栏消失了... ... 我需要它来进行情感分析.我是新的编程,所以提前感谢你的阅读!
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