如何基于双键合并Pandas DataFrame并填充最近年份匹配值?
填充合并DataFrame后缺失的最近年份对应值
示例数据
首先定义问题中的两个DataFrame:
import pandas as pd tab1 = pd.DataFrame({ 'col1': ['A', 'A', 'A', 'B', 'B', 'C', 'C'], 'col2': [2017, 2018, 2019, 2017, 2019, 2017, 2018] }) tab2 = pd.DataFrame({ 'col1': ['A', 'A', 'A', 'B', 'B', 'C', 'C'], 'col2': [2017, 2019, 2020, 2017, 2020, 2017, 2018], 'col3': ['foo', 'fii', 'fee', 'boo', 'bii', 'coo', 'cii'] })
问题描述
将两个DataFrame以col1和col2为键左合并后,部分行的col3会出现缺失值(比如tab1中(A,2018)在tab2中无匹配),需要用tab2中对应col1分组内最近年份的col3值填充这些缺失,最终得到指定结果。
解决方案一:双向填充法(完全匹配示例结果)
通过左合并+分组排序+双向填充的方式,复现你需要的结果:
# 1. 左合并两个表,保留tab1所有行 merged = pd.merge(tab1, tab2, on=['col1', 'col2'], how='left') # 2. 按col1分组,每组内按年份排序后,先向后填充再向前填充 merged['col3'] = merged.groupby('col1').apply( lambda x: x.sort_values('col2')['col3'].bfill().ffill() ).reset_index(drop=True) # 输出最终结果 print(merged)
运行结果:
col1 col2 col3 0 A 2017 foo 1 A 2018 fii 2 A 2019 fii 3 B 2017 boo 4 B 2019 boo 5 C 2017 coo 6 C 2018 cii
解决方案二:merge_asof高效法(适合大数据量)
如果数据量较大,推荐使用pandas专门的merge_asof函数,按最近年份键合并有序数据:
# 先对两个表按分组键和年份排序 tab1_sorted = tab1.sort_values(['col1', 'col2']) tab2_sorted = tab2.sort_values(['col1', 'col2']) # 按col1分组,匹配col2最近的记录 merged_asof = pd.merge_asof( tab1_sorted, tab2_sorted, on='col2', by='col1', direction='nearest' ) # 注意:此方法中B的2019会匹配tab2中更近的2020,得到col3为bii,与示例结果略有差异 print(merged_asof)
内容的提问来源于stack exchange,提问作者Detox
相关产品推荐
相关产品推荐

