【发布时间】:2016-11-15 01:31:39
【问题描述】:
问题
-
我有一个
ndarray,由arr定义,它是一个n维立方体,每个维度的长度为m。 -
我想通过沿维度
n=0切片并将每个n-1-dim 切片作为函数的输入来执行函数func。
这似乎适用于map(),但我找不到合适的numpy 变体。 np.vectorise 似乎将 n-1-张量拆分为单独的标量条目。 apply_along_axis 或 apply_over_axes 似乎都不合适。
我的问题是我需要将任意函数作为输入传递,所以我看不到einsum 的解决方案也是可行的。
问题
- 您知道使用
np.asarray(map(func, arr))的最佳numpy替代方案吗?
示例
我通过以下方式将示例数组arr 定义为4-dim 立方体(或4-张量):
m, n = 3, 4
arr = np.arange(m**n).reshape((m,)*n)
我定义了一个示例函数f,
def f(x):
"""makes it obvious how the np.ndarray is being passed into the function"""
try: # perform an op using x[0,0,0] which is expected to exist
i = x[0,0,0]
except:
print '\nno element x[0,0,0] in x: \n{}'.format(x)
return np.nan
return x-x+i
此函数的预期结果res 将保持相同的形状,但满足以下条件:
print all([(res[i] == i*m**(n-1)).all() for i in range(m)])
这适用于默认的map() 函数,
res = np.asarray(map(f, a))
print all([(res[i] == i*m**(n-1)).all() for i in range(m)])
True
我希望np.vectorize 的工作方式与map() 相同,但它在标量条目中起作用:
res = np.vectorize(f)(a)
no element x[0,0,0] in x:
0
...
【问题讨论】:
-
相关但未解决问题:stackoverflow.com/q/3379301/4013571
标签: python function numpy multidimensional-array vectorization