3

I'm looking for something similar to list.index(value) that works for numpy arrays. I think that numpy.where might do the trick, but I don't understand how it works, exactly. Could someone please explain

a) what this means

and b) whether or not it works like list.index(value) but with numpy arrays.

This is the article from the documentation:

numpy.where(condition[, x, y])

Return elements, either from x or y, depending on condition.
If only condition is given, return condition.nonzero().

Parameters: condition : array_like, bool

When True, yield x, otherwise yield y.

x, y : array_like, optional

Values from which to choose. x and y need to have the same shape as condition. Returns: out : ndarray or tuple of ndarrays

If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere. If only condition is given, return the tuple condition.nonzero(), the indices where condition is True. See also nonzero, choose

Notes If x and y are given and input arrays are 1-D, where is equivalent to: [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]

evtoh
  • 444
  • 3
  • 10
  • 21

1 Answers1

3

What it means?:

The numpy.where function takes a condition as an argument and returns the indices where that condition is true

Is it like list.index?:

It is close in that it returns the indices of the array where the condition is met, while list.index takes a value as the argument, this can be achieved with numpy.where by passing array == value as the condition.

Example:

Using the array

a = numpy.array([[1,2,3],
                 [4,5,6],
                 [7,8,9]])

and calling numpy.where(a == 4) returns (array([1]), array([0]))

calling numpy.where(a >= 4) returns (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])), two arrays of Y and X coordinates (respectively) where the condition is true.

njoosse
  • 549
  • 3
  • 8