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 :
JavaScript
x
8
1
from numpy import NaN
2
3
l = [NaN, 5, -12, NaN, 9, 0]
4
ll = [-9, 5, -12, -9, 9, 0]
5
6
print([max(i) for i in zip(l, ll)])
7
# output : [nan, 5, -12, nan, 9, 0]
8
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
JavaScript
1
11
11
1
from numpy import NaN,nan_to_num
2
3
l = [NaN, 5, -12, NaN, 9, 0]
4
ll = [-9, 5, -12, -9, 9, 0]
5
6
print([max(nan_to_num(i,nan=-9)) for i in zip(l, ll)])
7
# is same as
8
# print([nan_to_num(i,nan=-9) for i in l])
9
# change nan=-9 to any number of your choice.
10
11
OUTPUT [-9.0, 5, -12, -9.0, 9, 0]
Here you got -9.0
instead of -9
(I think because NaN Type is float).