Home > Net >  Forming a 3D np array from a 2D array
Forming a 3D np array from a 2D array

Time:04-08

Let's say I have a 2D array:

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

I would like to make a 3D array from this, using a parameter N, such that (in this example, let's say N=4)

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

Is there a nice way of doing this?

Cheers

CodePudding user response:

One option is to add another dimension, then repeat along the new dimension.

N = 4
out = L[..., None].repeat(N, axis=-1)

Output:

array([[[1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3]],

       [[4, 4, 4, 4],
        [5, 5, 5, 5],
        [6, 6, 6, 6]],

       [[7, 7, 7, 7],
        [8, 8, 8, 8],
        [9, 9, 9, 9]]])

CodePudding user response:

You can use a combination of swapaxes and broadcast_to:

N = 4
L2 = np.broadcast_to(L.swapaxes(0, 1), (N, *reversed(L.shape))).swapaxes(0, 2)

Output will be as desired.

  • Related