0

I'm trying to slice and iterate over a multidimensional array at the same time. I have a solution that's functional, but it's kind of ugly, and I bet there's a slick way to do the iteration and slicing that I don't know about. Here's the code:

import numpy as np
x = np.arange(64).reshape(4,4,4)
y = [x[i:i+2,j:j+2,k:k+2] for i in range(0,4,2) 
                          for j in range(0,4,2) 
                          for k in range(0,4,2)]
y = np.array(y)
z = np.array([np.min(u) for u in y]).reshape(y.shape[1:])
1
  • 2
    Could you please fix the errors in your code so that it actually works? Thanks. Commented Mar 6, 2013 at 18:02

2 Answers 2

4

Your last reshape doesn't work, because y has no shape defined. Without it you get:

>>> x = np.arange(64).reshape(4,4,4)
>>> y = [x[i:i+2,j:j+2,k:k+2] for i in range(0,4,2) 
...                           for j in range(0,4,2) 
...                           for k in range(0,4,2)]
>>> z = np.array([np.min(u) for u in y])
>>> z
array([ 0,  2,  8, 10, 32, 34, 40, 42])

But despite that, what you probably want is reshaping your array to 6 dimensions, which gets you the same result as above:

>>> xx = x.reshape(2, 2, 2, 2, 2, 2)
>>> zz = xx.min(axis=-1).min(axis=-2).min(axis=-3)
>>> zz
array([[[ 0,  2],
        [ 8, 10]],

       [[32, 34],
        [40, 42]]])
>>> zz.ravel()
array([ 0,  2,  8, 10, 32, 34, 40, 42])
Sign up to request clarification or add additional context in comments.

Comments

0

It's hard to tell exactly what you want in the last mean, but you can use stride_tricks to get a "slicker" way. It's rather tricky.

import numpy.lib.stride_tricks

# This returns a view with custom strides, x2[i,j,k] matches y[4*i+2*j+k]
x2 = numpy.lib.stride_tricks(
        x, shape=(2,2,2,2,2,2),
        strides=(numpy.array([32,8,2,16,4,1])*x.dtype.itemsize))

z2 = z2.min(axis=-1).min(axis=-2).min(axis=-3)

Still, I can't say this is much more readable. (Or efficient, as each min call will make temporaries.)

Note, my answer differs from Jaime's because I tried to match your elements of y. You can tell if you replace the min with max.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.