user297850
user297850

Reputation: 8015

append an numpy ndarray to another one along certain dimensions

There exist two numpy.ndarray, e.g., A is of shape (5,3,2), B is of shape (5,3).

A = np.random.rand(5,3,2)
B=np.random.rand(5,3)  #----- there was typo here

I would like to append B into A, and make the resulting array C with shape (5,3,3) I tried to use np.contaenate, but it does not work.

c=np.concatenate((a,b),axis=2) 

Upvotes: 0

Views: 124

Answers (1)

Ashley Alfredssons
Ashley Alfredssons

Reputation: 109

import numpy as np

a = np.random.rand(5,3,2)
b = np.random.rand(5,3)

b = b[..., np.newaxis] # or np.expand_dims(b, axis=2) or b.reshape(b.shape+(1,))
print(b) # (5, 3, 1)
c = np.append(a, b, axis=2)
print(c.shape) # (5, 3, 2)

Upvotes: 1

Related Questions