【问题标题】:Merging a list of numpy arrays into one array (fast)将 numpy 数组列表合并到一个数组中(快速)
【发布时间】:2011-08-27 05:13:48
【问题描述】:

如果知道列表的长度和数组的大小,那么将一个 numpy 数组列表合并为一个数组的最快方法是什么,这对所有人都是一样的?

我尝试了两种方法:

您可以看到vstack 更快,但出于某种原因,第一次运行的时间是第二次的三倍。我认为这是由(缺少)preallocation 引起的。那么如何为vstack 预分配一个数组呢?或者你知道更快的方法吗?

谢谢!

[更新]

我想要(25280, 320) 而不是(80, 320, 320),这意味着merged_array = array(list_of_arrays) 不适合我。感谢 Joris 指出这一点!!!

输出:

0.547468900681 s merged_array = array(first_list_of_arrays)
0.547191858292 s merged_array = array(second_list_of_arrays)
0.656183958054 s vstack first
0.236850976944 s vstack second

代码:

import numpy
import time
width = 320
height = 320
n_matrices=80

secondmatrices = list()
for i in range(n_matrices):
    temp = numpy.random.rand(height, width).astype(numpy.float32)
    secondmatrices.append(numpy.round(temp*9))

firstmatrices = list()
for i in range(n_matrices):
    temp = numpy.random.rand(height, width).astype(numpy.float32)
    firstmatrices.append(numpy.round(temp*9))


t1 = time.time()
first1=numpy.array(firstmatrices)
print time.time() - t1, "s merged_array = array(first_list_of_arrays)"

t1 = time.time()
second1=numpy.array(secondmatrices)
print time.time() - t1, "s merged_array = array(second_list_of_arrays)"

t1 = time.time()
first2 = firstmatrices.pop()
for i in range(len(firstmatrices)):
    first2 = numpy.vstack((firstmatrices.pop(),first2))
print time.time() - t1, "s vstack first"

t1 = time.time()
second2 = secondmatrices.pop()
for i in range(len(secondmatrices)):
    second2 = numpy.vstack((secondmatrices.pop(),second2))

print time.time() - t1, "s vstack second"

【问题讨论】:

  • 使用 timeit 在 Python 中进行简单的性能测试。它会产生更准确的结果。
  • 您希望合并后的数组具有哪些维度?因为first1(80, 320, 320)first2(25280, 320)
  • @joris,感谢您指出这一点。我想要第二个,这是我最初的方法。我会在问题中更改它。
  • 那么你需要 vstack 而不是 eumiro 的回答中的 dstack

标签: python arrays numpy


【解决方案1】:

您有 80 个 320x320 的阵列?所以你可能想使用dstack:

first3 = numpy.dstack(firstmatrices)

这会返回一个 80x320x320 数组,就像 numpy.array(firstmatrices) 所做的那样:

timeit numpy.dstack(firstmatrices)
10 loops, best of 3: 47.1 ms per loop


timeit numpy.array(firstmatrices)
1 loops, best of 3: 750 ms per loop

如果你想使用vstack,它会返回一个25600x320的数组:

timeit numpy.vstack(firstmatrices)
100 loops, best of 3: 18.2 ms per loop

【讨论】:

  • 嗨 eurmiro,抱歉我的问题不清楚。我实际上需要 (25280, 320) 而不是 (80, 320, 320)。查看我的问题的更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 2019-11-23
  • 1970-01-01
  • 2020-01-26
  • 2016-06-22
  • 2014-03-22
  • 1970-01-01
相关资源
最近更新 更多