Python中如何按特定偏移索引获取列表值(含nan处理)
基于偏移索引列表生成目标列表
问题示例
给定两个列表:
list_a = [10, 20, 30, 40, 50, 60, 70] list_b = [10, 11, 12, float('nan'), float('nan'), float('nan'), 16]
其中list_b是list_a的索引映射列表,但索引起始值为10(而非常规的0),nan元素表示对应位置无需处理,需生成目标列表list_c = [10, 20, 30, nan, nan, nan, 70]。
解决方案
基础Python实现
借助math.isnan判断缺失值,通过列表推导式快速生成结果:
import math list_a = [10, 20, 30, 40, 50, 60, 70] list_b = [10, 11, 12, float('nan'), float('nan'), float('nan'), 16] # 定义索引偏移量:list_b的起始索引10对应list_a的0索引 offset = 10 list_c = [list_a[int(idx) - offset] if not math.isnan(idx) else float('nan') for idx in list_b] print(list_c) # 输出:[10, 20, 30, nan, nan, nan, 70]
逻辑说明:
- 遍历
list_b的每个元素,判断是否为nan - 非
nan元素转为整数后减去偏移量,得到list_a的真实索引,取出对应值 nan元素直接保留
Pandas实现(适合大型数据集)
如果处理带缺失值的大规模数据,用Pandas更便捷:
import pandas as pd list_a = [10, 20, 30, 40, 50, 60, 70] list_b = [10, 11, 12, pd.NA, pd.NA, pd.NA, 16] offset = 10 # 将list_b转为Series,用apply处理每个元素 list_c = pd.Series(list_b).apply(lambda x: list_a[int(x)-offset] if pd.notna(x) else pd.NA).tolist() print(list_c) # 输出:[10, 20, 30, <NA>, <NA>, <NA>, 70]
内容的提问来源于stack exchange,提问作者Wenjie Yu
相关产品推荐
相关产品推荐

