Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have 4 NumPy arrays, each of the shapes (5,5). I would like to stack them such that I get a new array of shapes (5,5,4). I tried using:

N = np.stack((a, b, c, d))

but, as I am new to using NumPy, I cannot understand why that is giving a shape of (4, 5, 5) instead of (5, 5, 4). Is there another method I should be using? the dstack works but changes my arrays, I think it is transposing them.

For example, 4 arrays

[[1,2]

 [3,4]]

[[1,2]

 [3,4]]

[[1,2]

 [3,4]]

[[1,2]

 [3,4]]

when stacked I am expecting:

[[[1,2]

 [3,4]]

[[1,2]

 [3,4]]

[[1,2]

 [3,4]]

[[1,2]

 [3,4]]]

This is working as expected with stack but would give the shape of (4,2,2) instead of (2,2,4). From my understanding, this shape is (rows, columns, depth) Am I correct?

1 Answer

0 votes
by (36.8k points)
edited by

I believe you have concatenate the arrays, and reshape into the 3D array as:

l = [a,b,c,d]

np.concatenate(l).reshape(len(l), *a.shape)

Or if you want to avoid creating that list and know your amount of arrays beforehand:

np.concatenate((a,b,c,d)).reshape(4, *a.shape)

Checking on a shared example:

a = [[1, 2], [3, 4]]

d = c = b = a

np.concatenate((a,b,c,d)).reshape(4, *np.array(a).shape)

array([[[1, 2],

        [3, 4]],

       [[1, 2],

        [3, 4]],

       [[1, 2],

        [3, 4]],

       [[1, 2],

        [3, 4]]])

Want to gain skills in Data Science with Python? Sign up today for this Data Science with Python Course and be a master in it 

Related questions

Browse Categories

...