ocram
ocram

Reputation: 93

Iterate over a 2d numpy array until it contains only some specific values

I have a 2d numpy array which contains float numbers in each cell.

I'd like to iterate over it and change value of each cell (if a specific condition is matched), until it contains only the values 1, -1, or NaN in each cell.

How can I achieve this?

Upvotes: 0

Views: 35

Answers (1)

jrsm
jrsm

Reputation: 1695

In numpy you can use a conditional indexing. i.e.:

import numpy as np
x = np.arange(10)
c =  x > 5 
print c

will give

array([False, False, False, False, False, False,  True,  True,  True,  
True], dtype=bool)

and finally use the condition

x[c] = -1
print x

gives array([ 0, 1, 2, 3, 4, 5, -1, -1, -1, -1])

Upvotes: 1

Related Questions