Home > Back-end >  How to extract numpy array stored in tuple?
How to extract numpy array stored in tuple?

Time:07-19

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?

CodePudding user response:

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

CodePudding user response:

Just use this:

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

Outputs 2

CodePudding user response:

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
  • Related