说我有一个(40,20,30)numpy数组,并且我有一个函数,经过一些工作后将沿选定的输入轴返回一半的输入数组。有自动方法吗?我想避免这么难看的代码:
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
感谢您的帮助
埃里克
答案 0 :(得分:7)
我认为您可以对[docs]使用np.split
,只需返回第一个或第二个元素,具体取决于您想要的那个。例如:
>>> 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
答案 1 :(得分:4)
感谢您的帮助,帝斯曼。我会用你的方法。
与此同时,我发现了一个(肮脏的?)hack:
>>> a = np.random.random((40,20,30))
>>> s = [slice(None),]*a.ndim
>>> s[axis] = slice(f,l,s)
>>> a1 = a[s]
也许比np.split更通用但更不优雅!
答案 2 :(得分:2)
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)