Skip to content
Advertisement

How to add 2D np array to front of 3D np array?

I have a 3D numpy array and I want to add a 2D np array of 0’s to the front of it.

import numpy as np
A = np.zeros(3,3,3)
for i in np.arange(0,2):
    for j in np.arange(0,2):
        for k in np.arange(0,2):
            A[i,j,k] = 10
print(A)
#returns:
 [[[10. 10.  0.]
  [10. 10.  0.]
  [ 0.  0.  0.]]

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

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

I want to add another array B so that:

B = np.zeros(3,3)
print(B)
#returns 
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

# add B to front of A 
# B + A = 
[[[0.  0.  0.]
  [0.  0.  0.]
  [0.  0.  0.]]

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

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

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

I’ve tried np.append(B,A) but it returns a 2D array.

Advertisement

Answer

You can do it using numpy.vstack and by reshaping your array. For instance:

import numpy as np

a = np.ones((3, 3, 3))
b = np.zeros((3, 3))
res = np.vstack((b.reshape(1, 3, 3), a))

By the way, you can create your array A more efficiently:

import numpy as np

A = np.zeros((3,3,3))
A[:2, :2, :2] = 10
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement