Skip to main content
 首页 » 编程设计

python之计算与 pandas 框架中的条件匹配的行数(如果可能,使用数据的排序)

2024年10月17日6sharpest

数据集描述:

我有一个看起来像这样的数据集(按键排序,这也意味着它按 offset_time_stamp 排序):

key       offset_time_stamp       person          7_sec_count 
1         0                       A               0 
2         0                       B               0 
3         0                       A               1 
4         1                       A               2 
5         2                       B               1 
6         7                       A               1 
7         9                       B               0 

行数约为 2000 万。唯一人数约为 400 万(每个人在过去 7 秒内的记录从 0 到 10k+)。

我想计算那个人在过去 7 秒内出现的行数(使用 offset_time_stamp

计算)

这是我尝试过的:

def get_count(x): 
  return [data[the_condition].count() for row in x.iterrows()] 
 
counts = data.groupby(person).apply(get_count)  

这段代码运行了大约 6 个小时。我想用 1 秒重新采样,但它不起作用,因为数据集在那一秒内对同一个人有几行 - 而且我没有微秒级数据。当时间戳相同时,我需要使用键值来解决关系问题。

我现在想做什么?

我现在想用 1 亿行重新运行相同的练习,并将 7 秒窗口增加到 7000 秒。 现有代码预计在 5 天内运行。

如何使这个计算更快?我希望它能在 2-3 小时内完成运行,这样我就可以分析更大的数据集。我可以将解决方案移植到另一种语言或使用纯粹基于 numpy 的解决方案而不是 pandas。

我还可以使用数据的排序特性吗?我在按人分组并减去刚好落在 7 秒窗口之外的最后一行的 cumcount 后尝试了 cumcount。花了太长时间,可能是因为我写的方式:

data_cumcount = data.groupby(person).cumcount() + 1 
 
def get_subtractor(current_ts, person, index): 
    global data_cumcount 
    to_consider = sorted(person_level_indices[person][:person_level_indices[person].index(index)], reverse=True) 
    for index in to_consider: 
        if data_dict[index] <= current_ts: # -7 was already done and passed to this function 
            return data_cumcount[index] 
    return 0 
 
def get_count(x): 
    global data_cumcount 
    return data_cumcount[x.name] - get_subtractor(x[TIME_STAMP]-7, x[person], x.name) - 1 
 
counts = data.apply(get_count, axis=1) 

我猜测 get_subtractor 中的 for 循环导致它在这种方法中花费大量时间。

我尝试了其他几种方法,包括递归,但 data.groupby(person).apply(get_count) 是我看似不太高效的代码中表现最好的方法。

请您参考如下方法:

编辑:使用建议的时间戳排序,以及 searchsorted 是矢量化的事实,我能够将执行时间缩短为 3。

def get_count(dfg): 
    return pd.Series( 
        np.arange(len(dfg)) - dfg.offset_time_stamp.searchsorted(dfg.offset_time_stamp - 6), 
        index=dfg.index 
    ) 
 
df['count'] = df.groupby('person').apply(get_count).reset_index(level=0, drop=True) 

请注意 searchsorted返回的不是系列的索引,而是底层 numpy 数组中的位置。因此,计数只是当前位置(即 np.arange)与 searchsorted 返回的位置之间的差异。

将结果转换为系列会产生开销,但我需要它在最后重新分配结果。如果您找到一种直接使用 numpy 值的方法,您可以再次将时间减半。


原答案:

根据您在 cumcount 中提到的思路,可能有一个解决方案,但与此同时,这可能已经更快了:

def get_count(dfg): 
    return dfg.apply(lambda row: dfg[dfg.offset_time_stamp > row['offset_time_stamp'] - 7].loc[:row.name-1].count(), axis=1) 
 
df.groupby('person').apply(get_count) 

我使用 native 切片和选择而不是您的 iterrows 循环。请注意,将函数逐行应用于数据框时,row.name 是原始数据框的索引。