Skip to content

np.count_nonzero() should accept axis parameter #391

Closed

Description

@kernc

Currently, np.count_nonzero() accepts only the input array. I propose adding axis parameter similar to that of functions np.sum() and np.max() etc.

>>> A = np.arange(6).reshape(2,3)
>>> np.count_nonzero(A)  # with axis=None, count_nonzero in flattened A
5
>>> np.count_nonzero(A, axis=0)
array([1, 2, 2])
>>> np.count_nonzero(A, axis=1)
array([2, 3])

I think the alternative (A != 0).sum(axis=rows_or_cols) isn't as clear.

Activity

  1. charris commented on Feb 17, 2014

    @charris
    Member

    Sounds reasonable.

  2. jaimefrio commented on Feb 17, 2014

    @jaimefrio
    Member

    I wrote this elsewhere, but if no one else wants to try it, I can go on an "add axis" spree: I have working code for bincount (will try to make it into a PR tonight), and have searchsorted, interp, and now count_nonzero in the pipeline. Is there any other obvious one I am forgetting about?

  3. herr-biber commented on Apr 23, 2014

    @herr-biber
    Contributor

    Any news on this? I'd be interested in this feature as well.

  4. juliantaylor commented on Apr 23, 2014

    @juliantaylor
    Contributor

    an alternative might be to try and adapt sum(bool) to use the much faster non-casting count_nonzero code.
    sum is already a full ufunc with all bells and whistles so one gets (extended) axis for free

  5. seberg commented on Apr 23, 2014

    @seberg
    Member

    I am unsure if the ufunc reduce supports mixed type inner loops.

  6. WarrenWeckesser commented on Aug 6, 2014

    @WarrenWeckesser
    Member

    +1 for adding an axis argument to count_nonzero().

  7. JaimieMurdock commented on Nov 19, 2014

    @JaimieMurdock

    +1 here as well.

  8. tentrillion commented on Sep 3, 2015

    @tentrillion

    Also +1 here.

  9. lzkelley commented on Oct 19, 2015

    @lzkelley
    Contributor

    +1

  10. added a commit that references this issue on Apr 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions