numpy.cumsum#
- numpy.cumsum(a,axis=None,dtype=None,out=None)[source]#
Return the cumulative sum of the elements along a given axis.
- Parameters:
- aarray_like
Input array.
- axisint, optional
Axis along which the cumulative sum is computed. The default(None) is to compute the cumsum over the flattened array.
- dtypedtype, optional
Type of the returned array and of the accumulator in which theelements are summed. If
dtypeis not specified, it defaultsto the dtype ofa, unlessa has an integer dtype with aprecision less than that of the default platform integer. Inthat case, the default platform integer is used.- outndarray, optional
Alternative output array in which to place the result. It musthave the same shape and buffer length as the expected outputbut the type will be cast if necessary. SeeOutput type determinationfor more details.
- Returns:
- cumsum_along_axisndarray.
A new array holding the result is returned unlessout isspecified, in which case a reference toout is returned. Theresult has the same size asa, and the same shape asa ifaxis is not None ora is a 1-d array.
See also
cumulative_sumArray API compatible alternative for
cumsum.sumSum array elements.
trapezoidIntegration of array values using composite trapezoidal rule.
diffCalculate the n-th discrete difference along given axis.
Notes
Arithmetic is modular when using integer types, and no error israised on overflow.
cumsum(a)[-1]may not be equal tosum(a)for floating-pointvalues sincesummay use a pairwise summation routine, reducingthe roundoff-error. Seesumfor more information.Examples
>>>importnumpyasnp>>>a=np.array([[1,2,3],[4,5,6]])>>>aarray([[1, 2, 3], [4, 5, 6]])>>>np.cumsum(a)array([ 1, 3, 6, 10, 15, 21])>>>np.cumsum(a,dtype=float)# specifies type of output value(s)array([ 1., 3., 6., 10., 15., 21.])
>>>np.cumsum(a,axis=0)# sum over rows for each of the 3 columnsarray([[1, 2, 3], [5, 7, 9]])>>>np.cumsum(a,axis=1)# sum over columns for each of the 2 rowsarray([[ 1, 3, 6], [ 4, 9, 15]])
cumsum(b)[-1]may not be equal tosum(b)>>>b=np.array([1,2e-9,3e-9]*1000000)>>>b.cumsum()[-1]1000000.0050045159>>>b.sum()1000000.0050000029