Stefan Renard
Stefan Renard

Reputation: 73

How can I efficiently extend one dimension of a multidimensional array?

I have two numpy arrays:

data.shape -> (100, 81, 121, 6, 3)
(n_samples, latitude, longitude, features, level)

labels.shape -> (100, 2)
(n_samples, target_value)

All I want is to append the two vectors of labels to the 4 dimension of data. So my goal is to end up with a new array like this:
result.shape -> (100, 81, 121, 8, 3).

I'm looking for an efficient solution with numpy, xarray, pandas, etc. But find none. I hope someone can help me.

Upvotes: 1

Views: 60

Answers (1)

Divakar
Divakar

Reputation: 221564

Use np.broadcast_to to broadcast the smaller array to bigger array's shape and then concatenate with it along the axis of concatenation -

In [215]: data = np.random.rand(100,81,121,6,3)

In [216]: labels = np.random.rand(100,2)

In [218]: labels_ext = np.broadcast_to(labels[:,None,None,:,None],(100,81,121,2,3))

In [219]: np.concatenate((data,labels_ext),axis=3).shape
Out[219]: (100, 81, 121, 8, 3)

Upvotes: 2

Related Questions