我有一个返回 numpy 数组的生成器。 举个例子,就这样吧:
import numpy as np
a = np.arange(9).reshape(3,3)
gen = (x for x in a)
调用:
np.sum(gen)
在numpy 1.17.4上:
DeprecationWarning: Calling np.sum(generator) is deprecated, and in the future will give a different result. Use np.sum(np.fromiter(generator)) or the python sum builtin instead.
尝试重构上述内容:
np.sum(np.fromiter(gen, dtype=np.ndarray))
我得到:
ValueError: cannot create object arrays from iterator
上面的说法有什么问题吗?
最佳答案
问题出在 fromiter()
中的第二个参数 np.ndarray
。 Numpy fromiter预期为一维并返回一维数组:
Create a new 1-dimensional array from an iterable object.
因此,您无法从迭代器创建对象数组。此外,由于我在第一行中所述,.reshape()
也会引发错误。总而言之,这有效:
import numpy as np
a = np.arange(9)
gen = (x for x in a)
print(np.sum(np.fromiter(gen,float)))
输出:
36
关于python - 调用 np.sum(np.fromiter(generator)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60149857/