1

I have my np array list with tuples like np.array[(0,1), (2,5),...]

Now I want to search for the index of a certain value. But I just know the left side of the tuple. The approach I have found to get the index of a value (if you have both) is the following:

x = np.array(list(map(lambda x: x== (2, 5), groups)))
print(np.where(x))

But how can I search if I only know x==(2,) but not the right number?

2 Answers 2

1

As stated in https://numpy.org/doc/stable/reference/generated/numpy.where.html#numpy.where, it is preferred to use np.nonzero directly. I would also recommend reading up on NumPy's use of boolean masking. The answer to your question, is this:

import numpy as np
i = 0  # index of number we're looking for
j = 2  # number we're looking for


mask = x[:,i] == j  # Generate a binary/boolean mask for this array and this comparison
indices = np.nonzero(mask)  # Find indices where x==(2,_)
print(indices)

In NumPy it's generally preferred to avoid loops like the one you use above. Instead, you should use vectorized operations. So, try to avoid the list(map()) construction you used here.

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

Comments

1

It might just be easier that you think.

Example:

# Create a sample array.
a = np.array([(0, 1), (2, 5), (3, 2), (4, 6)])

# Use slicing to return all rows, there column 0 equals 2.
(a[:,0] == 2).argmax()
>>> 1

# Test the returned index against the array to verify.
a[1]
>>> array([2, 5])

Another way to look at the array is shown below, and will help put the concept of rows/columns into perspective for the mentioned array:

>>> a

array([[0, 1],
       [2, 5],
       [3, 2],
       [4, 6]])

Comments

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.