Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate Numpy arrays without copying

In Numpy, I can concatenate two arrays end-to-end with np.append or np.concatenate:

>>> X = np.array([[1,2,3]]) >>> Y = np.array([[-1,-2,-3],[4,5,6]]) >>> Z = np.append(X, Y, axis=0) >>> Z array([[ 1,  2,  3],        [-1, -2, -3],        [ 4,  5,  6]]) 

But these make copies of their input arrays:

>>> Z[0,:] = 0 >>> Z array([[ 0,  0,  0],        [-1, -2, -3],        [ 4,  5,  6]]) >>> X array([[1, 2, 3]]) 

Is there a way to concatenate two arrays into a view, i.e. without copying? Would that require an np.ndarray subclass?

like image 914
Fred Foo Avatar asked Oct 23 '11 20:10

Fred Foo


People also ask

Can you concatenate numpy arrays?

Joining Arrays Using Stack FunctionsWe can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis.

Does NP append make a copy?

NumPy: append() function The append() function is used to append values to the end of an given array. Values are appended to a copy of this array. These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis).

Is numpy concatenate faster than append?

In general it is better/faster to iterate or append with lists, and apply the np. array (or concatenate) just once. appending to a list is fast; much faster than making a new array.


1 Answers

The memory belonging to a Numpy array must be contiguous. If you allocated the arrays separately, they are randomly scattered in memory, and there is no way to represent them as a view Numpy array.

If you know beforehand how many arrays you need, you can instead start with one big array that you allocate beforehand, and have each of the small arrays be a view to the big array (e.g. obtained by slicing).

like image 198
pv. Avatar answered Sep 21 '22 02:09

pv.