1

I have an array that is as follows:

[[0, 0, 0, 1],
 [1, 0, 0, 0],
 [0, 1, 0, 0],
 [0, 0, 1, 0],
 [0, 0, 0, 1],
 etc

I'd like to determine the sum of index [3] in each line. For example, here I'd like to get 2 as a result.

I'm trying

np.sum(np.count_nonzero(array[:][3], axis=1))

but I get an out of bounds error. Any ideas?

pepe
  • 9,799
  • 25
  • 110
  • 188

2 Answers2

4

You need to index the array as a[:, 3] (the third column of all rows), then you can do:

# if the array contains only 0 and 1
a[:,3].sum()
# 2

# if the array can have other values besides 0 and 1
np.count_nonzero(a[:,3])
# 2

Here is more info about numpy indexing.

Psidom
  • 209,562
  • 33
  • 339
  • 356
1

Simply get the list as n[:,3] then sum normally since summing zero does nothing:

>>> numpy.sum(n[:,3])
2
Community
  • 1
  • 1
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76