How to insert data in a numpy array, preserving its shape?

Question:

I have a collection of several data of fixed shape, and I need to store these values in an array, only creating a new dimension, so I can preserve its initial shape. Here is a small example,

arr = np.array([0,1,2])
values = np.array([[3,4,5], [6,7,8], [9,10,11]])

n = 3

for i in range(n):
    arr = np.append(arr, values[n])

I need the code to output something simmilar to

>> array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])

But i can only find

>> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
Is there a function that can handle this problem?

Answers:

This is an easy one. Reshape your arr into a 2d array and add an axis argument to np.append.

import numpy as np
arr = np.array([0,1,2])
values = np.array([[3,4,5], [6,7,8], [9,10,11]])

out = np.append(arr.reshape(1,-1),values,axis=0)
print(out)

Yields:

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
Answered By: Carbon

There are various functions that all use np.concatenate. np.append is a poorly named function that just takes 2 arguments. It looks too much like list append, thus encouraging a iterative use such as yours. That’s not efficient. And your problem is you didn’t provide an axis.

In this case I prefer to use vstack.

In [24]: np.vstack((arr,values))
Out[24]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

It makes sure the first argument is 2d, i.e. [[0,1,2]] so that concatenate is happy.

concatenate without the dimension adjustment:

In [25]: np.concatenate((arr,values), axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[25], line 1
----> 1 np.concatenate((arr,values), axis=0)

File <__array_function__ internals>:200, in concatenate(*args, **kwargs)

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)

With the adjustment. This is essentially that append with axis does:

In [26]: np.concatenate((arr[None,:],values), axis=0)
Out[26]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
Answered By: hpaulj
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.