最佳的方式追加到numpy的数组 [英] Optimal way to append to numpy array

查看:259
本文介绍了最佳的方式追加到numpy的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy的数组,我可以通过追加,像这样的项目只是附加到它:

  numpy.append(myarray中,1)

在这种情况下,我只追加整数 1

但是,这是附加到一个数组的最快方法?我有一个运行到数万一个很长的阵列。

或者是更好的索引数组,并直接分配呢?
像这样的:

  myArray的[123] = 1


解决方案

追加到numpy的阵列是非常低效的。这是因为,除preTER需要找到并在每一个步骤中的整个阵列分配存储器。根据应用的不同,也有更好的策略

如果你提前知道的长度,最好是pre-分配使用函数一样的 np.ones ,的 np.zeros ,或 np.empty

  desired_length = 500
结果= np.empty(desired_length)
在范围(desired_length)我:
    结果[I] = I 2 **

如果你不知道的长度,它可能更有效地保持在一个常规列表中的结果,并将其转换为一个数组之后。

 的结果= []
而条件:
    A = do_stuff()
    results.append(一)
结果= np.array(结果)


下面是一些计时我的电脑上。

  DEF pre_allocate():
    结果= np.empty(5000)
    有效范围内的(5000)I:
        结果[I] = I 2 **
    返回结果高清list_append():
    结果= []
    有效范围内的(5000)I:
        results.append(ⅰ** 2)
    返回np.array(结果)高清numpy_append():
    结果= np.array([])
    有效范围内的(5000)I:
        np.append(的结果,我** 2)
    返回结果%timeit pre_allocate()
#100圈,最好的3:每循环2.42毫秒%timeit list_append()
#100圈,最好的3:每循环为2.5 ms%timeit numpy_append()
#10圈,最好的3:48.4%环毫秒

所以,你可以看到,无论pre-分配和使用列表,然后转换速度会更快。

I have a numpy array and I can simply append an item to it using append, like this:

numpy.append(myarray, 1)

In this case I just appended the integer 1.

But is this the quickest way to append to an array? I have a very long array that runs into the tens of thousands.

Or is it better to index the array and assign it directly? Like this:

myarray[123] = 1

解决方案

Appending to numpy arrays is very inefficient. This is because the interpreter needs to find and assign memory for the entire array at every single step. Depending on the application, there are much better strategies.

If you know the length in advance, it is best to pre-allocate the array using a function like np.ones, np.zeros, or np.empty.

desired_length = 500
results = np.empty(desired_length)
for i in range(desired_length):
    results[i] = i**2

If you don't know the length, it's probably more efficient to keep your results in a regular list and convert it to an array afterwards.

results = []
while condition:
    a = do_stuff()
    results.append(a)
results = np.array(results)


Here are some timings on my computer.

def pre_allocate():
    results = np.empty(5000)
    for i in range(5000):
        results[i] = i**2
    return results

def list_append():
    results = []
    for i in range(5000):
        results.append(i**2)
    return np.array(results)

def numpy_append():
    results = np.array([])
    for i in range(5000):
        np.append(results, i**2)
    return results

%timeit pre_allocate()
# 100 loops, best of 3: 2.42 ms per loop

%timeit list_append()
# 100 loops, best of 3: 2.5 ms per loop

%timeit numpy_append()
# 10 loops, best of 3: 48.4 ms per loop

So you can see that both pre-allocating and using a list then converting are much faster.

这篇关于最佳的方式追加到numpy的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆