I’m encountering an annoying shape mismatch issue when I’m working with arrays that are the same length, but one is only width one. For example:
import numpy as np
x = np.ones(80)
y = np.ones([80, 100])
x*y
ValueError: shape mismatch: objects cannot be broadcast to a single shape
The simple solution is y*x.reshape(x.shape[0],1). However, I often end up subsetting one column of an array, and then having to designate this reshape. Is there a way to avoid this?
Two somewhat easy ways are:
or
Numpy’s broadcasting is a very powerful feature, and will do exactly what you want automatically, but it expects the last axis (or axes) of the arrays to have the same shape, not the first axes. Thus, you need to transpose
yfor it to work.The second option is the same as what you’re doing, but
-1is treated as a placeholder for the array’s size, which reduces some typing.