python - Numpy: Subtract 2 numpy arrays row wise -
i have 2 numpy arrays , b below:
a = np.random.randint(0,10,(3,2)) out[124]: array([[0, 2], [6, 8], [0, 4]]) b = np.random.randint(0,10,(2,2)) out[125]: array([[5, 9], [2, 4]])
i want subtract each row in b each row in , desired output of shape(3,2,2):
array([[[-5, -7], [-2, -2]], [[ 1, -1], [ 4, 4]], [[-5, -5], [-2, 0]]])
i can using:
print(np.c_[(a - b[0]),(a - b[1])].reshape(3,2,2))
but need vectorized solution or built in numpy function this.
just use np.newaxis
(which alias none) add singleton dimension a, , let broadcasting rest:
in [45]: a[:, np.newaxis] - b out[45]: array([[[-5, -7], [-2, -2]], [[ 1, -1], [ 4, 4]], [[-5, -5], [-2, 0]]])
Comments
Post a Comment