首页 > 解决方案 > Pandas:为每个行索引在数据集的子集中进行计算

问题描述

我有以下情况,我解决了,但为每个索引创建数据框子集的复杂性花费了太长时间。

对于 df 中的每个 id 和日期,我必须创建一个 df_search 的子集,其中包含以下内容

    lapse = 90
    period = df.loc[i, 'period']
    period_Nmonths_ago = (period - datetime.timedelta(lapse)).replace(day=1)
    
    #=== create the subset dataframe based on the id
    _id_df = df_search[df_search['id'] == _id].copy()
    
    #=== create another subset but just for the interval of N months ago.
    _id_df_interval = _id_df[(_id_df['period'] >= period_Nmonths_ago ) & (_id_df['period'] <= period)].copy()

    #=== do calculations on the time interval subset...
    cant_of_docs = len(list(_id_df_interval['document_id'].values))

依此类推,我对_id_df_interval进行计算,但最耗时的过程是生成这些子集。

有没有办法加快这些步骤的计算?也许是一种并行的方法?

标签: pythonpandasparallel-processingdatasetdask

解决方案


推荐阅读