1

I want to find elements of a 1d array in rows of a 2d array.

Example

In [1]: import numpy as np

In [2]: a = np.array([7,7,7])

In [3]: a
Out[3]: array([7, 7, 7])

In [4]: b = np.arange(15).reshape(3,5)

In [5]: b
Out[5]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

Rows 0 and 2 of b do not have a match for the corresponding element of a, but row 1 has a match in position 2. Expected output:

array([nan, 2, nan])

If there are multiple matches in a given row, the position of the first match should be used.

I can grind out a solution using normal python loops but I'm interested in a way to vectorize this.

3
  • What if there are multiple matches in a row? What do you want the result to be? Commented May 25, 2017 at 1:44
  • What's the expected output if row 1 in b has multiple occurrences of 7? Commented May 25, 2017 at 1:44
  • It can return the first match. Updated the question. Commented May 25, 2017 at 1:53

1 Answer 1

2

Compare b and a element wise, and then find the first True value index for each row, or set to nan if all False.

np.where(np.sum(b==a[:,None],1) > 0, np.argmax(b==a[:,None],1), np.nan)
Out[22]: array([ nan,   2.,  nan])
Sign up to request clarification or add additional context in comments.

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.