Ary
Ary

Reputation: 128

How to calculate the difference b/w each element in an numpy array with a shape[0]>2

Please feel free to let me know whether it is a duplicate question.

From in_arr1 = np.array([[2,0], [-6,0], [3,0]])

How can I get: diffInElements = [[5,0]] ?

I tried np.diff(in_arr1, axis=0) but it does not generate what I want. is there a NumPy function I can use ?

Cheers,

Upvotes: 0

Views: 469

Answers (2)

You want to subtract the remaining rows from the first row. The straightforward answer does just that:

>>> arr = np.array([[2, 1], [-6, 3], [3, -4]])
>>> arr[0, :] - arr[1:, :].sum(0)
array([5, 2])

There is also, however, a more advanced option making use of the somewhat obscure reduce() method of numpy ufuncs:

>>> np.subtract.reduce(arr, axis=0)
array([5, 2])

Upvotes: 0

user17242583
user17242583

Reputation:

You can negate and then sum all but the first value, and then add the first value:

diff = (-a[1:]).sum(axis=0) + a[0]

Output:

>>> diff
array([5, 0])

Upvotes: 1

Related Questions