简体   繁体   中英

(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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM