Ayman Alawin
Ayman Alawin

Reputation: 93

Concatenate 1D array to a 3D array

I have a three dimensional array A, with shape (5774,15,100) and another 1 D array B with shape (5774,). I want to add these in order to get the another matrix C with shape (5774,15,101).

I am using hstack as

C = hstack((A ,np.array(B)[:,None]))

I am getting the below error, any suggesstions.

ValueError: could not broadcast input array from shape (5774,15,100) into shape (5774)

Upvotes: 2

Views: 2842

Answers (1)

Daniel F
Daniel F

Reputation: 14399

You'd need to use np.concatenate (which can cancatenate arrays of different shape, unlike the various np.*stack methods). Then, you need to use np.broadcast_to to get that (5774,) shaped array to (5774, 15, 1) (because concatenate still needs all the arrays to have the same number of dimensions).

C = np.concatenate((A, 
                    np.broadcast_to(np.array(B)[:, None, None], A.shape[:-1] + (1,))), 
                   axis = -1)

Checking:

A = np.random.rand(5774, 15, 100)
B = np.random.rand(5774)
C = np.concatenate((A, 
                    np.broadcast_to(np.array(B)[:, None, None], A.shape[:-1] + (1,))), 
                   axis = -1)
C.shape

Out: (5774, 15, 101)

Upvotes: 7

Related Questions