I am trying to modify the values of an array based on a subset of a subset, but I can't find a way to do this. I think this exposes my lack of understanding about exactly how array indexing and subsetting works and what views are, but I can't find a solution anywhere so I am hoping that someone can help me.
Example problem:
import numpy as np
#generate some simple data
MyArray=np.arange(20).reshape(4,5)
>>>MyArray
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
#subset 1
i=np.where(MyArray > 5)
#subset of that subset
j=np.where(MyArray[i] < 15)
>>>MyArray[i][j]
array([ 6, 7, 8, 9, 10, 11, 12, 13, 14])
Great, that's what I expected to see! But if I now want to change those values to something else, I can't:
>>>MyArray[i][j]=999
>>>MyArray[i][j]
array([ 6, 7, 8, 9, 10, 11, 12, 13, 14])
#hmmmm :(
An ugly solution that works
I CAN get the values to change by looping over the elements of j individually, but this seems extraordinarily clumsy & hard to read:
#get number of elements in j
nj=np.size(j)
#loop over each element of j and modify the corresponding ith element
of MyArray
for j_it in range(0,nj):
MyArray[i[0][j[0][j_it]]][i[1][j[0][j_it]]]=999
>>>MyArray
array([[ 0, 1, 2, 3, 4],
[ 5, 999, 999, 999, 999],
[999, 999, 999, 999, 999],
[ 15, 16, 17, 18, 19]])
Similarly, I can modify MyArray using just one level of subsetting:
ii=np.where((MyArray > 5) & (MyArray < 15))
MyArray[ii]=999
>>>MyArray
array([[ 0, 1, 2, 3, 4],
[ 5, 999, 999, 999, 999],
[999, 999, 999, 999, 999],
[ 15, 16, 17, 18, 19]])
So, where am I going wrong with the first example?
NOTE:- I know that my last solution works fine for this problem, but my actual problem necessarily involves far more data and the second level of subsetting (and possibly a third...)
Thanks in advance, and apologies if this is something simple that I really should be able to work out fo myself from the documentation: I just haven't been able to :(