【问题标题】:How to find the set of indices where two vectors have equal elements in Python如何在Python中找到两个向量具有相同元素的索引集
【发布时间】:2015-06-04 08:34:42
【问题描述】:

我在 Python 中有两个向量:Predictions 和 Labels。我想做的是找出这两个向量具有相同元素的索引集。例如,假设向量是:

Predictions = [4, 2, 5, 8, 3, 4, 2, 2]

     Labels = [4, 3, 4, 8, 2, 2, 1, 2]

因此两个向量具有相同元素的索引集将是:

Indices = [0, 3, 7]

我怎样才能在 Python 中得到这个?不使用 for 循环等。在numpy 中是否有内置函数?

感谢您的帮助!

【问题讨论】:

    标签: python numpy vector


    【解决方案1】:

    这是使用 numpy 的一种方法:

    np.where(np.equal(Predictions, Labels))
    

    相当于:

    np.equal(Predictions, Labels).nonzero()
    

    虽然它会返回一个元素元组,所以要获取实际的数组,请添加[0],如下所示:

    np.equal(Predictions, Labels).nonzero()[0]
    

    【讨论】:

    • 感谢您的帮助 =) 感激不尽
    【解决方案2】:

    对于两个数组a, b :

    a = np.array([1, 2, 3, 4, 5])
    b = np.array([1, 3, 2, 4, 5])
    

    np.equal(a,b) 与a==b 具有相同的输出(我认为这首先更容易理解):

    > array([ True, False, False,  True,  True], dtype=bool)
    

    元素被逐个检查,然后创建一个布尔数组。

    np.where() 在数组上逐元素检查一些条件:

    np.where(a > 2)
    > (array([2, 3, 4]),)
    

    所以结合np.where 和np.equal 是你想要的:

    np.where(np.equal(a,b))
    > (array([0, 3, 4]),)
    

    编辑:没关系,只是看到我太慢了^^

    【讨论】:

    • 谢谢,感谢您的帮助:)
    猜你喜欢
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    相关资源
    最近更新 更多