0

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?

2 Answers 2

3

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]]])
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.