Alejandro Sazo Alejandro Sazo - 2 months ago 8
Python Question

Strange assignment in numpy arrays

I have a numpy array A with n rows of size 3. Each row is composed by three integers, each one is a integer which refers to another position inside the numpy array. For example If I want the rows refered by

N[4]
, I use
N[N[4]]
. Visually:

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


I am building a function that modifies N, and I need to modify N[N[x]] for some specified x which is a parameter too (4 in the example). I want to change all the 6 in the subarray for another number (let's say 0), so I use numpy.where to find the indexes, which are

where_is_6 = np.where(N[N[4]] == 6)


Now, if I replace directly like
N[N[4]][where_is_6] = 0
there is no change. If I make a previous reference like
var = N[N[4]]
and then
var[where_is_6]
the change is done but locally to the function and N is not changed globally. What can I do in this case? or what am I doing wrong?

Answer Source

Sounds like you just need to convert the indices to the original N's coordinates:

row_idxs = N[4]
r,c = np.where(N[row_idxs] == 6)
N[row_idxs[r],c] = 0