Joe Phongpreecha
Joe Phongpreecha

Reputation: 133

Stacking arrays in new dimension

let's say I have three arrays

k = np.array([[1,1],[2,2]])
m = np.array([[3,3],[4,4]])
n = np.array([[5,5],[6,6]])

I ideally I would like to achieve a final arrays of a shape (3,2,2), i.e.

array([[[1, 1],
        [2, 2]],

       [[3, 3],
        [4, 4]]

       [[5, 5],
        [6, 6]]])

So I did

l = np.stack((k,m), axis=0)

and got an array

array([[[1, 1],
        [2, 2]],

       [[3, 3],
        [4, 4]]])

of size (2,2,2). However, when I tried to append/stack the n array, I always got an error of wrong dimension. I could do np.dstack but that's not giving me what I want. Any help with this would be very much appreciated. Thank you.

Upvotes: 2

Views: 3320

Answers (1)

kmario23
kmario23

Reputation: 61355

Just for the sake of completeness and to close this question, the answers suggested by Akavall and f5r5e5d are all working solutions.

# Akavall's solution
np.stack((k, m, n), axis=0)

# f5r5e5d's solution
np.array([k,m,n])

# my approach
In [38]: np.concatenate((k[None, :, :], m[None, :, :], n[None, :, :]))
Out[38]: 
array([[[1, 1],
        [2, 2]],

       [[3, 3],
        [4, 4]],

       [[5, 5],
        [6, 6]]])

Upvotes: 2

Related Questions