nero_tulip
nero_tulip

Reputation: 55

Cannot change Numpy array elements filtered by boolean indexing

Reproducible code:

x = np.array([0.9, 0.9, 1])
y = np.array([0, 0, 1])
y[x<1] = 1 - x[x<1]
print(y)

Output

array([0, 0, 1])

Desired output

array([0.1, 0.1, 1])

I know np.where will get me the desired output. I'm just curious about why boolean indexing doesn't work in this case.

Upvotes: 2

Views: 90

Answers (1)

Ali_Sh
Ali_Sh

Reputation: 2816

You must specify the dtype for y:

y = np.array([0, 0, 1], dtype=np.float64)

When you did not specify that, it assume integer as dtype. So each modification on this will be converted to original dtype of this array.

Upvotes: 2

Related Questions