简体   繁体   中英

How to create 3D array with filled value along one dimension?

It's easy to create a 2D array with filled values:

import numpy as np

np.full((5, 3), [1])
np.full((5, 3), [1, 2, 3])

Then, I wanna create a 3D array with same value for last two dimensions:

import numpy as np

np.full((2, 3, 1), [[1], [2]])

'''
# perferred result
[[[1],
  [1],
  [1]]
 [[2],
  [2],
  [2]]]
'''

However, I got this error:

ValueError: could not broadcast input array from the shape (2,1) into shape (2,3,1)

Does anyone know the correct way to use np.full() for 3D array?

In order to boardcast the value to the desired shape, you require the value in shape (2, 1, 1) to match with the input shape (2, 3, 1)

np.full((2, 3, 1), [[[1]], [[2]]])

output:

array([[[1],
        [1],
        [1]],

       [[2],
        [2],
        [2]]])

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