+2 votes
in Programming Languages by (14.6k points)
How can I delete all NaN from a list?

E.g.

From

[100, 200, nan, 300, nan, 400]

to

[100, 200, 300, 400]

1 Answer

0 votes
by (25.6k points)

Assuming that nan is float('NaN'), not a string, you can use the following code to delete all NaN from the list.

import math
aa = [100,200,float('nan'),300,float('nan'),400]
bb = [x for x in aa if not math.isnan(x)]
print(bb)

Output
[100, 200, 300, 400]

...