pwtools.num.sum

pwtools.num.sum(arr, axis=None, keepdims=False, **kwds)[source]

This numpy.sum() with some features implemented which can be found in numpy v1.7 and later: axis can be a tuple to select arbitrary axes to sum over.

We also have a keepdims keyword, which however works completely different from numpy. Docstrings shamelessly stolen from numpy and adapted here and there.

Parameters:
  • arr (nd array) –

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a sum is performed. The default (axis = None) is to perform a sum over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis. If this is a tuple of ints, a sum is performed on multiple axes, instead of a single axis or all the axes as before.

  • keepdims (bool, optional) – If this is set to True, the axes from axis are left in the result and the reduction (sum) is performed for all remaining axes. Therefore, it reverses the axis to be summed over.

  • **kwds (passed to np.sum().) –

Examples

>>> a=rand(2,3,4)
>>> num.sum(a)
12.073636268676152
>>> a.sum()
12.073636268676152
>>> num.sum(a, axis=1).shape
(2, 4)
>>> num.sum(a, axis=(1,)).shape
(2, 4)
>>> # same as axis=1, i.e. it inverts the axis over which we sum
>>> num.sum(a, axis=(0,2), keepdims=True).shape
(2, 4)
>>> # numpy's keepdims has another meaning: it leave the summed axis (0,2)
>>> # as dimension of size 1 to allow broadcasting
>>> numpy.sum(a, axis=(0,2), keepdims=True).shape
(1, 3, 1)
>>> num.sum(a, axis=(1,)) - num.sum(a, axis=1)
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> num.sum(a, axis=(0,2)).shape
(3,)
>>> num.sum(a, axis=(0,2)) - a.sum(axis=0).sum(axis=1)
array([ 0.,  0.,  0.])