a=np.array([[1,2,3],[4,5,6],[7,8,9]])
b=np.array([[1,2,3],[4,5,6],[7,8,9]])
I've 2 identical 2D arrays, I'm trying to zip them element-wise. It should look like:
[[(1,1) (2,2), (3,3)]
[(4,4) (5,5) (6,6)]
[(7,7) (8,8) (9,9)]]
I've tried the method below but it didn't work out. First flatten the arrays, zip them, convert it into a list, then convert it into an array and reshape it.
np.array(list(zip(np.ndarray.flatten(a),np.ndarray.flatten(b)))).reshape(a.shape)
I'm getting the following error
cannot reshape array of size 18 into shape (3,3)
It's not treating the elements (1,1) (2,2)
etc. of the final array as tuples but as individual elements. Hence, 18 elements.
This question has been posted once but I didn't find an answer that worked for me.
CodePudding user response:
Don't zip
, use numpy native functions! You want a dstack
:
out = np.dstack([a, b])
output:
array([[[1, 1],
[2, 2],
[3, 3]],
[[4, 4],
[5, 5],
[6, 6]],
[[7, 7],
[8, 8],
[9, 9]]])