计算熊猫的日期

Noachr

我有一个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

这是我的尝试,如果第一个表存储在Pandas中df

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)

问题是这非常慢,而且我正在使用大型数据集。谁能建议一种更有效的方法来做同样的事情?

ipramusinto

尝试这个

df['eil_hour'] = df.rolling('1h', on='time')['event'].sum() # sum or count??
df['eil_day'] = df.rolling('1d', on='time')['event'].sum()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章