Numpy sub-array assignment with advanced, mixed indexing

Viewed 7408

Original question

I am getting a very odd error message when I try to assign some of the elements of an array. I am using a combination of a slice and a set of indices. See the following simple example.

 import scipy as sp

 a = sp.zeros((3, 4, 5))
 b = sp.ones((4, 5))

 I = sp.array([0, 1, 3])

 b[:, I] = a[0, :, I]

This code raises the following ValueError:

ValueError: shape mismatch: value array of shape (3,4) could not be broadcast to indexing result of shape (3,4)

--

Follow up

Be careful when using a combination of a slice and seq. of integers. As pointed out on github:

x = rand(3, 5, 7)

print(x[0, :, [0,1]].shape)
# (2, 5)

print(x[0][:, [0,1]].shape)
# (5, 2)

This is how numpy is designed to work, but it is nevertheless a bit confusing that x[0][:, I] is not the same as x[0, :, I]. Since this is the behavior I want I choose to use x[0][:, I] in my code.

3 Answers
Related