dabadaba
dabadaba

Reputation: 9532

Changed value in numpy array based on index and on criteria

I have a numpy array:

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

>> arr
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]]

I want to take a portion of the array based on indices (not slices):

ix = np.ix_([0, 1], [0, 2])
>> arr[ix]

[[1 3]
 [6 8]]

And I want to modify those elements in the original array, which would work if I did this:

arr[ix] = 0
>> arr
[[ 0  2  0  4  5]
 [ 0  7  0  9 10]]

But I only want to change them if they follow a specific condition, like if they are lesser than 5. I am trying this:

subarr = arr[ix]
subarr[subarr < 5] = 0

But it doesn't modify the original one.

>> arr
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]]

>> subarr
[[0 0]
 [6 8]]

I am not sure why this is not working, since both accessing the array by indices with np.ix_ and using a mask subarr < 5 should return a view of the array, not a copy.

Upvotes: 3

Views: 4042

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

When you do:

arr[ix] = 0

The python interpreter does arr.__setitem__(ix, 0) hence modifying the original object.

On the second case subarr is independent of arr, it is a copy of the subset of arr. You then modify this copy.

Upvotes: 0

jpp
jpp

Reputation: 164773

Fancy indexing returns a copy; hence your original array will not be updated. You can use numpy.where to update your values:

arr[ix] = np.where(arr[ix] < 5, 0, arr[ix])

array([[ 0,  2,  0,  4,  5],
       [ 6,  7,  8,  9, 10]])

Upvotes: 4

Related Questions