numpy:如何在另一个2D数组中查找2D数组的参数

在发布此问题之前,我已经搜索过该网站上的解决方案,但找不到任何解决方案。

假设我有2个numpy二维数组ab,这样:

a = np.array([[0.,1.],[0.5,1.6],[1.2,3.2],[4.,3. ],[4.7,3.5],[5.9,2.4],[7.6,8.8],[9.5,6.2]
              ])

b = np.array([[7.6,6.2],3.2]
              ])

我想获取数组b中数组a的参数。也就是说,对于b的每一行,返回其在b上的位置。 在这种情况下,预期结果如下:

args =np.array([6,3,7,2])

我已经尝试过类似的事情:

args = np.argwhere(a == b) # But the result is an empty array

感谢您的帮助。

zucker19782002 回答:numpy:如何在另一个2D数组中查找2D数组的参数

尝试一下:

temp_search = (a[:,None] == b).all(-1)
args = np.where(temp_search.any(0),temp_search.argmax(0),np.nan)
args = args[~np.isnan(args)].astype(int) 

输出:

[6 3 7 2]

问题似乎出在a==b中。而不是返回np array而是返回一个布尔值,即false

在2 numpy数组之间使用elementwise进行==比较似乎已经过了一段时间。

https://github.com/numpy/numpy/issues/6784

参考:Check common elements of two 2D numpy arrays,either row or column wise


这是处理数组中重复项的增强版本,请参见this answer以供参考。

import numpy as np
import pandas as pd

def assign_duplbl(a):
    df = pd.DataFrame(a)
    df['num'] = 1
    return df.groupby(list(range(a.shape[1]))).cumsum().values

def argwhere2d(arr,target_arr):
    # return the location of arr in the target_array

    # this is an updated version to handle duplicates
    a = np.hstack((arr,assign_duplbl(arr)))
    b = np.hstack((target_arr,assign_duplbl(target_arr)))
    temp_search = (b[:,None] == a).all(-1)
    args = np.where(temp_search.any(0),np.nan)
    args = args[~np.isnan(args)].astype(int) 
    return args
本文链接:https://www.f2er.com/3162986.html

大家都在问