NumPy:从可迭代对象创建多维数组 [英] NumPy: Create a multidimensional array from an iterable
问题描述
我有一个可重复的元组,我想从中构建一个 ndarray
.假设形状为(12345,67890)
.一种有效而优雅的方法是什么?
I have an iterable of tuples, and I'd like to build an ndarray
from it. Say that the shape would be (12345, 67890)
. What would be an efficient and elegant way to do so?
以下是一些选择,以及为什么我将它们排除在外:
Here are a few options, and why I ruled them out:
-
np.array(my_tuples)
在知道大小之前就开始分配数组,根据NumPy的文档,这需要低效率的重定位.
np.array(my_tuples)
starts allocating the array before it knows the size, which requires inefficient relocations according to NumPy's documentation.
使用 np.ndarray((12345,67890))
创建一个包含未初始化内容的数组,然后执行一个循环,以数据填充该数组.它有效且有效,但是有点笨拙,因为它需要多个语句.
Create an array with uninitialized content using np.ndarray((12345, 67890))
and then do a loop that populates it with data. It works and it's efficient, but a bit inelegant because it requires multiple statements.
使用 np.fromiter
似乎仅适用于一维数组.
Use np.fromiter
which appears to be geared towards 1-dimensional arrays only.
有人有更好的解决方案吗?
Does anyone have a better solution?
(I've seen this question, but I'm not seeing any promising answers there.)
推荐答案
将 fromiter()
与 .reshape()
一起使用.重塑不需要更多的内存或处理.
Use fromiter()
with .reshape()
.
Reshaping does not require more memory or processing.
这篇关于NumPy:从可迭代对象创建多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!