Home > Enterprise >  Cannot change Numpy array elements filtered by boolean indexing
Cannot change Numpy array elements filtered by boolean indexing

Time:06-11

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.

CodePudding user response:

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.

  • Related