NumPy附加vs Python附加 [英] NumPy append vs Python append

查看:41
本文介绍了NumPy附加vs Python附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我可以追加到一个空数组,例如:

In Python I can append to an empty array like:

>>> a = []
>>> a.append([1,2,3])
>>> a.append([1,2,3])
>>> a
[[1, 2, 3], [1, 2, 3]]

我如何在NumPy中做同样的事情? np.append不幸的是,该数组展平了(我需要在开始时有一个空数组).

How can I do the same in NumPy? np.append flattens the array, unfortunately (and I need to have an empty array at the beginning).

推荐答案

OP旨在以空数组开头.因此,这是使用NumPy的一种方法

OP intended to start with empty array. So, here's one approach using NumPy

In [2]: a = np.empty((0,3), int)

In [3]: a
Out[3]: array([], shape=(0L, 3L), dtype=int32)

In [4]: a = np.append(a, [[1,2,3]], axis=0)

In [5]: a
Out[5]: array([[1, 2, 3]])

In [6]: a = np.append(a, [[1,2,3]], axis=0)

In [7]: a
Out[7]:
array([[1, 2, 3],
       [1, 2, 3]])

(如果要添加大量循环).首先附加列表并转换为数组比附加NumPy数组更快.

BUT, if you're appending in a large number of loops. It's faster to append list first and convert to array than appending NumPy arrays.

In [8]: %%timeit
   ...: list_a = []
   ...: for _ in xrange(10000):
   ...:     list_a.append([1, 2, 3])
   ...: list_a = np.asarray(list_a)
   ...:
100 loops, best of 3: 5.95 ms per loop

In [9]: %%timeit
   ....: arr_a = np.empty((0, 3), int)
   ....: for _ in xrange(10000):
   ....:     arr_a = np.append(arr_a, np.array([[1,2,3]]), 0)
   ....:
10 loops, best of 3: 110 ms per loop

这篇关于NumPy附加vs Python附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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