7

say that I have a (40,20,30) numpy array and that I have a function that after some work will return half of the input array along a selected input axis. Is there an automatic way to do so ? I would like to avoid such an ugly code:

def my_function(array,axis=0):

    ...

    if axis == 0:
        return array[:array.shape[0]/2,:,:] --> (20,20,30) array
    elif axis = 1:
        return array[:,:array.shape[1]/2,:] --> (40,10,30) array
    elif axis = 2: 
        return array[:,:,:array.shape[2]/2] --> (40,20,15) array

thanks for your help

Eric

3 Answers 3

8

I think you can use np.split for this [docs], and simply take the first or second element returned, depending on which one you want. For example:

>>> a = np.random.random((40,20,30))
>>> np.split(a, 2, axis=0)[0].shape
(20, 20, 30)
>>> np.split(a, 2, axis=1)[0].shape
(40, 10, 30)
>>> np.split(a, 2, axis=2)[0].shape
(40, 20, 15)
>>> (np.split(a, 2, axis=0)[0] == a[:a.shape[0]/2, :,:]).all()
True
Sign up to request clarification or add additional context in comments.

1 Comment

FYI: split() also takes a tuple specifying arbitrary split points.
4

thanks for your help, DSM. I will use your approach.

In the meantime, I found a (dirty ?) hack:

>>> a = np.random.random((40,20,30))
>>> s = [slice(None),]*a.ndim
>>> s[axis] = slice(f,l,s)
>>> a1 = a[s]

Perhaps a bit more general than np.split but much less elegant !

1 Comment

This is not less elegant. This just removes some of the syntactic sugar: : is slice(None), a:b:c is slice(a, b, c), etc.
2

numpy.rollaxis is a good tool for this:

def my_func(array, axis=0):
    array = np.rollaxis(array, axis)
    out = array[:array.shape[0] // 2]
    # Do stuff with array and out knowing that the axis of interest is now 0
    ...

    # If you need to restore the order of the axes
    if axis == -1:
        axis = out.shape[0] - 1
    out = np.rollaxis(out, 0, axis + 1)

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.