Here is a test case

>>> import numpy as np
>>> a = np.array( [ 0.0, 1, 2, 0.2, 0.0, 0.0, 2, 3] )

I want to turn all non-zero elements of this array to 1. I can do it using `np.where`

and numpy indexing.

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

note: `np.where`

returns the indices where the condition is true. e.g. if you want to change all 0 to -1.

>>> a[ np.where[ a == 0] ] = -1.0

That’s it. Checkout `np.clip`

as well.

### Like this:

Like Loading...

*Related*

## About Dilawar

Graduate Student at National Center for Biological Sciences, Bangalore.