np.subtract along an axis

Viewed 270

Is there an easy way to subtract along the axis of 2-D array?

a=np.array([[610,550],[400,360]])
np.sum(a,axis=0) # Results in  array([1010, 910])

np.subtract(a[0],a[1]) # Results in array([210, 190])
np.subtract(a,axis=0) # Errors out obviously
1 Answers

np.subtract subtracts the corresponding elements of two arrays. Subtraction of two arrays along an axis is meaningless, since it happens to each element regardless of its position relative to its neighbors. Notice that in your example, np.sum only accepts one array, not two.

To find the differences between successive elements of a single array, use np.diff, which accepts an axis argument exactly as you would expect

np.diff(a, axis=0)

You can manually implement diff by calling subtract on an array sliced as 1: and :-1 along the desired axis. In your example:

a[1:] - a[:-1]
Related