Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace values in an array

Tags:

python

numpy

as a replacement value for another within an operation with arrays, or how to search within an array and replace a value by another

for example:

array ([[NaN, 1., 1., 1., 1., 1., 1.]
       [1., NaN, 1., 1., 1., 1., 1.]
       [1., 1., NaN, 1., 1., 1., 1.]
       [1., 1., 1., NaN, 1., 1., 1.]
       [1., 1., 1., 1., NaN, 1., 1.]
       [1., 1., 1., 1., 1., NaN, 1.]
       [1., 1., 1., 1., 1., 1., NaN]])

where it can replace NaN by 0. thanks for any response

like image 324
ricardo Avatar asked Nov 25 '09 21:11

ricardo


1 Answers

You could do this:

import numpy as np
x=np.array([[np.NaN, 1., 1., 1., 1., 1., 1.],[1., np.NaN, 1., 1., 1., 1., 1.],[1., 1., np.NaN, 1., 1., 1., 1.], [1., 1., 1., np.NaN, 1., 1., 1.], [1., 1., 1., 1., np.NaN, 1., 1.],[1., 1., 1., 1., 1., np.NaN, 1.], [1., 1., 1., 1., 1., 1., np.NaN]])
x[np.isnan(x)]=0

np.isnan(x) returns a boolean array which is True wherever x is NaN. x[ boolean_array ] = 0 employs fancy indexing to assign the value 0 wherever the boolean array is True.

For a great introduction to fancy indexing and much more, see also the numpybook.

like image 115
unutbu Avatar answered Sep 25 '22 06:09

unutbu