我有一个pandas数据框,其中包含事件列表。每个事件都有一个时间戳。它们是按时间排序的。
id time
68851 2017-11-06 17:07:09
34067 2017-11-06 17:51:53
99838 2017-11-06 18:38:58
81212 2017-11-06 18:47:47
34429 2017-11-06 19:01:52
我想扩展每一行,以包括过去一个小时和一天中发生了多少个事件。因此,上表将变为(eil =“ events in last”):
id time eil_hour eli_day
68851 2017-11-06 17:07:09 1 1
34067 2017-11-06 17:51:53 2 2
99838 2017-11-06 18:38:58 2 3
81212 2017-11-06 18:47:47 3 4
34429 2017-11-06 19:01:52 3 5
如果第一个表存储在df
中,这是我在Pandas中尝试做的事情:
def eventsInLast(date):
ddict = {"eil_hour": 0, "eil_minute": 0}
#loop over timedeltas
for c, delta in [("eil_hour",timedelta(hours=1)),("eil_minute",timedelta(minutes=1))]:
#find number of rows with dates between current row - delta and delta
n = ((df["time"] >= (date-delta)) & (df["time"] <= date)).sum()
ddict[c] = n
if n==0:
break #break if no events in last hour, since there won't be any in last minute either
return pd.Series(ddict)
pd.concat([df,df["time"].apply(eventsInLast)],axis=1)
问题是这非常慢,并且我正在处理大型数据集。谁能建议一种更有效的方法来做同样的事情?
答案 0 :(得分:1)
尝试一下
df['eil_hour'] = df.rolling('1h', on='time')['event'].sum() # sum or count??
df['eil_day'] = df.rolling('1d', on='time')['event'].sum()