2

Let's consider very easy example:

import numpy as np
a = np.array([0, 1, 2])
print(np.where(a < -1))
(array([], dtype=int64),)
print(np.where(a < 2))
(array([0, 1]),) 

I'm wondering if its possible to extract length of those arrays, i.e. I want to know that the first array is empty, and the second is not. Usually it can be easily done with len function, however now numpy array is stored in tuple. Do you know how it can be done?

1
  • 6
    len(np.where(a < 2)[0])? Commented Jul 19, 2022 at 11:13

3 Answers 3

2

Just use this:

import numpy as np
a = np.array([0, 1, 2])
x = np.where(a < 2)[0]
print(len(x))

Outputs 2

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

Comments

1

To find the number of values in the array satisfying the predicate, you can skip np.where and use np.count_nonzero instead:

a = np.array([0, 1, 2])
print(np.count_nonzero(a < -1))
>>> 0
print(np.count_nonzero(a < 2))
>>> 2

If you need to know whether there are any values in a that satisfy the predicate, but not how many there are, a cleaner way of doing so is with np.any:

a = np.array([0, 1, 2])
print(np.any(a < -1))
>>> False
print(np.any(a < 2))
>>> True

Comments

1

np.where takes 3 arguments: condition, x, y where last two are arrays and are optional. When provided the funciton returns element from x for indices where condition is True, and y otherwise. When only condition is provided it acts like np.asarray(condition).nonzero() and returns a tuple, as in your case. For more details see Note at np.where.

Alternatively, because you need only length of sublist where condition is True, you can simply use np.sum(condition):

a = np.array([0, 1, 2])
print(np.sum(a < -1))
>>> 0
print(np.sum(a < 2))
>>> 2

1 Comment

he's using the single argument version of np.where

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.