vectorize 和有什么区别?和 frompyfunc在 numpy 中?
两者看起来非常相似。它们各自的典型用例是什么?
Edit:正如 JoshAdel 所指出的,vectorize
类似乎是建立在 frompyfunc
之上的。 (见 the source)。我仍然不清楚 frompyfunc
是否可能有任何 vectorize
...
最佳答案
正如 JoshAdel 指出的那样,vectorize
包装了 frompyfunc
。 Vectorize 增加了额外的功能:
- 从原始函数复制文档字符串
- 允许您从广播规则中排除参数。
- 返回正确 dtype 的数组,而不是 dtype=object
编辑:经过一些简短的基准测试,我发现对于大型数组,vectorize
比 frompyfunc
慢得多(~50%)。如果性能对您的应用程序至关重要,请首先对您的用例进行基准测试。
`
>>> a = numpy.indices((3,3)).sum(0)
>>> print a, a.dtype
[[0 1 2]
[1 2 3]
[2 3 4]] int32
>>> def f(x,y):
"""Returns 2 times x plus y"""
return 2*x+y
>>> f_vectorize = numpy.vectorize(f)
>>> f_frompyfunc = numpy.frompyfunc(f, 2, 1)
>>> f_vectorize.__doc__
'Returns 2 times x plus y'
>>> f_frompyfunc.__doc__
'f (vectorized)(x1, x2[, out])\n\ndynamic ufunc based on a python function'
>>> f_vectorize(a,2)
array([[ 2, 4, 6],
[ 4, 6, 8],
[ 6, 8, 10]])
>>> f_frompyfunc(a,2)
array([[2, 4, 6],
[4, 6, 8],
[6, 8, 10]], dtype=object)
`
关于python - numpy中frompyfunc和vectorize的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6768245/