在另一个数组中按行搜索一个数组的元素-Python / NumPy

时间:2019-12-28 08:19:22

标签: python numpy

例如,我有一个唯一元素矩阵,

a=[
    [1,2,3,4],
    [7,5,8,6]
]

和另一个唯一的填充有元素的矩阵,出现在第一个矩阵中。

b=[
    [4,1],
    [5,6]
]

我希望得到的结果

[
    [3,0],
    [1,3]
].

也就是说,我要查找b的每行元素,它们等于同一行中a的某些元素,并返回a中这些元素的索引。 我怎样才能做到这一点?谢谢。

3 个答案:

答案 0 :(得分:2)

这是一种矢量化方法-

<div id="someEl">You don't see me</div>

样品运行-

# https://stackoverflow.com/a/40588862/ @Divakar
def searchsorted2d(a,b):
    m,n = a.shape
    max_num = np.maximum(a.max() - a.min(), b.max() - b.min()) + 1
    r = max_num*np.arange(a.shape[0])[:,None]
    p = np.searchsorted( (a+r).ravel(), (b+r).ravel() ).reshape(m,-1)
    return p - n*(np.arange(m)[:,None])

def search_indices(a, b):
    sidx = a.argsort(1)
    a_s = np.take_along_axis(a,sidx,axis=1)
    return np.take_along_axis(sidx,searchsorted2d(a_s,b),axis=1)

另一个向量化了一个利用broadcasting-

In [54]: a
Out[54]: 
array([[1, 2, 3, 4],
       [7, 5, 8, 6]])

In [55]: b
Out[55]: 
array([[4, 1],
       [5, 6]])

In [56]: search_indices(a, b)
Out[56]: 
array([[3, 0],
       [1, 3]])

答案 1 :(得分:0)

如果您不介意使用循环,这是使用np.where的快速解决方案:

import numpy as np

a=[[1,2,3,4],
   [7,5,8,6]]
b=[[4,1],
   [5,6]]

a = np.array(a)
b = np.array(b)
c = np.zeros_like(b)

for i in range(c.shape[0]):
    for j in range(c.shape[1]):
        _, pos = np.where(a==b[i,j])
        c[i,j] = pos

print(c.tolist())

答案 2 :(得分:0)

您可以这样做:

np.split(pd.DataFrame(a).where(pd.DataFrame(np.isin(a,b))).T.sort_values(by=[0,1])[::-1].unstack().dropna().reset_index().iloc[:,1].to_numpy(),len(a))                               

# [array([3, 0]), array([1, 3])]