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

标签 python numpy

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

相关文章:

python - cProfile 配置文件在线程内调用吗?

python - 使用Python分析文件中数据的类结构

python - 编写更快的 Python 物理模拟器

python - NumPy 数组数组到 PyOpenCL vecs 数组

python - 向量化或优化循环,其中每次迭代都取决于前一次迭代的状态

c# - 安全和短的服务器-客户端连接

python - Pandas:没有排序索引和列的数据透视表

python - 使用 Google Sheets API 公开电子表格?

python - 如何安装 Python Pandas ?

python - 关于在 Numpy 中向量化 block 操作的建议