15

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

3 Answers 3

31

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@ricardo: Let x be your numpy array.
15

these days there is the special function:

a = numpy.nan_to_num(a)

4 Comments

Just saved my bacon while doing in Inverse Filter. [image-processing]
But this will involve a temporary variable with same type and shape as a, it will matter on large matrices.
@dashesy As of version 1.13 you can do in place: a = numpy.nan_to_num(a, copy=False) ... More information on the parameter 'copy': Whether to create a copy of x (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True. New in version 1.13.
Any way to choose a fill value other than 0?
1

Here is the example array in the question:

import numpy as np
a = np.where(np.eye(7), np.nan, 1)

You can either use numpy.where and numpy.isnan functions to create a new array b:

b = np.where(np.isnan(a), 0, a)

Or use an in-place function to directly modify the a array:

np.place(a, np.isnan(a), 0)  # returns None

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.