Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a very large NumPy array

1 40 3 4 50 4 5 60 7 5 49 6 6 70 8 8 80 9 8 72 1 9 90 7 ....  

I want to check to see if a value exists in the 1st column of the array. I've got a bunch of homegrown ways (e.g. iterating through each row and checking), but given the size of the array I'd like to find the most efficient method.

Thanks!

like image 211
thegreatt Avatar asked Aug 17 '11 06:08

thegreatt


People also ask

How do you check if a value is present in an array in Python?

Check if List Contains Element With not in Operator. By contrast, we can use the not in operator, which is the logical opposite of the in operator. It returns True if the element is not present in a sequence. Running this code won't produce anything, since the Bird is present in our list.

Which of the following method is use to search a certain value in an NumPy array?

You can search an array for a certain value, and return the indexes that get a match. To search an array, use the where() method.

How do I find the most common value in an array in Python?

Steps to find the most frequency value in a NumPy array:Create a NumPy array. Apply bincount() method of NumPy to get the count of occurrences of each element in the array. The n, apply argmax() method to get the value having a maximum number of occurrences(frequency).

How do you check if a NumPy array is in a list Python?

The variable is_in_list indicates if there is any array within he list of numpy arrays which is equal to the array to check.


2 Answers

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

like image 137
agf Avatar answered Oct 19 '22 23:10

agf


The most obvious to me would be:

np.any(my_array[:, 0] == value) 
like image 36
detly Avatar answered Oct 19 '22 23:10

detly