Python And Numpy : Subtracting Line By Line A 2-dim Array From A 1-dim Array
In python, I wish to subtract line by line a 2-dim array from a 1-dim array. I know how to do it with a 'for' loop and indexes but I suppose it may be quicker to use numpy function
Solution 1:
The problem is that y-x
have the respective shapes (2) (2,5)
. To do proper broadcasting, you'll need shapes (2,1) (2,5)
. We can do this with .reshape
as long as the number of elements are preserved:
y.reshape(2,1) - x
Gives:
array([[19, 18, 17, 16, 15],
[ 4, 3, 2, 1, 0]])
Solution 2:
y[:,newaxis] - x
should work too. The (little) comparative benefit is then you pay attention to the dimensions themselves, instead of the sizes of dimensions.
Post a Comment for "Python And Numpy : Subtracting Line By Line A 2-dim Array From A 1-dim Array"