21

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]]

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).

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
atapaka
  • 1,172
  • 4
  • 14
  • 30
  • I would suggest to create an zero array with one element/row/column and than use `np.append()` and at the end remove the first element/row/column. I would suggest if it possible to predefine actual array size and not to change size every time. – lskrinjar Apr 24 '15 at 05:32
  • 3
    Make your list, and then create the array: `np.array(a)`. List `append` is faster than array `append`. – hpaulj Apr 24 '15 at 05:54

3 Answers3

44

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]])

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
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
Zero
  • 74,117
  • 18
  • 147
  • 154
4

I think you're looking for vstack:

>>> import numpy as np
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> np.vstack((a, b))
array([[1, 2, 3],
       [1, 2, 3]])
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
ComputerFellow
  • 11,710
  • 12
  • 50
  • 61
0

Using 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:

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.]])
John1024
  • 109,961
  • 14
  • 137
  • 171