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 stack 2d array on an existing 3d array (python)

I’m trying to "stack" array a2 below a1 such that I get array b with the following shape

a1.shape => (2, 50, 241)
a2.shape => (50, 241)

# goal
b.shape => (3, 50, 241)

This was my attempt, but np.stack requires the same shape

b = np.stack([a1, a2])

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

>Solution :

import numpy as np
arr1 = np.random.rand(2, 50, 241)
arr2 = np.random.rand(50, 241)

Reshape arr2 so it’s got the same 3d structure:

arr2 = arr2.reshape(1, 50, 241)

Vstack it:

arr3 = np.vstack((arr1, arr2))

>>> arr3.shape
(3, 50, 241)
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