I have a 2D numpy array. Some of the values in this array are NaN
. I want to perform certain operations using this array. For example consider the array:
You could use np.where to find where you have NaN
:
import numpy as np
a = np.array([[ 0, 43, 67, 0, 38],
[ 100, 86, 96, 100, 94],
[ 76, 79, 83, 89, 56],
[ 88, np.nan, 67, 89, 81],
[ 94, 79, 67, 89, 69],
[ 88, 79, 58, 72, 63],
[ 76, 79, 71, 67, 56],
[ 71, 71, np.nan, 56, 100]])
b = np.where(np.isnan(a), 0, a)
In [20]: b
Out[20]:
array([[ 0., 43., 67., 0., 38.],
[ 100., 86., 96., 100., 94.],
[ 76., 79., 83., 89., 56.],
[ 88., 0., 67., 89., 81.],
[ 94., 79., 67., 89., 69.],
[ 88., 79., 58., 72., 63.],
[ 76., 79., 71., 67., 56.],
[ 71., 71., 0., 56., 100.]])
You can use numpy.nan_to_num :
numpy.nan_to_num(x) : Replace nan with zero and inf with finite numbers.
Example (see doc) :
>>> np.set_printoptions(precision=8)
>>> x = np.array([np.inf, -np.inf, np.nan, -128, 128])
>>> np.nan_to_num(x)
array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000,
-1.28000000e+002, 1.28000000e+002])
You can use lambda function, an example for 1D array:
import numpy as np
a = [np.nan, 2, 3]
map(lambda v:0 if np.isnan(v) == True else v, a)
This will give you the result:
[0, 2, 3]