user20408
user20408

Reputation: 709

Stumped on easy numpy problem - append 2D array to 3D array

I have a 3D array with the dimensions (X, Y, 8) and a 2D array with dimensions (X, Y). I know there is an easy solution but cannot seem to figure out how to append the 2D array to the 3D array such that the output has dimensions (X, Y, 9). I have tried append, concatenate, dstack, column_stack() with a million different variations (in how I am formatting the input arrays, which axis, etc.) and keep getting either the error "all the input arrays must have same number of dimensions" or "all the input array dimensions except for the concatenation axis must match exactly."

I have looked at and followed every relevant SO question. That I can't seem to figure out something so easy is driving me nuts. Help?

Upvotes: 0

Views: 67

Answers (1)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

Given:

  • arr3d of shape (z, y, x)
  • arr2d of shape (z, y)

You can concatenate them to an array of shape (z, y, x + 1) by:

np.concatenate((arr3d, arr2d[..., np.newaxis]), axis=-1)

where arr2d[..., np.newaxis] is of shape (z, y, 1).

Upvotes: 1

Related Questions