Numpy matching one array with parts of another

lets say i have one array

a = numpy.arange(8*6*3).reshape((8, 6, 3)) #and another: l = numpy.array([[0,0],[0,1],[1,1]]) #an array of indexes to array "a" #and yet another: b = numpy.array([[0,0,5],[0,1,0],[1,1,3]]) 

where "l" and "b" are the same length and I want to say

  a[l] = b 

so that [0] [0] becomes [0,0,5], and [0] [1] becomes [0,1,0], etc.

it seems to work fine when ive gets one-dimensional arrays, but it gives me an error

  ValueError: array is not broadcastable to correct shape 

when i try it with a 3 dimensional array.

+4
source share
2 answers
 import numpy as np a = np.arange(8*6*3).reshape((8, 6, 3)) l = np.array([[0,0],[0,1],[1,1]]) #an array of indexes to array "a" b = np.array([[0,0,5],[0,1,0],[1,1,3]]) a[tuple(lT)] = b print(a[0,0]) # [0 0 5] print(a[0,1]) # [0 1 0] print(a[1,1]) # [1 1 3] 

Ann Archibald says

When you supply arrays in all index slots, what you get back has the same shape as the arrays that you insert; so if you are one-dimensional lists for example

A [[1,2,3], [1,4,5], [7,6,2]]

what are you getting

[A [1,1,7], A [2,4,6], A [3,5,2]]

When you compare this with your example, you see that

a[l] = b tells NumPy to install

 a[0,0,1] = [0,0,5] a[0,1,1] = [0,1,0] 

and the third element b not assigned. This is why you get an error message

 ValueError: array is not broadcastable to correct shape 

The solution is to convert the array l to the correct form:

 In [50]: tuple(lT) Out[50]: (array([0, 0, 1]), array([0, 1, 1])) 

(You can also use zip(*l) , but tuple(lT) bit faster.)

+3
source

Or using the same arrays you can use

 for i in range(len(l)): a[l[i][0]][l[i][1]]=b[i] 
0
source

All Articles