从 numpy 数组列表创建 numpy 数组的 Pythonic 方法

标签 python performance arrays numpy scipy

我在循环中生成一维 numpy 数组的列表,然后将此列表转换为 2d numpy 数组。如果我提前知道项目的数量,我会预先分配一个 2d numpy 数组,但我不知道,因此我将所有内容都放在一个列表中。

模型如下:

>>> list_of_arrays = map(lambda x: x*ones(2), range(5))
>>> list_of_arrays
[array([ 0.,  0.]), array([ 1.,  1.]), array([ 2.,  2.]), array([ 3.,  3.]), array([ 4.,  4.])]
>>> arr = array(list_of_arrays)
>>> arr
array([[ 0.,  0.],
       [ 1.,  1.],
       [ 2.,  2.],
       [ 3.,  3.],
       [ 4.,  4.]])

我的问题如下:

有没有更好的方法(性能方面)来完成收集顺序数值数据(在我的情况下为 numpy 数组)的任务,而不是将它们放在一个列表中,然后从中制作一个 numpy.array(我正在创建一个新的obj 和复制数据)?在经过良好测试的模块中是否有可用的“可扩展”矩阵数据结构?

我的二维矩阵的典型大小在 100x10 到 5000x10 float 之间

编辑:在这个例子中我使用的是 map ,但在我的实际应用中我有一个 for 循环

最佳答案

方便的方式,使用numpy.concatenate .我相信它也比@unutbu 的回答更快:

In [32]: import numpy as np 

In [33]: list_of_arrays = list(map(lambda x: x * np.ones(2), range(5)))

In [34]: list_of_arrays
Out[34]: 
[array([ 0.,  0.]),
 array([ 1.,  1.]),
 array([ 2.,  2.]),
 array([ 3.,  3.]),
 array([ 4.,  4.])]

In [37]: shape = list(list_of_arrays[0].shape)

In [38]: shape
Out[38]: [2]

In [39]: shape[:0] = [len(list_of_arrays)]

In [40]: shape
Out[40]: [5, 2]

In [41]: arr = np.concatenate(list_of_arrays).reshape(shape)

In [42]: arr
Out[42]: 
array([[ 0.,  0.],
       [ 1.,  1.],
       [ 2.,  2.],
       [ 3.,  3.],
       [ 4.,  4.]])

关于从 numpy 数组列表创建 numpy 数组的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2106287/

相关文章:

python - 在 Django 中,如何重写对象的 delete() 函数?

python - 在 django 模型中自动生成席位

arrays - Swift 数组按字母顺序和组顺序排序

java - 获取按钮在网格布局上的位置

java - Java中最快的数据结构(4D可视化处理)

java - 从字节数组末尾过滤数据(智能卡响应)

python - 用 Pandas 迭代合并数据框

python - 如何估计 OpenCV 中两个摄像头的位置?

java - 为什么 EhCache 中的每次 DiskStorage 刷新需要 4 秒?

performance - 用于检查值是否在区间内的快速矢量化函数