从 Python 列表中删除 nan 值

Removing nan values from a Python List

有人能看出为什么这不起作用吗?我正在尝试从我的 python List/array 中删除 nan 值。

import math
import numpy as np

def clean_List_nan(List):
    Myarray=np.array(List)
    x = float('nan')
    for elem in Myarray:
        if math.isnan(x):
            x = 0.0
    return Myarray


oldlist =[nan, 19523.3211203121, 19738.4276377355, 19654.8478302742, 119.636737571360, 19712.4329437810, nan, 20052.3645613346, 19846.4815936009, 20041.8676619438, 19921.8126944154, nan, 20030.5073635719]

print(clean_List_nan(oldlist))

你的函数中的控制流没有意义 - 你将一个变量 x 设置为 nan,然后检查它是否确实在你的循环中 nan 并设置它到 0。您永远不会接触或检查数组的任何元素。

要将 nan 值正确转换为 0,您可以简单地使用 numpy.nan_to_num,因为看起来您正在使用 NumPy 数组。

演示

In[37]: arr
Out[37]: 
array([            nan,  19523.32112031,  19738.42763774,  19654.84783027,
          119.63673757,  19712.43294378,             nan,  20052.36456133,
        19846.4815936 ,  20041.86766194,  19921.81269442,             nan,
        20030.50736357])

In[38]: np.nan_to_num(arr)
Out[38]: 
array([     0.        ,  19523.32112031,  19738.42763774,  19654.84783027,
          119.63673757,  19712.43294378,      0.        ,  20052.36456133,
        19846.4815936 ,  20041.86766194,  19921.81269442,      0.        ,
        20030.50736357])

如果您对常规 Python 列表方法的功能版本更感兴趣,您可以尝试类似的方法,或者 fafl 提供的列表理解。

In[39]: list(map(lambda x: 0.0 if math.isnan(x) else x, oldlist))
Out[39]: 
[0.0,
 19523.3211203121,
 19738.4276377355,
 19654.8478302742,
 119.63673757136,
 19712.432943781,
 0.0,
 20052.3645613346,
 19846.4815936009,
 20041.8676619438,
 19921.8126944154,
 0.0,
 20030.5073635719]

Mitch 的回答可能是最好的方法。如果你想手动写这个,你可以做类似

的事情
cleanlist = [0.0 if math.isnan(x) else x for x in oldlist]