Merging two dataframe using ID and asof(使用ID和ASOF合并两个数据帧)
本文介绍了使用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-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')
这篇关于使用ID和ASOF合并两个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用ID和ASOF合并两个数据帧


基础教程推荐
猜你喜欢
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01