Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

viraatdas
Copy link

@viraatdas viraatdas commented Sep 8, 2025

Description

This PR implements a reverse keyword-only parameter for the following functions:

  • numpy.cumsum
  • numpy.cumprod
  • numpy.nancumsum
  • numpy.nancumprod

When reverse=True, accumulation proceeds right-to-left along the specified axis.
It is equivalent to:

np.flip(fn(np.flip(a, axis=axis), axis=axis), axis=axis)

but implemented using negative-stride views to avoid extra copies.
If out is provided, we accumulate into a flipped view of the output array.

Rationale

  • Addresses gh-29144.
  • A flip-based approach is efficient, requires no C-API changes, and preserves subclass behavior.
  • Scope is limited to high-level APIs (numpy.cumsum, etc.) and does not modify ndarray.cumsum/cumprod or ufunc.accumulate.
    If desired, ufunc.accumulate(reverse=...) can follow in a later PR.

API Changes

  • New argument: reverse=False (keyword-only).
  • Supported for both regular and NaN-aware variants.
  • Works with axis=None, dtype=, and out=.

Examples

>>> import numpy as np
>>> x = np.array([1, 2, 3, 4])
>>> np.cumsum(x)
array([ 1,  3,  6, 10])
>>> np.cumsum(x, reverse=True)
array([10,  9,  7,  4])

>>> np.cumprod(x, reverse=True)
array([24, 24, 12, 4])

>>> y = np.array([1.0, np.nan, 2.0])
>>> np.nancumsum(y, reverse=True)
array([3., 2., 2.])

>>> # Works with multi-dimensional arrays
>>> z = np.arange(6).reshape(2, 3)
>>> np.cumsum(z, axis=1, reverse=True)
array([[ 3,  3,  2],
       [12,  9,  5]])

Tests

  • Added new test files covering:
  • 1D and multi-D arrays
  • axis=None behavior
  • dtype overrides
  • out parameter
  • NaN propagation for nancumsum and nancumprod
  • Empty arrays

All new tests pass locally.

@mattip
Copy link
Member

mattip commented Sep 8, 2025

The proposal had no discussion. Usually new kwargs or functionality is discussed in the issue and a concensus is reached that it is a good thing before submitting a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants