将整数的Numpy数组转换为数组的Numpy数组

2024-04-25 07:03:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把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

Tags: 方法numpy错误withnpnot数组be
3条回答

您尝试的操作将通过以下小的修改生效:

a = np.array(a)
np.where(a[...,None]==0,[0,0,0],[255,255,255])

要使多维索引可用,我们必须首先将a转换为arraya[...,None]a的末尾添加一个新维度,以容纳三元组0、0、0和255255。你知道吗

您可以使用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))

在不交换轴的情况下产生相同的输出。你知道吗

In [204]: a = np.array([[0,0,0],[0,255,0],[0,255,255],[255,255,255]])           
In [205]: a.shape                                                               
Out[205]: (4, 3)

看起来您想将每个元素复制3次,生成一个新的尾随维度。我们可以使用repeat(在添加新的尾随维度之后)来实现这一点:

In [207]: a.reshape(4,3,1).repeat(3,2)                                          
Out[207]: 
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]]])
In [208]: _.shape                                                               
Out[208]: (4, 3, 3)

相关问题 更多 >