numpy fromiter与列表生成器
问题内容:
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
yield c.tolist()
j += 1
# What I did:
# res = np.array(list(gen_c())) <-- useless allocation of memory
# this line is what I'd like to do and it's killing me
res = np.fromiter(gen_c(), dtype=int) # dtype=list ?
错误说 ValueError: setting an array element with a sequence.
这是一段非常愚蠢的代码。我想从生成器创建列表数组(最终是2D数组)…
尽管我到处搜索,但仍然无法弄清楚它如何工作。
问题答案:
您只能按照-文档numpy.fromiter()
中的说明numpy.fromiter
创建一维数组(而非二维数组)。
numpy.fromiter(iterable,dtype,count = -1)
从可迭代对象创建一个新的一维数组。
您可以做的一件事是将生成器函数转换为从中给出单个值c
,然后从中创建一维数组,然后将其重塑为(-1,5)
。范例-
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
for i in c:
yield i
j += 1
np.fromiter(gen_c(),dtype=int).reshape((-1,5))
演示-
In [5]: %paste
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
for i in c:
yield i
j += 1
np.fromiter(gen_c(),dtype=int).reshape((-1,5))
## -- End pasted text --
Out[5]:
array([[0, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[2, 1, 1, 1, 1],
[3, 1, 1, 1, 1],
[4, 1, 1, 1, 1],
[5, 1, 1, 1, 1],
[6, 1, 1, 1, 1],
[7, 1, 1, 1, 1],
[8, 1, 1, 1, 1],
[9, 1, 1, 1, 1]])