Can someone see why this is not working? I am trying to remove nan values from my python List/array.
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))
Best Answer
The control flow in your function makes no sense - you set a variable
x
to benan
, and then check if it is indeednan
in your loop and set it to 0. You never touch nor check any of the elements of the array.To properly convert your
nan
values to 0, you could simply usenumpy.nan_to_num
as it appears you're working with NumPy arrays.Demo
If you're more interested in having a functioning version of an approach for a regular Python list, you might try something like this, or a list comprehension as fafl has provided.