RVS*_*RVS 6 python numpy vectorization
我有一个numpy对象数组包含几个索引号列表:
>>> idxLsts = np.array([[1], [0, 2]], dtype=object)
Run Code Online (Sandbox Code Playgroud)
我定义了一个向量化函数,为每个列表附加一个值:
>>> idx = 99
>>> f = np.vectorize(lambda idxLst: idxLst.append(idx))
Run Code Online (Sandbox Code Playgroud)
我调用了这个函数.我不关心返回值,只是副作用.
>>> f(idxLsts)
array([None, None], dtype=object)
Run Code Online (Sandbox Code Playgroud)
索引99被添加到第一个列表两次.为什么?我很难过.
>>> idxLsts
array([[1, 99, 99], [0, 2, 99]], dtype=object)
Run Code Online (Sandbox Code Playgroud)
使用idxLsts的其他值,它不会发生:
>>> idxLsts = np.array([[1, 2], [0, 2, 4]], dtype=object)
>>> f(idxLsts)
array([None, None], dtype=object)
>>> idxLsts
array([[1, 2, 99], [0, 2, 4, 99]], dtype=object)
Run Code Online (Sandbox Code Playgroud)
我的怀疑是它与文档有关:"定义一个矢量化函数,它将一个嵌套的对象序列或numpy数组作为输入,并返回一个numpy数组作为输出.向量化函数在输入数组的连续元组上评估pyfunc,如python map函数,除了它使用numpy的广播规则."
从vectorize文档字符串:
Run Code Online (Sandbox Code Playgroud)The data type of the output of `vectorized` is determined by calling the function with the first element of the input. This can be avoided by specifying the `otypes` argument.
并从代码:
theout = self.thefunc(*newargs)
Run Code Online (Sandbox Code Playgroud)
这是一个额外的调用thefunc,用于确定输出类型.这就是第一个元素99附加两个s的原因.
在第二种情况下也会发生此行为:
import numpy as np
idxLsts = np.array([[1, 2], [0,2,4]], dtype = object)
idx = 99
f = np.vectorize(lambda x: x.append(idx))
f(idxLsts)
print(idxLsts)
Run Code Online (Sandbox Code Playgroud)
产量
[[1, 2, 99, 99] [0, 2, 4, 99]]
Run Code Online (Sandbox Code Playgroud)
您可以使用np.frompyfunc而不是np.vectorize:
import numpy as np
idxLsts = np.array([[1, 2], [0,2,4]], dtype = object)
idx = 99
f = np.frompyfunc(lambda x: x.append(idx), 1, 1)
f(idxLsts)
print(idxLsts)
Run Code Online (Sandbox Code Playgroud)
产量
[[1, 2, 99] [0, 2, 4, 99]]
Run Code Online (Sandbox Code Playgroud)