2

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!

0

1 Answer 1

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]]])
Sign up to request clarification or add additional context in comments.

1 Comment

AHA! Thanks. I appreciate you spotting that - it was making me nuts.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.