使用Pandas匹配Indicator枚举为DataFrame补全缺失全零行
实现思路
- 预处理
IndiRelat:给数据列命名为Indicator,新增顺序索引列保留原始列表的排序和重复规则 - 提取
inp中的唯一Key值,生成每个Key与IndiRelat所有Indicator的全量配对组合,确保每个Key都对应完整的11条Indicator记录 - 以全量配对组合为左表,和原
inp表通过Key、Indicator两个字段做左连接 - 连接后除
Key、Indicator外的缺失字段统一填充为0,按Key和之前新增的顺序索引排序后删除临时列,得到最终结果
实现代码
import pandas as pd # 原有业务数据定义 inp = [[2, 'cvt' , -3, 5, 17, -2, -9, -0.2, 'RL'], [2, 'cv' , 0, 0, 0, 0, 0, 0, 'LL'], [2, 'sope' , 0, 0, 0, 0, 0, 0, 'SD'], [2, 'wix+' ,-13,-13, 2, 1,-62, -0.5, 'WI'], [2, 'wix-' , 0, 16, 6, 13, 0, 0.3, 'WI'], [4, 'sope' ,-42, 0, 29, 0, 0, -13, 'SD'], [4, 'cv' , 0, 0, 0, 0, 0, 0, 'LL'], [4, 'cvt' , 0, 0, 0, 0, 0, -1, 'RL'], [4, 'wix+' ,-18, -2, 19, 19, 3, -64, 'WI'], [4, 'wix-' , 0,-30, -2, -2, 32, 0, 'WI']] inp = pd.DataFrame(data = inp, columns = ['Key','Descr', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'Indicator']) # 处理Indicator映射表,保留原始顺序 IndiRelat_list = ['SD', 'LL', 'RL', 'SS', 'RR', 'WI', 'WI', 'WI', 'WI', 'QU', 'QU'] IndiRelat = pd.DataFrame(IndiRelat_list, columns=['Indicator']) IndiRelat['sort_idx'] = IndiRelat.index # 生成Key与Indicator的全量配对 unique_keys = inp[['Key']].drop_duplicates() unique_keys['tmp'] = 1 IndiRelat['tmp'] = 1 full_pairs = pd.merge(unique_keys, IndiRelat, on='tmp').drop('tmp', axis=1) # 左连接原有数据,缺失值填充0 result = pd.merge(full_pairs, inp, on=['Key', 'Indicator'], how='left').fillna(0) # 排序并清理临时列 result = result.sort_values(by=['Key', 'sort_idx']).drop('sort_idx', axis=1).reset_index(drop=True) # 输出最终结果 print(result)
如果需要和你示例里的Indicator顺序完全匹配,直接调整IndiRelat_list的顺序为你需要的顺序即可。
内容的提问来源于stack exchange,提问作者DaniV
相关产品推荐
相关产品推荐

