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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

is the axis correct? I still get the out of bounds error
If you extract values with a[:,3], you get a 1d array, then you don't need the axis parameter.
1

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

>>> numpy.sum(n[:,3])
2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.