Append dimensional numpy array

Viewed 35

I have two numpy array matrix A and B of length 32 and shape (32, 32, 3) each . I want to combine them into a new array so that the dimensions of my new array is (2, 32, 32,3).

Using np. concatenate is throwing an error.

3 Answers

Use np.stack

def dim0_stack(*arrays):
    return np.stack(arrays, axis = 0)

Another way to do it:

a = np.random.randn(32, 32, 3)
b = np.random.randn(32, 32, 3)
c = np.concatenate([np.expand_dims(a,0), np.expand_dims(b, 0)], axis=0)
print(c.shape)

Because you mentioned using concatenate, I thought to show you how you can use it.

Another more literal method

result = np.zeros((2, A.shape[0], A.shape[1], A.shape[2]))
result[0, :, :, :] = A
result[1, :, :, :] = B
Related