Append value to each array in a numpy array


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:


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[0] = np.append(x[0],4)
x[1] = np.append(x[1],40)
ValueError : could not broadcast input array from shape (4) into shape (3)
Asked By: hirschme



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.

Answered By: roganjosh
  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[0][-1] = 4
    new_X[1][-1] = 40

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

Answered By: Felipe Rigel

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]])
Answered By: Sephos
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.