# Append value to each array in a numpy array

## Question:

I have a numpy array of arrays, for example:

``````x = np.array([[1,2,3],[10,20,30]])
``````

Now lets say I want to extend each array with [4,40], to generate the following resulting array:

``````[[1,2,3,4],[10,20,30,40]]
``````

How can I do this without making a copy of the whole array? I tried to change the shape of the array in place but it throws a ValueError:

``````x = np.append(x,4)
x = np.append(x,40)
ValueError : could not broadcast input array from shape (4) into shape (3)
``````

You can’t do this. Numpy arrays allocate contiguous blocks of memory, if at all possible. Any change to the array size will force an inefficient copy of the whole array. You should use Python lists to grow your structure if possible, then convert the end result back to an array.

However, if you know the final size of the resulting array, you could instantiate it with something like `np.empty()` and then assign values by index, rather than appending. This does not change the size of the array itself, only reassigns values, so should not require copying.

1. Create a new matrix
2. Insert the values of your old matrix
3. Then, insert your new values in the last positions

``````x = np.array([[1,2,3],[10,20,30]])
new_X = np.zeros((2, 4))
new_X[:2,:3] = x
new_X[-1] = 4
new_X[-1] = 40
x=new_X
``````

Or Use np.reshape() or np.resize() instead

While @roganjosh is right that you cannot modify the numpy arrays without making a copy (in the underlying process), there is a simpler way of appending each value of an ndarray to the end of each numpy array in a 2d ndarray, by using numpy.column_stack

``````x = np.array([[1,2,3],[10,20,30]])
array([[ 1,  2,  3],
[10, 20, 30]])

stack_y = np.array([4,40])
array([ 4, 40])

numpy.column_stack((x, stack_y))
array([[ 1,  2,  3,  4],
[10, 20, 30, 40]])
``````
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.