无论如何,在python numpy vectorize函数中使用索引吗?

时间:2018-08-15 07:59:50

标签: python numpy iterable

以下示例说明了我的问题:

>>> import numpy as np
>>> l = lambda i, value: i*v
>>> y = np.vectorize(l)
>>> y(range(10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2755, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2825, in _vectorize_call
    ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
  File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2785, in _get_ufunc_and_otypes
    outputs = func(*inputs)
TypeError: <lambda>() missing 1 required positional argument: 'value'
>>> y(enumerate(range(10)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2755, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2825, in _vectorize_call
    ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
  File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2785, in _get_ufunc_and_otypes
    outputs = func(*inputs)
TypeError: <lambda>() missing 1 required positional argument: 'value'

是否有类似fromiter的东西支持此功能,但是对于大输入(例如矢量化)速度更快?

2 个答案:

答案 0 :(得分:1)

np.vectorize只是一个循环,将函数应用于可迭代的每个值。给定一个可迭代的对象,它应该比通过map + enumerate向每个项目依次应用函数要有效。然后,您可以将map对象提供给np.fromiter

var = range(10)
indexed = enumerate(var)

def foo(x):
    idx, val = x
    return idx * val

res = np.fromiter(map(foo, indexed), dtype=int)

print(res)

[ 0  1  4  9 16 25 36 49 64 81]

答案 1 :(得分:0)

您可以帮助itertools.count

import numpy as np
from itertools import count

i = count(-1)
l = lambda value: next(i) * value
y = np.vectorize(l)

print(y(range(10)))
# [ 0  1  4  9 16 25 36 49 64 81]
相关问题