1

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.

1
  • expand_dims takes a tuple, so you can add a number of trailing dimensions with something like: np.expand_dims(np.arange(5),tuple(range(1,4))). Under the covers, expand_dims constructs a shape and does a reshape. Commented Jul 11, 2022 at 18:31

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

The "data" ndarray will not always be the same shape, and won't even always have the same number of dimensions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.