How to count the number of true elements in a NumPy bool array

后端 未结 4 937
迷失自我
迷失自我 2020-12-12 13:50

I have a NumPy array \'boolarr\' of boolean type. I want to count the number of elements whose values are True. Is there a NumPy or Python routine dedicated for

4条回答
  •  无人及你
    2020-12-12 13:59

    You have multiple options. Two options are the following.

    numpy.sum(boolarr)
    numpy.count_nonzero(boolarr)
    

    Here's an example:

    >>> import numpy as np
    >>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
    >>> boolarr
    array([[False, False,  True],
           [ True, False,  True],
           [ True, False,  True]], dtype=bool)
    
    >>> np.sum(boolarr)
    5
    

    Of course, that is a bool-specific answer. More generally, you can use numpy.count_nonzero.

    >>> np.count_nonzero(boolarr)
    5
    

提交回复
热议问题