slicing multi-dimensional numpy arrays with arrays [duplicate]

天涯浪子 提交于 2019-12-24 01:18:26

问题


I have a numpy array (we'll call it test) of ~286 x 181 x 360, and need to extract a 3-D array from it. The ranges needed for the three dimensions are defined as other numpy arrays (a_dim, b_dim, and c_dim) (based ultimately on user input). Naively, I had hoped I'd be able to do something like big_array[a_dim,b_dim,c_dim]. That ran happily when the b_dim and c_dim contained only a single value (which happened to occur in my main test case), but doesn't work when they're bigger than 1.

Traceback (most recent call last):
  File "<pyshell#541>", line 1, in <module>
    test[a_dim,b_dim,c_dim]
ValueError: shape mismatch: objects cannot be broadcast to a single shape

To simplify, given the following 4 arrays:

test=arange(125).reshape((5,5,5))
a_dim=[0,1]
b_dim=[1,2]
c_dim=[2,3]

What I'd like to get as output from that combination above is:

array([[[ 7,  8],
        [12, 13]],

       [[32, 33],
        [37, 38]]])

Or, a 3D array containing the all of the rows, columns, and bands (or whatever you'd like to call a third dimension) that are defined in a_dim, b_dim, and c_dim. I've tried using ix_ for this, but am clearly missing something from the examples I've seen:

>>> test[ix_((a_dim,b_dim,c_dim))]

Traceback (most recent call last):
  File "<pyshell#517>", line 1, in <module>
    test[ix_((a_dim,b_dim,c_dim))]
  File "C:\Python27\lib\site-packages\numpy\lib\index_tricks.py", line 73, in ix_
    raise ValueError, "Cross index must be 1 dimensional"
ValueError: Cross index must be 1 dimensional

Any suggestions? Thanks!


回答1:


So close -- just remove one pair of parens in the call to numpy.ix_():

>>> test[ix_(a_dim,b_dim,c_dim)]
array([[[ 7,  8],
        [12, 13]],

       [[32, 33],
        [37, 38]]])


来源:https://stackoverflow.com/questions/9027024/slicing-multi-dimensional-numpy-arrays-with-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!