+3 votes
in Programming Languages by (40.5k points)
I want to replace all 0's with some non-zero value in a Numpy array. How can I do this in pythonic way?

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

You can use Numpy's where() function to find the indices of 0's and then change those 0's to a non-value using indices.

Example using a 1D array:

I am changing 0 to 2 in both examples.

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

 Example using a 2D array:

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

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


...