Home > Mobile >  How to stack 2d array on an existing 3d array (python)
How to stack 2d array on an existing 3d array (python)

Time:12-18

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

CodePudding user response:

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)

CodePudding user response:

If your arrays are numpy arrays, try np.append

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

This is assuming you are trying to construct b such that a2 is the last item of b and a1 is the first 2 items.

CodePudding user response:

Try using:

a2_reshaped = a2.reshape((1,)   a2.shape)
b = np.stack([a1, a2_reshaped])
  • Related