user3601754
user3601754

Reputation: 3862

Python - Force nan values to get a certain value

I used a mask to work on arrays and now i would like to force "nan" to get a certain value (0 per example...)

A simple example with moderate array, i have :

[[[nan, nan], [nan, nan], [nan, nan], [nan, nan]], [[2, 0], [2, 2], [nan, nan], [nan, nan]], [[2, 2], [2, 0], [2, 1], [2, 2]]]

And i would like to get an array as :

[[0, 0], [0, 0], [0, 0], [0, 0]], [[2, 0], [2, 2], [0, 0], [0, 0]], [[2, 2], [2, 0], [2, 1], [2, 2]]]

Upvotes: 0

Views: 292

Answers (2)

wwii
wwii

Reputation: 23753

Use boolean indexing with numpy.isnan on the left-hand-side of an assignment.

>>> a
array([[[ nan,  nan],
        [ nan,  nan]],

       [[  2.,   0.],
        [ nan,  nan]],

       [[  2.,   2.],
        [  2.,   0.]]])
>>> a[np.isnan(a)] = 0
>>> a
array([[[ 0.,  0.],
        [ 0.,  0.]],

       [[ 2.,  0.],
        [ 0.,  0.]],

       [[ 2.,  2.],
        [ 2.,  0.]]])
>>>

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 122061

This can easily be achieved with numpy.nan_to_num:

>>> import numpy as np
>>> a = np.array([[np.nan, 0], [1, 2]])
>>> a
array([[ nan,   0.],
       [  1.,   2.]])
>>> a = np.nan_to_num(a)
>>> a
array([[ 0.,  0.],
       [ 1.,  2.]])

Note that this creates a new array, it won't alter the original in-place.

Upvotes: 3

Related Questions