Skip to content
Advertisement

Remove NaN in a python list using max

In a recent interview I was given the following problem.

We have a list l = [NaN, 5, -12, NaN, 9, 0] and we want to replaceNaN with -9 using the max function knowing that max(NaN, -9) = -9. What I have tried is :

from numpy import   NaN

l = [NaN, 5, -12, NaN, 9, 0]
ll = [-9, 5, -12, -9, 9, 0]

print([max(i) for i in zip(l, ll)])
# output : [nan, 5, -12, nan, 9, 0]

but the output is still the same list. Can’t figure out how to code this.

Advertisement

Answer

You can use nan_to_num function to change the NaN value to any number

from numpy import NaN,nan_to_num

l = [NaN, 5, -12, NaN, 9, 0]
ll = [-9, 5, -12, -9, 9, 0]

print([max(nan_to_num(i,nan=-9)) for i in zip(l, ll)])
# is same as
# print([nan_to_num(i,nan=-9) for i in l])
# change nan=-9 to any number of your choice.

OUTPUT [-9.0, 5, -12, -9.0, 9, 0]

Here you got -9.0 instead of -9 (I think because NaN Type is float).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement