Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
Alejandro Sazo Avatar asked Sep 10 '14 21:09

Alejandro Sazo


People also ask

What is __ Array_interface __?

__array_interface__ A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if they are not provided. The keys are: shape (required) Tuple whose elements are the array size in each dimension.

How do I assign a NumPy array?

Element Assignment in NumPy Arrays We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).

Can I append NumPy array to list?

You can use numpy. append() function to add an element in a NumPy array. You can pass the NumPy array and multiple values as arguments to the append() function. It doesn't modify the existing array but returns a copy of the passed array with given values added.

Can you store strings in a NumPy array?

The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects.


1 Answers

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
like image 124
perimosocordiae Avatar answered Nov 15 '22 00:11

perimosocordiae