首页 > 解决方案 > 将两个 numpy 数组按索引连接在一起

问题描述

我有两个 2D numpy 数组:

a = np.array([[0,1,2,3,4],
              [0,1,2,3,4],
              [0,1,2,3,4]
              ...
              ])

b = np.array([[0,0,0,0,0],
              [1,1,1,1,1],
              [2,2,2,2,2],
              ...
              ])

我如何能够获得一个 numpy 数组,其中每个精确索引将连接在一起?

OUT:
[[0,0], [1,0], [2,0], [3,0], [4,0] [0,1], [1,1], [2,1], [3,1], [4,1] ...]

标签: pythonarraysnumpy

解决方案


你想要堆栈

result = np.stack((a,b), axis=2)
array([[[0, 0],
        [1, 0],
        [2, 0],
        [3, 0],
        [4, 0]],

       [[0, 1],
        [1, 1],
        [2, 1],
        [3, 1],
        [4, 1]],

       [[0, 2],
        [1, 2],
        [2, 2],
        [3, 2],
        [4, 2]]])

取自@user15270287,您可以使用重塑结果np.reshape(result, (-1, 2))


推荐阅读