首页 > 解决方案 > numpy 整数数组转换为 numpy 数组数组

问题描述

我想将 numpy 数组转换为 numpy 数组数组。

我有一个数组:a = [[0,0,0],[0,255,0],[0,255,255],[255,255,255]]

我想拥有:b = [[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[255,255,255],[0,0,0]],[[0,0,0],[255,255,255],[255,255,255]],[[255,255,255],[255,255,255],[255,255,255]]]

有什么简单的方法吗?

我已经尝试过,np.where(a == 0, [0,0,0],[255,255,255])但出现以下错误:

ValueError: operands could not be broadcast together with shapes

标签: pythonarraysnumpy

解决方案


您可以broadcast_to用作

b = np.broadcast_to(a, (3,4,3))

a形状在哪里(3,4)。然后你需要交换轴

import numpy as np
a = np.array([[0,0,0],[0,255,0],[0,255,255],[255,255,255]])
b = np.broadcast_to(a, (3,4,3))
c = np.moveaxis(b, [0,1,2], [2,0,1])
c

给予

array([[[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [255, 255, 255],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [255, 255, 255],
        [255, 255, 255]],

       [[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]]])

@Divakar 建议的更直接的方法广播方法是

 b = np.broadcast(a[:,:,None], (4,3,3))

它在没有轴交换的情况下产生相同的输出。


推荐阅读