Home > OS >  replace one floor of a 3D np array by a 2D numpy array
replace one floor of a 3D np array by a 2D numpy array

Time:02-04

I'm trying to "replace one floor of a 3D np array by a 2D numpy array"

this is my code, but I'm pretty sure there is a better way :

import numpy as np
w,h = 2,5
board_2D = np.random.randint(1, 5, size=(h, w))
board_3D = np.arange(h*w*4).reshape(4,h,w)
print(board_3D)

z= 1
for y in range(h):
    for x in range(w):
        board_3D[z,y,x] = board_2D[y,x]

print(board_3D)

CodePudding user response:

Are you sure your output is correct?

I think you meant to do:

board_3D[1] = board_2D

output:

array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5],
        [ 6,  7],
        [ 8,  9]],

       [[ 2,  1],
        [ 2,  4],
        [ 4,  1],
        [ 4,  1],
        [ 3,  1]],

       [[20, 21],
        [22, 23],
        [24, 25],
        [26, 27],
        [28, 29]],

       [[30, 31],
        [32, 33],
        [34, 35],
        [36, 37],
        [38, 39]]])
  •  Tags:  
  • Related