Home > Enterprise >  Multiply multidimensional numpy array by 1-D array
Multiply multidimensional numpy array by 1-D array

Time:07-12

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.

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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