如何从生成器对象中构建numpy数组?
让我来说明一下这个问题:
>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)
在这个例子中,gimme()是我想要变成数组的输出的生成器.但是,数组构造函数不会迭代生成器,它只是存储生成器本身.我想要的行为来自numpy.array(list(gimme())),但我不想支付同时在内存中使用中间列表和最终数组的内存开销.有更节省空间的方式吗?
我想使用itertools的各种函数来创建numpy数组.我可以很容易地提前计算产品中元素的数量,组合,排列等,因此分配空间不应该是一个问题.
例如
coords = [[1,2,3],[4,5,6]]
iterable = itertools.product(*coords)
shape = (len(coords[0]), len(coords[1]))
arr = np.iterable_to_array(
iterable,
shape=shape,
dtype=np.float64,
count=shape[0]*shape[1]
) #not a real thing
answer = np.array([
[1,4],[1,5],[1,6],
[2,4],[2,5],[2,6],
[3,4],[3,5],[3,6]])
assert np.equal(arr, answer)
Run Code Online (Sandbox Code Playgroud)