4

I have a numpy array and I want to return the count of true values for each row.

for example I have a numpy array:

[[False False False ..., False False False]
 [False False False ..., False False False]
 [False False False ..., False  True False]
 ..., 
 [False False False ..., False False False]
 [ True False  True ...,  True  True  True]
 [False False False ..., False False False]]

and the return value should be like:

[10
 15
 8
 ..., 
 11
 10
 12]

This question asks about how to do it for the whole array but how do I do it for each row?

cs95
  • 379,657
  • 97
  • 704
  • 746
aroma
  • 1,370
  • 1
  • 15
  • 30
  • 2
    Did you check the docs for either of the solutions suggested in that answer? Both [`numpy.sum`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html) and [`numpy.count_nonzero`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonzero.html) take an optional `axis` argument. – user2357112 Aug 05 '17 at 07:17
  • I don't know about numpy with with plain python, something like: `r = [len(filter(None, a)) for a in source]` with `source` being your original list – shevron Aug 05 '17 at 07:19
  • @user2357112 thanks I found it out. – aroma Aug 05 '17 at 07:24
  • Added a [community wiki answer](https://stackoverflow.com/a/45519545/4909087) to the linked question, since that generates a lot of traffic. – cs95 Aug 05 '17 at 07:47

1 Answers1

8

We can simply do this by providing an axis argument to the sum function:

arr.sum(axis=1)
cs95
  • 379,657
  • 97
  • 704
  • 746
aroma
  • 1,370
  • 1
  • 15
  • 30