将两个不同形状的 2d 数组转换为 3d 数组

问题描述 投票:0回答:1

如何将两个形状 (629, 5) 和 (629, 6) 的 2d 数组转换为形状 (629, 5, 6) 的 3d 数组?

输入:

[[2, 5, 6, 7, 8],
 [3, 5, 6, 7, 8],
 [4, 5, 6, 7, 8]]

[[2, 5, 6, 7, 8, 9],
 [3, 5, 6, 7, 8, 9],
 [4, 5, 6, 7, 8, 9]]

输出:

[[[2, 5, 6, 7, 8, 9], [2, 5, 6, 7, 8, 9], [2, 5, 6, 7, 8, 9], [2, 5, 6, 7, 8, 9], [2, 5, 6, 7, 8, 9]], 
 [[3, 5, 6, 7, 8, 9], [3, 5, 6, 7, 8, 9], [3, 5, 6, 7, 8, 9], [3, 5, 6, 7, 8, 9], [3, 5, 6, 7, 8, 9]], 
 [[4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9]]]
numpy reshape
1个回答
0
投票

如果你只是想广播

arr2
你可以使用:

arr1 = np.array([[2, 5, 6, 7, 8],
                 [3, 5, 6, 7, 8],
                 [4, 5, 6, 7, 8]])
arr2 = np.array([[2, 5, 6, 7, 8, 9],
                 [3, 5, 6, 7, 8, 9],
                 [4, 5, 6, 7, 8, 9]])

out = np.broadcast_to(arr2[:,None], (*arr1.shape, arr2.shape[1]))

或:

out = np.repeat(arr2[:,None], arr1.shape[1], axis=1)

输出:

array([[[2, 5, 6, 7, 8, 9],
        [2, 5, 6, 7, 8, 9],
        [2, 5, 6, 7, 8, 9],
        [2, 5, 6, 7, 8, 9],
        [2, 5, 6, 7, 8, 9]],

       [[3, 5, 6, 7, 8, 9],
        [3, 5, 6, 7, 8, 9],
        [3, 5, 6, 7, 8, 9],
        [3, 5, 6, 7, 8, 9],
        [3, 5, 6, 7, 8, 9]],

       [[4, 5, 6, 7, 8, 9],
        [4, 5, 6, 7, 8, 9],
        [4, 5, 6, 7, 8, 9],
        [4, 5, 6, 7, 8, 9],
        [4, 5, 6, 7, 8, 9]]])
© www.soinside.com 2019 - 2024. All rights reserved.