我喜欢从numpy
使用np.fromiter
,因为它是一种资源惰性的方式来构建np.array
对象。然而,它似乎不支持多维数组,这也是非常有用的。
import numpy as np
def fun(i):
""" A function returning 4 values of the same type.
"""
return tuple(4*i + j for j in range(4))
# Trying to create a 2-dimensional array from it:
a = np.fromiter((fun(i) for i in range(5)), '4i', 5) # fails
# This function only seems to work for 1D array, trying then:
a = np.fromiter((fun(i) for i in range(5)),
[('', 'i'), ('', 'i'), ('', 'i'), ('', 'i')], 5) # painful
# .. `a` now looks like a 2D array but it is not:
a.transpose() # doesn't work as expected
a[0, 1] # too many indices (of course)
a[:, 1] # don't even think about it
我怎样才能让a
成为一个多维数组,同时保持这样一个基于生成器的懒惰结构?
2条答案
按热度按时间bq9c1y661#
np.fromiter
本身只支持构造一维数组,因此,它期望一个可迭代的值,而不是元组/列表/序列等。解决这个限制的一种方法是使用itertools.chain.from_iterable
将生成器表达式的输出“解压”成单个1D值序列:z18hc3ub2#
关于这个问题的简短更新:使用
NumPy=1.23
,现在可以完全执行示例中给出的操作:就我个人而言,我发现直接传递数据类型而不是使用字符串更容易阅读(不是
'i'
导致int32
,而不是标准的int64
):另请参阅fromiter的文档,其中包含一个类似的示例。