I would like to assign values of an array arr_2 to a different array arr_1. However, I want to do this based on 2 selection criteria. As a working example, I define my selection criteria as such
import numpy as np
# An array of -1 values of shape(10,): [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
arr_1 = np.zeros(10, dtype=int) - 1
# An array of 0-9 values of shape(10,): [0 1 2 3 4 5 6 7 8 9]
arr_2 = np.arange(10)
# Create an initial selection of values we want to change
# In this example: even indices: [ T F T F T F T F T F]
selection_a = np.arange(10) % 2 == 0
# Create a second selection based on selection_a: [F F F T T]
selection_b = arr_2[selection_a] > 5
Based on these two selection criteria I would like to assign the values of arr_2 where both conditions hold to the array arr_1. I.e. equivalent to [F F F F F F T F T F].
arr_1[selection_a][selection_b] = arr_2[selection_a][selection_b]
If I inspect both sides of the equation before the assignment, they yield the values that I expect:
print(arr_1[selection_a][selection_b]) # yields [-1 -1]
print(arr_2[selection_a][selection_b]) # yields [ 6, 8]
However, the assignment itself does not assign the values, i.e. arr_1 remains unchanged. My question is, why is this the case?
NB: I know that in most (and maybe even all cases) this can be circumvented by creating a single criterion, however I want to know why using 2 separate criteria won't work.
If anything is unclear, please let me know and I'll try to clarify.
Edit
I investigated this a bit further and the problem seems to be in the left hand side of the equation as something like
arr_1[selection_a][selection_b] = 5
does not work either.
idx = arr_2[selection_a][selection_b]; arr_1[idx] = idxselection_basarr_2 > 5 & selection_athen usearr_1[selection_b] = 5selection_aandselection_bhave different shapes.selection_bdepend on the result inselection_arequiring a nested selection, just define it with the same shape asselection_aand use&to "filter". You can always rewrite a nested condition[a][b][c][d]into[a& b' & c' & d']where the primed versionsb',c',d'(ecc.) have the same shape asa.arr_1[selection_a]is acopy, not aview. The assignment is modifying a portion of that copy, not a portion of the original.numpyis not parsing the 2 criteria together. Python is performing two separate indexing operations.