Manasi
Manasi

Reputation: 189

Append dimensional numpy array

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.

Upvotes: 3

Views: 45

Answers (3)

Gulzar
Gulzar

Reputation: 27974

Another more literal method

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

Upvotes: 1

Moher
Moher

Reputation: 741

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.

Upvotes: 1

Daniel F
Daniel F

Reputation: 14399

Use np.stack

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

Upvotes: 4

Related Questions