简体   繁体   中英

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.

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)
data * scale_factors.reshape([-1]+[1]*(len(data.shape)-1))
data * scale_factors[:,None,None,None]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM