The numpy where() function is only working once

Viewed 62
import numpy as np
myList = [[1, 2, 3, 4],[3, 4, 5, 6], [5, 6, 7, 8]]
arr = np.array(myList, dtype='float')
arr[1,1] = np.nan
arr[1,2] = np.inf
arr = np.where(arr==np.inf, -1, arr)
arr = np.where(arr==np.nan, -1, arr)
print(arr)

When I try to replace nan and inf, only the first where function works. If they're switched, nan will work instead of inf

2 Answers

You can not check with == np.nan, since NaN is not equal to NaN, indeed:

>>> np.nan == np.nan
False

You can use the isnan(..) function [numpy-doc] for that:

arr = np.where(np.isnan(arr), -1, arr)

You should use np.isnan function to check 'nan'ness of a number.

You can look at this question :

'NaN has the property that it doesn't equal itself, you should use np.isnan to test NaN values'

import numpy as np
myList = [[1, 2, 3, 4],[3, 4, 5, 6], [5, 6, 7, 8]]
arr = np.array(myList, dtype='float')
arr[1,1] = np.nan
arr[1,2] = np.inf
arr = np.where(arr==np.inf, -1, arr)
arr = np.where(np.isnan(arr), -1, arr)
print(arr)
Related