7

インデックス番号のいくつかのリストを含むnumpyオブジェクト配列があります。

>>> idxLsts = np.array([[1], [0, 2]], dtype=object)

各リストに値を追加するベクトル化された関数を定義します。

>>> idx = 99  
>>> f = np.vectorize(lambda idxLst: idxLst.append(idx))

関数を呼び出します。戻り値は気にせず、副作用だけです。

>>> f(idxLsts)  
array([None, None], dtype=object)

インデックス99が最初のリストに2回追加されました。なんで?私は困惑しています。

>>> idxLsts
array([[1, 99, 99], [0, 2, 99]], dtype=object)

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)

私の疑惑は、次のようなドキュメントに関連しています。「オブジェクトまたはnumpy配列のネストされたシーケンスを入力として受け取り、numpy配列を出力として返すベクトル化された関数を定義します。ベクトル化された関数は、次のような入力配列の連続するタプルに対してpyfuncを評価します。 numpyのブロードキャストルールを使用することを除いて、pythonmap関数。」

4

1 に答える 1

8

vectorizedocstringから:

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)

これはへの追加の呼び出しでありthefunc、出力タイプを決定するために使用されます。99これが、最初の要素に2つのが追加される理由です。

この動作は、2番目のケースでも発生します。

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)

収量

[[1, 2, 99, 99] [0, 2, 4, 99]]

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)

収量

[[1, 2, 99] [0, 2, 4, 99]]
于 2012-10-27T01:05:57.777 に答える