gpt4 book ai didi

python - 使用 ID 和 asof 合并两个数据框

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:16 56 4
gpt4 key购买 nike

我有两个数据框,我希望将它们连接在一起,其中左侧数据框的信息索引为(日期,ID),右侧数据框的信息索引为(期间,ID),其中期间为年月。

我最终对左帧按 ID 进行分组,迭代组,在右帧上选择相同的组,然后对左数据帧中组的索引执行 asof 操作,如下所示:

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-join , merging 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')

关于python - 使用 ID 和 asof 合并两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672088/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com