简体   繁体   English

沿任意维度切割numpy数组

[英]slicing numpy array along an arbitrary dimension

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. 说我有一个(40,20,30)numpy数组,并且我有一个函数,在一些工作后将沿选定的输入轴返回一半的输入数组。 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 埃里克

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. 我想你可以在这个[docs]中使用np.split ,只需要返回第一个或第二个元素,具体取决于你想要的那个。 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: 在此期间,我发现了一个(脏?)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 ! 也许比np.split更通用但更不优雅!

numpy.rollaxis is a good tool for this: numpy.rollaxis是一个很好的工具:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM