Mathew Carroll
Mathew Carroll

Reputation: 377

NumPy: Concatenating 1D array to 3D array

Suppose I have a 5x10x3 array, which I interpret as 5 'sub-arrays', each consisting of 10 rows and 3 columns. I also have a seperate 1D array of length 5, which I call b.

I am trying to insert a new column into each sub-array, where the column inserted into the ith (i=0,1,2,3,4) sub-array is a 10x1 vector where each element is equal to b[i].

For example:

import numpy as np
np.random.seed(777)
A = np.random.rand(5,10,3)
b = np.array([2,4,6,8,10])

A[0] should look like:

A[1] should look like:

And similarly for the other 'sub-arrays'. (Notice b[0]=2 and b[1]=4)

Upvotes: 2

Views: 1236

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

One method would be np.pad:

np.pad(A, ((0,0),(0,0),(0,1)), 'constant', constant_values=[[[],[]],[[],[]],[[],b[:, None,None]]])
# array([[[9.36513084e-01, 5.33199169e-01, 1.66763960e-02, 2.00000000e+00],
#         [9.79060284e-02, 2.17614285e-02, 4.72452812e-01, 2.00000000e+00],
 # etc.

Or (more typing but probably faster):

i,j,k = A.shape
res = np.empty((i,j,k+1), np.result_type(A, b))
res[...,:-1] = A
res[...,-1] = b[:, None]

Or dstack after broadcast_to:

np.dstack([A,np.broadcast_to(b[:,None],A.shape[:2])]

Upvotes: 0

spadarian
spadarian

Reputation: 1624

What about this?

# Make an array B with the same dimensions than A
B = np.tile(b, (1, 10, 1)).transpose(2, 1, 0)  # shape: (5, 10, 1)

# Concatenate both
np.concatenate([A, B], axis=-1)  # shape: (5, 10, 4)

Upvotes: 1

Related Questions