简体   繁体   中英

Numpy find 1d array elements in 2d array rows

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.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM