使用ID和ASOF合并两个数据帧 [英] Merging two dataframe using ID and asof

查看:17
本文介绍了使用ID和ASOF合并两个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框要拼接在一起,左边的数据框有信息索引by(日期,ID),右边的数据框有信息索引by(Period,ID),周期是年-月。

结束时,我对左侧帧执行了GROUP BY ID,遍历各个组,在右侧帧上选择相同的组,然后对左侧数据框中组的索引执行AND ASF操作,如下所示:

def merge_func(base_df, si_df):  
    df_list = list()
    by_cusip = base_df.groupby('cusip8')

    for cusip, group in by_cusip:
        si_df_by_cusip = si_df[si_df.cusip==cusip]
        if len( si_df_by_cusip[ pd.notnull(si_df_by_cusip['sif'])]) > 0:
            group['sif'] = si_df_by_cusip['sif'].asof(group.index)
        else:
            group['sif'] = np.nan
        if len( si_df_by_cusip[ pd.notnull(si_df_by_cusip['si_cover'])]) > 0:
            group['sir'] = si_df_by_cusip['si_cover'].asof(group.index)
        else:
            group['sir'] = np.nan
        df_list.append(group)
    return pd.concat(df_list)

但此函数速度相当慢。有谁有办法使此合并功能更快、更高效?

您可能会发现这些链接与我正在尝试完成的内容相关:sample for doing asof-joinmerging tables with millions of rows

提前感谢您的意见和帮助!

推荐答案

您只需使用the "asof join" feature added to pandas 0.19

pd.merge_asof(df1, df2, left_on='date', right_on='period', by='ID')

这篇关于使用ID和ASOF合并两个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆