简体   繁体   中英

How to zip 2D arrays

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM