Reputation: 43
I'm trying to figure out how to change an array such as:
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
a.shape
(3,3)
into:
a = np.array([[[1,255,255],[2,255,255],[3,255,255]],
[4,255,255],[5,255,255],[6,255,255]],
[7,255,255],[8,255,255],[9,255,255]]])
a.shape
(3,3,3)
essentially turning a single element 1
into a [1, 255, 255]
I've played around with reshape
but I can't seem to get the logic to do this without a slow for
loop.
Upvotes: 4
Views: 452
Reputation: 3828
One solution is to create a new array of the desired shape, filled with 255
s using np.full
, and then to just populate the index 0 value of each of the inner lists with the values from a
.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.full((3, 3, 3), 255)
b[:, :, 0] = a
Output is
array([[[ 1, 255, 255],
[ 2, 255, 255],
[ 3, 255, 255]],
[[ 4, 255, 255],
[ 5, 255, 255],
[ 6, 255, 255]],
[[ 7, 255, 255],
[ 8, 255, 255],
[ 9, 255, 255]]])
Upvotes: 4