NumPy 追加与 Python 追加

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29839350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:05:23  来源:igfitidea点击:

NumPy append vs Python append

pythonnumpy

提问by leosenko

In Python I can append to an empty array like:

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

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

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

我如何在 NumPy 中做同样的事情?np.append不幸的是,使数组变平(而且我需要在开头有一个空数组)。

采纳答案by Zero

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

OP 打算从空数组开始。所以,这是使用 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]])

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.

但是,如果您要附加大量循环。首先附加列表并转换为数组比附加 NumPy 数组更快。

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

回答by ComputerFellow

I think you're looking for vstack:

我认为您正在寻找vstack

>>> import numpy as np
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> np.vstack((a, b))
array([[1, 2, 3],
       [1, 2, 3]])

回答by John1024

Using np.append

使用 np.append

Let's start with an empty 2-D array:

让我们从一个空的二维数组开始:

In [8]: a = np.array([]); a = a.reshape((0, 3)); a
Out[8]: array([], shape=(0, 3), dtype=float64)

Now, let's append some rows:

现在,让我们附加一些行:

In [19]: a = np.append(a, [[1, 2, 3]], axis=0 ); a
Out[19]: array([[ 1.,  2.,  3.]])

In [20]: a = np.append(a, [[1, 2, 3]], axis=0 ); a
Out[20]: 
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])

Using np.concatenate:

使用np.concatenate

Again, let's start with an empty 2-D array:

同样,让我们​​从一个空的二维数组开始:

In [28]: a = np.array([]); a = a.reshape((0, 3)); a
Out[28]: array([], shape=(0, 3), dtype=float64)

Now, let's concatenate some rows:

现在,让我们连接一些行:

In [29]: a = np.concatenate( (a, [[1, 2, 3]]), axis=0 ); a
Out[29]: array([[ 1.,  2.,  3.]])

In [30]: a = np.concatenate( (a, [[1, 2, 3]]), axis=0 ); a
Out[30]: 
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])