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,
CodePudding user response:
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])
CodePudding user response:
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])