0

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?

4
  • 1
    Sounds like you are trying things at random, without understanding the underlying mechanism. You can only concatenate a (X,Y,1) to your (X,Y,8). Forget about all those append and stack. Add the dimension to the (X,Y) and then simply use np.concatenate. And take those error messages seriously! Commented Aug 5, 2020 at 7:26
  • 1
    Another way to get a good answer is to provide a small example, with actual code and error message (and traceback). Then we can point out exactly what you are doing wrong! Commented Aug 5, 2020 at 7:29
  • 1
    how about something like np.concatenate((np.zeros([x,y,8]), np.ones([x,y]).reshape([x,y,1])), axis=2) ? (replace the np.zeros and np.ones with your arrays of course) Commented Aug 5, 2020 at 7:30
  • 1
    np.concatenate((arr3d, arr2d[..., np.newaxis]), axis=-1) Commented Aug 5, 2020 at 7:31

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

that works, as does np.append(arr3d, arr2d[..., np.newaxis], axis = 2). I just feel like I have previously been able to do np.append(arr3d, [arr2d], axis = 2) and was frustrated that that was not working. I was unfamilar with [..., np.newaxis]. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.