我想对 numpy.ndarray 的每个元素应用一个函数,如下所示:
import numpy
import math
a = numpy.arange(10).reshape(2,5)
b = map(math.sin, a)
print b
但这给出了:
TypeError: only length-1 arrays can be converted to Python scalars
我知道我可以做到:
import numpy
import math
a = numpy.arange(10).reshape(2,5)
def recursive_map(function, value):
if isinstance(value, (list, numpy.ndarray)):
out = numpy.array(map(lambda x: recursive_map(function, x), value))
else:
out = function(value)
return out
c = recursive_map(math.sin, a)
print c
我的问题是:是否有内置函数或方法来执行此操作?这似乎是基本的,但我一直无法找到它。我正在使用 Python 2.7。
请您参考如下方法:
使用 np.sin 它已经在 ndarray 上以元素方式运行。
您还可以重新整形为一维数组,原生 map 应该可以正常工作。然后您可以再次使用 reshape 来恢复原始尺寸。
您还可以使用 np.vectorize编写可以像 np.sin 一样工作的函数。
