alan watt
alan watt

Reputation: 79

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.

Upvotes: 1

Views: 279

Answers (2)

BeRT2me
BeRT2me

Reputation: 13242

Use numpy's nanmax function:

from numpy import NaN, nanmax

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

print([nanmax(x) for x in zip(l, ll)])

Output:

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

Upvotes: 1

Sharim09
Sharim09

Reputation: 6224

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).

Upvotes: 1

Related Questions