What is the most efficient way to check if a value exists in a NumPy array? What is the most efficient way to check if a value exists in a NumPy array? numpy numpy

What is the most efficient way to check if a value exists in a NumPy array?


How about

if value in my_array[:, col_num]:    do_whatever

Edit: I think __contains__ is implemented in such a way that this is the same as @detly's version


The most obvious to me would be:

np.any(my_array[:, 0] == value)


To check multiple values, you can use numpy.in1d(), which is an element-wise function version of the python keyword in. If your data is sorted, you can use numpy.searchsorted():

import numpy as npdata = np.array([1,4,5,5,6,8,8,9])values = [2,3,4,6,7]print np.in1d(values, data)index = np.searchsorted(data, values)print data[index] == values