Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy array cannot index within a single []

>>> allData.shape
Out[72]: (8L, 161L)
>>> mask = allData[2,:]
>>> allData[[0,1,3],:][:,mask == 1]  # works fine
>>> allData[[0,1,3],mask == 1]  # error: ValueError: shape mismatch: objects cannot be broadcast to a single shape

Why is it that numpy arrays cannot be indexed within a single bracket []?

like image 712
Sean Avatar asked Oct 02 '13 19:10

Sean


1 Answers

Changing allData[[0,1,3],mask == 1] to allData[[0,1,3],argwhere(mask == 1)] should fix it.

Brief explanation, if you slice an array by [[list1], [list2]], both lists are supposed to be lists of indices. If one of them is substituted by : to take all the element among that axis, then the other list can be a Boolean array of the same size. Only ONE of them need to be substituted by :. Consider the following 3D array example:

b=random.random((5, 10,2))
b[[0,1,3],:, some_mask==1] #works
b[:,:, some_mask==1] #works
b[[0,1,3],[2,4], some_mask==1] #ValueError
like image 142
CT Zhu Avatar answered Sep 20 '22 21:09

CT Zhu