Pandas如何将DataFrame整数值匹配到另一表的区间并映射对应字段
Pandas编码区间匹配实现行业分类映射
问题场景
现有两个Pandas DataFrame,需要根据整数编码的区间归属完成字段值匹配更新:
- 主表DF1:已拆分
CodeRange列生成Start、End两个int类型列存储区间上下限,同时存储区间对应的标准行业分类Sector,样例数据如下:
CodeRange Sector Start End 0 0100-0999 Agriculture, Forestry and Fishing 0100 0999 1 1000-1499 Mining 1000 1499 2 1500-1799 Construction 1500 1799 3 1800-1999 not used 1800 1999 4 2000-3999 Manufacturing 2000 3999 5 4000-4999 Transportation, Communications, Electric, Gas ... 4000 4999 6 5000-5199 Wholesale Trade 5000 5199 7 5200-5999 Retail Trade 5200 5999 8 6000-6799 Finance, Insurance and Real Estate 6000 6799 9 7000-8999 Services 7000 8999 10 9100-9729 Public Administration 9100 9729 11 9900-9999 Nonclassifiable 9900 9999
- 待匹配表DF2:存储SIC整数编码和原始分类值,需要逐行判断
SICCode落在DF1的哪个[Start, End]闭区间内,将对应行的Sector值替换为DF1匹配区间的标准分类值,样例数据如下:
SICCode Sector 0 1230 Agro 1 4974 Utils 2 5120 shops 3 9997 Utils
匹配完成后的预期DF2效果:
SICCode Sector 0 1230 Agriculture, Forestry and Fishing 1 4974 Transportation, Communications, Electric, Gas ... 2 5120 Wholesale Trade 3 9997 Nonclassifiable
实现方案
优先使用Pandas原生IntervalIndex完成区间匹配,性能远高于逐行循环判断,代码如下:
import pandas as pd # 基于DF1的区间上下限构建闭区间索引 interval_idx = pd.IntervalIndex.from_arrays( left=DF1['Start'], right=DF1['End'], closed='both' # 匹配[Start, End]闭区间规则,包含端点值 ) # 建立编码到行业分类的映射关系,直接替换DF2的Sector列 sector_mapping = DF1.set_index(interval_idx)['Sector'] DF2['Sector'] = DF2['SICCode'].map(sector_mapping)
注意事项
- 该方法在万级以上数据量场景下性能优势明显,避免使用逐行
apply+条件判断的低效写法 - 如果业务规则是左闭右开区间,只需要把
closed参数调整为'left'即可 - 若存在SICCode不在DF1任何区间内的情况,匹配结果会返回
NaN,可通过fillna()方法按需填充默认值
内容的提问来源于stack exchange,提问作者risky2109
相关产品推荐
相关产品推荐

