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
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.
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.
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.]])
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 .
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
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With