Colin
Colin

Reputation: 10820

Multiply multidimensional numpy array by 1-D array

I have a multidimensional array and a set of scale factors that I want to apply along the first axis:

>>> data.shape, scale_factors.shape
((22, 20, 2048, 2048), (22,))
>>> data * scale_factors
ValueError: operands could not be broadcast together with shapes (22,20,2048,2048) (22,) 

I can do this with apply_along_axis, but is there a vectorized way to do this? I found a similar question, but the solution is specific to a 1-D * 2-D operation. The "data" ndarray will not always be the same shape, and won't even always have the same number of dimensions. But the length of the 1-D scale_factors will always be the same as axis 0 of data.

Upvotes: 1

Views: 46

Answers (3)

Ahmed AEK
Ahmed AEK

Reputation: 17496

data * scale_factors.reshape([-1]+[1]*(len(data.shape)-1))

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150735

You can try reshape the data into 2D, then broadcast scale_factor to 2D, and reshape back:

(data.reshape(data.shape[0], -1) * scale_factors[:,None]).reshape(data.shape)

Or, you can swap the 0-th axis to the last so you can broadcast:

(data.swapaxes(0,-1) * scale_factors).swapaxes(0,-1)

Upvotes: 1

Frank Yellin
Frank Yellin

Reputation: 24

data * scale_factors[:,None,None,None]

Upvotes: -1

Related Questions