NumPy矢量化一个功能,未知的形状

时间:2016-01-27 14:54:59

标签: python numpy vectorization

我有把numpy数组作为参数的函数,例如:

def f(arr):
  return arr.sum()

我想从A中的每个vec创建numpy数组,所以如果A.shape = (14,12,7),我的函数myfunc(A).shape = (14,12)
myfunc(A)[x, y] = f(A[x, y])

请注意,未指定len(A.shape)

1 个答案:

答案 0 :(得分:1)

您可以沿最后一轴应用sum

A.sum(axis=-1)

例如:

In [1]: np.ones((14,12,7)).sum(axis=-1).shape
Out[1]: (14, 12)

如果您有通用功能,可以使用apply_along_axis

np.apply_along_axis(sum, -1, A)
相关问题