Skip to main content
 首页 » 编程设计

python之从另一个列表中删除一个列表中对应于 nan 的项目

2025年05月04日11xxx_UU

对于 sklearn 中的回归,我有一个列表 x 和一个列表 y。不幸的是,这些列表有空白/NaN。 NaN 会使任何分析崩溃,因此我需要删除每个 NaN 及其在另一个列表中的对应数字(以保持 x[0] 和 y[0] 之间的关系等)

找到它的优雅方法是什么?有循环的替代方法吗?

请您参考如下方法:

尝试以下操作,使用 Python 内置函数 zip和 filter :

def filter_nans(x, y): 
    filtered = filter(lambda o: not math.isnan(o[0]) and not math.isnan(o[1]), zip(x, y))     
    return [el[0] for el in filtered], [el[1] for el in filtered] 

例如:

x = [1, 2, 3, 4, 5, 6, None, 8] 
y = [10, 'not a number', 30, 40, 50, 60, 70, 80] 
 
x, y = filter_nans(x, y) 
 
>>> x 
[1, 3, 4, 5, 6, 8] 
>>> y 
[10, 30, 40, 50, 60, 80]