1

When I try to slice the boolean filtered numpy array it's not changing its value. please look a

array = np.array([1,2,3,4,5,6,7,8])
array[array>=2]

array([2, 3, 4, 5, 6, 7, 8])

array = np.array([1,2,3,4,5,6,7,8])
array[array>=2][1:5]

array([3, 4, 5, 6])

array = np.array([1,2,3,4,5,6,7,8])
array[array>=2][1:5] = [1,1,1,1]
array

array([1, 2, 3, 4, 5, 6, 7, 8])

When I changed [1:5] index into ones it's not changing it's vale...How can I change these value in boolean filter.?

  • Once you use a boolean index, you are working with a new array containing these elements, rather than the original array. You need to save the new array as variable, otherwise you will write new values, but have no way to access the afterwards. – Tyberius Jan 04 '21 at 01:03

1 Answers1

0
In [246]: arr = np.arange(1,9)
In [247]: mask = arr>=2
In [248]: mask
Out[248]: array([False,  True,  True,  True,  True,  True,  True,  True])

arr[mask] makes a new array, a copy (not a view). You can slide and modify it, but it won't affect arr.

Instead you have to modify the mask or an indexed derived from it.

One way:

In [249]: idx = np.nonzero(mask)[0]
In [250]: idx
Out[250]: array([1, 2, 3, 4, 5, 6, 7])
In [251]: arr[idx[1:5]]
Out[251]: array([3, 4, 5, 6])
In [252]: arr[idx[1:5]] = 1
In [253]: arr
Out[253]: array([1, 2, 1, 1, 1, 1, 7, 8])

[252] has just one indexing operation, so the assignment works.

I could go into how array[array>=2][1:5] = [1,1,1,1] evaluates as separate get and set operations if needed.

hpaulj
  • 221,503
  • 14
  • 230
  • 353