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

Time:12-05

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?

CodePudding user response:

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