1

np.dstack works as expected for 2D arrays, but for some reason for 3D arrays it stack not by last dimension.

What is proper way for stack by last dimension for ND arrays?

Example:

import numpy as np

#2D
a = np.zeros((2,2,1))
a.shape
(2, 2, 1)

np.dstack([a] * 3).shape
(2, 2, 3)

#3D
b = np.zeros((8,2,2,1))
b.shape
(8, 2, 2, 1)
np.dstack([b] * 3).shape
(8, 2, 6, 1)
mrgloom
  • 20,061
  • 36
  • 171
  • 301

1 Answers1

0

If you want to stack an array against itself, like in your example, you can use np.repeat

b = np.zeros((8,2,2,1))
n_stacks = 3
np.repeat(b, n_stacks, axis=b.ndim-1).shape
(8, 2, 2, 3)

If you want to stack two different arrays along their last dimension you can use np.concatenate

b = np.zeros((8,2,2,1))
c = np.ones((8,2,2,1))
np.concatenate((b,c),axis=b.ndim-1).shape
(8, 2, 2, 2)