P227
P227

Reputation: 47

Forming a 3D np array from a 2D array

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?

Upvotes: 1

Views: 90

Answers (2)

Professor Pantsless
Professor Pantsless

Reputation: 484

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.

Upvotes: 0

user7864386
user7864386

Reputation:

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

Upvotes: 4

Related Questions