Reputation: 5395
I was wondering if there a method that can subtract values? Something similar to sum
for Examples
> np.array([[10, 2], [1, 2]]).sum()
15
" imaginary method "
> np.array([[10, 2], [1, 2]]).sub()
6
# axis = 1
> np.array([[10, 2], [1, 2]]).sum(axis=1)
array([12, 3])
" imaginary method "
> np.array([[10, 2], [1, 2]]).sum(axis=1)
array([8, -1])
# axis = 0
> np.array([[10, 2], [1, 2]]).sum(axis=0)
array([11, 4])
"imaginary"
> np.array([[10, 2], [1, 2]]).sub(axis=0)
array([9, 0])
I am frustrated I cann't find anything in docs (somehow numpy docs are not easy to use if you don't know what you looking for).
thank you.
Upvotes: 1
Views: 3396
Reputation: 231510
np.sum
is np.add.reduce
:
In [87]: np.add.reduce(arr, axis=0)
Out[87]: array([11, 4])
In [88]: np.add.reduce(arr, axis=1)
Out[88]: array([12, 3])
There is a subtract
ufunc
too:
In [93]: np.subtract.reduce(arr, axis=0)
Out[93]: array([9, 0])
In [94]: np.subtract.reduce(arr, axis=1)
Out[94]: array([ 8, -1])
np.diff
does sliced subtraction:
In [97]: np.subtract(arr[:-1,:], arr[1:,:])
Out[97]: array([[9, 0]])
In [98]: np.subtract(arr[:,:-1], arr[:,1:])
Out[98]:
array([[ 8],
[-1]])
For two elements diff
and subtract.reduce
do the same thing. What's supposed to happen when you have more than 2 rows or columns?
In [109]: arr = np.array([[10, 2, 3], [1, 2, 4], [0, 1, 2]])
In [110]: arr
Out[110]:
array([[10, 2, 3],
[ 1, 2, 4],
[ 0, 1, 2]])
diff
does pair wise subtraction, row 0 from 1, row 1 from 2:
In [111]: np.diff(arr, axis=0)
Out[111]:
array([[-9, 0, 1],
[-1, -1, -2]])
subtract.reduce
does a cumulative, which might be easier to follow with the accumulate
alternative:
In [112]: np.subtract.reduce(arr, axis=0)
Out[112]: array([ 9, -1, -3])
In [113]: np.subtract.accumulate(arr, axis=0)
Out[113]:
array([[10, 2, 3],
[ 9, 0, -1],
[ 9, -1, -3]])
Upvotes: 1