Say I have
x=np.random.random((3,10))
y=np.array([1,10,100])
and I want to subtract the values in each column of x
from y
. I can do this like so:
np.array([y]*10).T-x
However, this involves the creation of a new array of 10 times the size of y
(in this case). I could also imagine using a for loop. Can anyone suggest a better way of doing this?
Something like this?
>>> (y - x.T).T
array([[ 8.79354250e-01, 5.30104393e-01, 7.78342126e-01,
4.56857161e-02, 5.32181828e-01, 1.47155126e-01,
3.39654176e-01, 3.72693537e-01, 4.32737024e-01,
7.55366710e-01],
[ 9.53976069e+00, 9.51725133e+00, 9.00439583e+00,
9.65411497e+00, 9.55728110e+00, 9.35189161e+00,
9.72451832e+00, 9.20089714e+00, 9.60367043e+00,
9.41722649e+00],
[ 9.99248465e+01, 9.96932738e+01, 9.93110996e+01,
9.94116657e+01, 9.98695626e+01, 9.92118001e+01,
9.93602275e+01, 9.99518088e+01, 9.98442735e+01,
9.93865628e+01]])
Just stack y
vertically and subtract x
. For example:
y[:, None] - x # insert a new axis into y (creating a new view of y)
or
np.vstack(y) - x # stack y vertically (creating a copy of y)
This works because y
now has shape (3, 1)
and so can be broadcast with your x
which has shape (3, 10)
.
x
and y
can be broadcast together if each trailing dimension (i.e. starting from the end of the shape tuple) of x
is equal to the trailing dimension of y
, or if one of the compared dimensions is 1. In this example, the trailing dimension of y
was changed to 1, so that the two arrays are compatible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With