Krystian K
Krystian K

Reputation: 377

(Python Numpy) How can I create new 3D array from given 2D array?

I want to do something like this:

I give a 2D numpy array:

[[ 1, 2, 3],
 [ 4, 5, 6],
 [ 7, 8, 9]]

And I want to get a 3D numpy array:

[[[1, 1, 1],
  [2, 2, 2],
  [3, 3, 3]],

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

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

Does numpy has a function that can do this transformation?

Upvotes: 0

Views: 199

Answers (2)

jkr
jkr

Reputation: 19250

One can use np.tile. Before doing this, a dimension needs to be added at the end of the array.

In [28]: x = np.array([[ 1, 2, 3],
    ...:  [ 4, 5, 6],
    ...:  [ 7, 8, 9]])

In [29]: np.tile(x[..., None], 3)
Out[29]: 
array([[[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]],

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

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

Upvotes: 3

Amit Vikram Singh
Amit Vikram Singh

Reputation: 2128

First extend the dimension of 2D array using arr[:, :, np.newaxis], this changes dimension from (3, 3) to (3, 3, 1). Now repeat this 3D array along the third dimension.

Use:

arr = np.repeat(arr[:, :, np.newaxis], 3, -1)

Output:

>>> np.repeat(arr[:, :, np.newaxis], 3, -1)
array([[[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]],

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

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

Upvotes: 2

Related Questions