Let's call the four methods on add
function.
add
function, the result of reducing is similar to calculating the sum of an array. Call the reduce
method:a = np.arange(9) print "Reduce", np.add.reduce(a)
The reduced array should be as follows:
Reduce 36
accumulate
method also recursively goes through the input array. But, contrary to the reduce
method, it stores the intermediate results in an array and returns that. The result, in the case of the add
function, is equivalent to calling the cumsum
function. Call the accumulate
method on the add
function:print "Accumulate", np.add.accumulate(a)
The accumulated array:
Accumulate [ 0 1 3 6 10 15 21 28 36]
reduceat
method is a bit complicated to explain, so let's call it and go through its algorithm, step-by-step. The reduceat
method requires as arguments, an input array and a list of indices:print "Reduceat", np.add.reduceat(a, [0, 5, 2, 7])
The result is shown as follows:
Reduceat [10 5 20 15]
The first step concerns the indices 0
and 5
. This step results in a reduce operation of the array elements between indices 0
and 5
.
print "Reduceat step I", np.add.reduce(a[0:5])
The output of step 1 is as follows:
Reduceat step I 10
The second step concerns indices 5
and 2
. Since 2
is less than 5
, the array element at index 5
is returned:
print "Reduceat step II", a[5]
The second step results in the following output:
Reduceat step II 5
The third step concerns indices 2
and 7
. This step results in a reduce operation of the array elements between indices 2
and 7
:
print "Reduceat step III", np.add.reduce(a[2:7])
The result of the third step is shown as follows:
Reduceat step III 20
The fourth step concerns index 7
. This step results in a reduce operation of the array elements from index 7
to the end of the array:
print "Reduceat step IV", np.add.reduce(a[7:])
The fourth step result is shown as follows:
Reduceat step IV 15
outer
method returns an array that has a rank, which is the sum of the ranks of its two input arrays. The method is applied to all possible pairs of the input array elements. Call the outer
method on the add
function:print "Outer", np.add.outer(np.arange(3), a)
The outer sum output result is as follows:
Outer [[ 0 1 2 3 4 5 6 7 8] [ 1 2 3 4 5 6 7 8 9] [ 2 3 4 5 6 7 8 9 10]]
We applied the four methods, reduce
, accumulate
, reduceat
, and outer
, of universal functions to the add
function (see ufuncmethods.py
):
import numpy as np a = np.arange(9) print "Reduce", np.add.reduce(a) print "Accumulate", np.add.accumulate(a) print "Reduceat", np.add.reduceat(a, [0, 5, 2, 7]) print "Reduceat step I", np.add.reduce(a[0:5]) print "Reduceat step II", a[5] print "Reduceat step III", np.add.reduce(a[2:7]) print "Reduceat step IV", np.add.reduce(a[7:]) print "Outer", np.add.outer(np.arange(3), a)