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

后端 未结 4 933
迷失自我
迷失自我 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:57
    boolarr.sum(axis=1 or axis=0)
    

    axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so

    boolarr[[true,true,true],[false,false,true]]
    print(boolarr.sum(axis=1))
    

    will be (3,1)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-12 14:01

    That question solved a quite similar question for me and I thought I should share :

    In raw python you can use sum() to count True values in a list :

    >>> sum([True,True,True,False,False])
    3
    

    But this won't work :

    >>> sum([[False, False, True], [True, False, True]])
    TypeError...
    
    0 讨论(0)
  • 2020-12-12 14:08

    In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

    import numpy as np
    result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
    target = np.random.randint(3,size=(5,2)) # 5x2 random integer array
    
    res = np.equal(result,target)
    print result
    print target
    print np.sum(res[:,0])
    print np.sum(res[:,1])
    

    which can be extended to D dimensions.

    The results are:

    Prediction:

    [[1 2]
     [2 0]
     [2 0]
     [1 2]
     [1 2]]
    

    Target:

    [[0 1]
     [1 0]
     [2 0]
     [0 0]
     [2 1]]
    

    Count of correct prediction for D=1: 1

    Count of correct prediction for D=2: 2

    0 讨论(0)
提交回复
热议问题