Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading