Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy append vs concatenate

Tags:

python

numpy

What is the difference between NumPy append and concatenate?

My observation is that concatenate is a bit faster and append flattens the array if axis is not specified.

In [52]: print a [[1 2]  [3 4]  [5 6]  [5 6]  [1 2]  [3 4]  [5 6]  [5 6]  [1 2]  [3 4]  [5 6]  [5 6]  [5 6]]  In [53]: print b [[1 2]  [3 4]  [5 6]  [5 6]  [1 2]  [3 4]  [5 6]  [5 6]  [5 6]]  In [54]: timeit -n 10000 -r 5 np.concatenate((a, b)) 10000 loops, best of 5: 2.05 µs per loop  In [55]: timeit -n 10000 -r 5 np.append(a, b, axis = 0) 10000 loops, best of 5: 2.41 µs per loop  In [58]: np.concatenate((a, b)) Out[58]:  array([[1, 2],        [3, 4],        [5, 6],        [5, 6],        [1, 2],        [3, 4],        [5, 6],        [5, 6],        [1, 2],        [3, 4],        [5, 6],        [5, 6],        [5, 6],        [1, 2],        [3, 4],        [5, 6],        [5, 6],        [1, 2],        [3, 4],        [5, 6],        [5, 6],        [5, 6]])  In [59]: np.append(a, b, axis = 0) Out[59]:  array([[1, 2],        [3, 4],        [5, 6],        [5, 6],        [1, 2],        [3, 4],        [5, 6],        [5, 6],        [1, 2],        [3, 4],        [5, 6],        [5, 6],        [5, 6],        [1, 2],        [3, 4],        [5, 6],        [5, 6],        [1, 2],        [3, 4],        [5, 6],        [5, 6],        [5, 6]])  In [60]: np.append(a, b) Out[60]:  array([1, 2, 3, 4, 5, 6, 5, 6, 1, 2, 3, 4, 5, 6, 5, 6, 1, 2, 3, 4, 5, 6, 5,        6, 5, 6, 1, 2, 3, 4, 5, 6, 5, 6, 1, 2, 3, 4, 5, 6, 5, 6, 5, 6]) 
like image 526
Jana Avatar asked Mar 11 '16 04:03

Jana


People also ask

Is list append faster than NumPy append?

NumPy Arrays Are NOT Always Faster Than Lists " append() " adds values to the end of both lists and NumPy arrays. It is a common and very often used function. The script below demonstrates a comparison between the lists' append() and NumPy's append() .

What is concatenate in NumPy?

concatenate. Advertisements. Concatenation refers to joining. This function is used to join two or more arrays of the same shape along a specified axis.

How do I merge multiple arrays in NumPy?

You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array. Concatenation refers to putting the contents of two or more arrays in a single array.

Is NP append fast?

np. append is extremely slow, why is that the case? The docs don't have anything on the performance part. With the below given code example, it took me more than 10 minutes to have some result.


1 Answers

np.append uses np.concatenate:

def append(arr, values, axis=None):     arr = asanyarray(arr)     if axis is None:         if arr.ndim != 1:             arr = arr.ravel()         values = ravel(values)         axis = arr.ndim-1     return concatenate((arr, values), axis=axis) 
like image 172
hpaulj Avatar answered Sep 20 '22 18:09

hpaulj