Reputation: 8234
I have an numpy array a
that I would like to replace some elements. I have the value of the new elements in a tuple/numpy array and the indexes of the elements of a
that needs to be replaced in another tuple/numpy array. Below is an example of using python to do what I want.How do I do this efficiently in NumPy?
Example script:
a = np.arange(10)
print( f'a = {a}' )
newvalues = (10, 20, 35)
indexes = (2, 4, 6)
for n,i in enumerate( indexes ):
a[i]=newvalues[n]
print( f'a = {a}' )
Output:
a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a = array([ 0, 1, 10, 3, 20, 5, 35, 7, 8, 9])
I tried a[indexes]=newvalues
but got IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed
Upvotes: 0
Views: 798
Reputation: 1855
The list of indices indicating which elements you want to replace should be a Python list
(or similar type), not a tuple
. Different items in the selection tuple indicate that they should be selected from different axis dimensions.
Therefore, a[(2, 4, 6)]
is the same as a[2, 4, 6]
, which is interpreted as the value at index 2 in the first dimension, index 4 in the second dimension, and index 6 in the third dimension.
The following code works correctly:
indexes = [2, 4, 6]
a[indexes] = newvalues
See also the page on Indexing from the numpy documentation, specifically the second 'Note' block in the introduction as well as the first 'Warning' under Advanced Indexing:
In Python,
x[(exp1, exp2, ..., expN)]
is equivalent tox[exp1, exp2, ..., expN]
; the latter is just syntactic sugar for the former.
The definition of advanced indexing means that
x[(1,2,3),]
is fundamentally different thanx[(1,2,3)]
. The latter is equivalent tox[1,2,3]
which will trigger basic selection while the former will trigger advanced indexing. Be sure to understand why this occurs.
Upvotes: 3