donchuan
donchuan

Reputation: 95

Numpy array of integers into numpy array of arrays

I would like to convert numpy array into numpy array of arrays.

I have an array: a = [[0,0,0],[0,255,0],[0,255,255],[255,255,255]]

and I would like to have: 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]]]

Is there any easy way to do it?

I have tried with np.where(a == 0, [0,0,0],[255,255,255]) but I got the following error:

ValueError: operands could not be broadcast together with shapes

Upvotes: 4

Views: 364

Answers (3)

Andrew Swann
Andrew Swann

Reputation: 1021

You can use broadcast_to as

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

where a was shape (3,4). Then you need to swap the axes around

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

giving

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]]])

A more direct method broadcasting method suggested by @Divakar is

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

which produces the same output without axis swapping.

Upvotes: 4

hpaulj
hpaulj

Reputation: 231738

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)

Looks like you want to replicate each element 3 times, making a new trailing dimension. We can do that using repeat (after adding the new trailing dimension):

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)

Upvotes: 1

Paul Panzer
Paul Panzer

Reputation: 53119

What you tried will work with the following small modification:

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

To make multidimensional indexing available we have to cast a to array first. a[...,None] adds a new dimension at the end of a to accomodate the triplets 0,0,0 and 255,255,255.

Upvotes: 2

Related Questions