Updating array values ​​using two masks: [mask1] [mask2] = value

Given the array and mask, we can assign new values ​​to the TRUE positions in the mask:

import numpy as np    
a = np.array([1,2,3,4,5,6])
mask1 = (a==2) | (a==5)
a[mask1] = 100
print a
# [  1 100   3   4 100   6]

However, if we apply the second mask to the first, we can access the values, but we cannot change them:

a = np.array([1,2,3,4,5,6])
mask1 = (a==2) | (a==5)
mask2 = (a[mask1]==2)
print a[mask1][mask2]
# [2]
a[mask1][mask2] = 100
print a
# [ 1 2 3 4 5 6 ]

Why is this happening?

(Even if it seems like a weird way to do it. Just out of curiosity)

+4
source share
2 answers

This is probably due to the fact that you mix getters and setters , preventing backpropagagation .

This is because you are using mark1as an indexer:

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

, a[mask1] = 100, , mask1 ,

>>> a
array([  1, 100,   3,   4, 100,   6])

, "", , a.

a[mask1][mask2] = 100 . , :

temp = a[mask1] #getter
temp[mask2] = 2#setter

temp, , , "backpropagated", a. temp ( , python -).

: , , : if temp - , , , . .

+3

advanced * , 100 .

a[mask1] . a[mask1][mask2] = 100 , mask2 100. a .

, , a[mask1], , ( , ).

* ( "" ) . , , ( , , ).

+3

Source: https://habr.com/ru/post/1608670/


All Articles