Home > Net >  How to modify an np.array like this?
How to modify an np.array like this?

Time:07-23

I have an empty array

arr = np.array([])

Then I have a loop. At the beginning of each iteration I want to modify the array so that the next index in the array is an array of 4 arrays with 3 zeros in each of the 4 arrays. So the first iteration would look like this.

[[[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]]

second iteration:

[[[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]
 [[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]]

Do I have use np.zeros as the initial array and specify a size? What modify methods should I use: concatenate, stack, etc?

CodePudding user response:

If you know the number of iterations before-hand, then it is as simple as:

arr = np.zeros((number_of_iterations, 4, 3))

E.g.:

>>> arr = np.zeros((2, 4, 3))  #  only two iterations
>>> arr
array([[[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]]])
  • Related