Home > Software design >  How to remove nan value from a nested list
How to remove nan value from a nested list

Time:11-16

I would like to update a webpage with these values. But I have nan values , i neeed to skip the values with nan. Here the list[1] has 3 nan values. I only need to update it by [[1, 8.4], [1, 2.2],[2, 4.0]]

list[0] = [[1, 8.4], [1, 2.2], [1, 1.3], [2, 4.7], [2, 4.0], [8, 9.6]]
list[1] = [[1, 8.4], [1, 2.2], [1, nan], [2, nan], [2, 4.0], [8, nan]]

output:

list[0] = [[1, 8.4], [1, 2.2], [1, 1.3], [2, 4.7], [2, 4.0], [8, 9.6]]
list[1] = [[1, 8.4], [1, 2.2],[2, 4.0]]

CodePudding user response:

You can iterate on your list and check if there are any None values in it, and remove it from it.

I'm using the built-in list.copy() method to clone the list so that changes are not being made on both lists.

def remove_nan_values(my_list: list):
    new_list = my_list.copy()
    for elem in my_list:
        if None in elem:
            new_list.remove(elem)
    return new_list

list_zero = [[1, 8.4], [1, 2.2], [1, 1.3], [2, 4.7], [2, 4.0], [8, 9.6]]
list_one = [[1, 8.4], [1, 2.2], [1, None], [2, None], [2, 4.0], [8, None]]

print(remove_nan_values(list_zero))
print(remove_nan_values(list_one))

Outputs:

[[1, 8.4], [1, 2.2], [1, 1.3], [2, 4.7], [2, 4.0], [8, 9.6]]
[[1, 8.4], [1, 2.2], [2, 4.0]]
  • Related