Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy append vs Python append

Tags:

python

numpy

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

like image 506
leosenko Avatar asked Apr 24 '15 05:04

leosenko


People also ask

What is NumPy append in Python?

numpy.append() in Python. About : numpy.append(array, values, axis = None) : appends values along the mentioned axis at the end of the array. Parameters : array : [array_like]Input array. values : [array_like]values to be added in the arr.

How to append two arrays to an array in NumPy?

If axis is None, out is a flattened array. Here array a is created and then two arrays are appended to a with the help of np.append (). The resulting array of append function is a copy of the original array with other arrays added to it.

What is the difference between append() insert() and extend() method in Python lists?

In this article, we are going to discuss the difference between append (), insert (), and, extend () method in Python lists. It adds an element at the end of the list. The argument passed in the append function is added as a single element at end of the list and the length of the list is increased by 1.

Why are NumPy arrays faster than lists?

NumPy Arrays Are NOT Always Faster Than Lists If lists had been useless compared to NumPy arrays, they would have probably been dumped by the Python community. An example where lists rise and shine in comparison with NumPy arrays is the append () function. " append () " adds values to the end of both lists and NumPy arrays.


2 Answers

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
like image 88
Zero Avatar answered Sep 21 '22 02:09

Zero


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]])
like image 22
ComputerFellow Avatar answered Sep 23 '22 02:09

ComputerFellow