gpt4 book ai didi

python - 调用 np.sum(np.fromiter(generator))

转载 作者:行者123 更新时间:2023-12-02 11:56:26 30 4
gpt4 key购买 nike

我有一个返回 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com