Strange assignment in numpy arrays

I have a numpy array with n rows of size 3. Each row consists of three integers, each of which is an integer that refers to a different position inside the numpy array. For example, if I need strings that N[4] refers to, 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 create a function that modifies N, and I need to change N [N [x]] for some given x, which is also a parameter (4 in the example). I want to change all 6 in a subarray for another number (say 0), so I use numpy.where to find indexes that

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

Now, if I replace directly as N[N[4]][where_is_6] = 0 , there will be no changes. If I make the previous link, for example var = N[N[4]] and then var[where_is_6] , the change will be made, but locally for the function, and N will not be changed globally. What can I do in this case? or what am i doing wrong?

+6
source share
2 answers

It looks like you just need to convert the indices to the original N coordinates:

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

The problem is that N[N[4]] is a new array that you can check:

 print(N[N[4]].flags) C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False 

where OWNDATA shows this fact.

+4
source

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


All Articles