Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slicing numpy array along an arbitrary dimension

Tags:

python

numpy

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

like image 538
Eurydice Avatar asked May 24 '13 14:05

Eurydice


People also ask

Can NumPy arrays be sliced?

Slicing 1-Dimensional NumPy ArraysUsing slicing operation we can extract elements of a 1-D NumPy array. For example, arr[1:6] syntax to slice elements from index 1 to index 6 from the following 1-D array.

How do you slice a one-dimensional array in Python?

One-Dimensional Slicing The first item of the array can be sliced by specifying a slice that starts at index 0 and ends at index 1 (one item before the 'to' index). Running the example returns a subarray with the first element. We can also use negative indexes in slices.

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

How do I slice a NumPy 2d array?

Slice Two-dimensional Numpy Arrays To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .


2 Answers

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
like image 185
DSM Avatar answered Sep 29 '22 13:09

DSM


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 !

like image 30
Eurydice Avatar answered Sep 29 '22 14:09

Eurydice