简体   繁体   English

如何 zip 2D arrays

[英]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.我有 2 个相同的 2D arrays,我正在尝试按元素对它们进行 zip。 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.先把arrays、zip他们压平,转成列表,再转成数组再整形。

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.它没有将最终数组的元素(1,1) (2,2)等视为元组,而是作为单个元素。 Hence, 18 elements.因此,有 18 个元素。

This question has been posted once but I didn't find an answer that worked for me.这个问题已发布一次,但我没有找到适合我的答案

Don't zip , use numpy native functions!不要zip ,使用 numpy 本机功能! You want a dstack :你想要一个dstack

out = np.dstack([a, b])

output: output:

array([[[1, 1],
        [2, 2],
        [3, 3]],

       [[4, 4],
        [5, 5],
        [6, 6]],

       [[7, 7],
        [8, 8],
        [9, 9]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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