【问题标题】:Numpy element-wise comparison using a different array for values使用不同的数组进行 Numpy 逐元素比较
【发布时间】:2020-11-21 06:34:31
【问题描述】:

这可能是一个简单的问题,但我被这个问题困住了,我发现的解决方案效率不高(我认为)。

假设我有两个 numpy 数组,一个包含每个位置的索引,第二个包含有效索引:

import numpy as np

x = np.array([0, 1, 2, 1, 3, 2])

indices = np.array([True, True, False, False])

我想获得一个布尔数组,指示第一个数组中的值与第二个数组中包含的值相同的位置。我提到的效率不高的解决方案是:

indices2 = np.where(indices)[0]

y1 = (x == indices2[0]) | (x == indices2[1])

y2 = np.zeros_like(x, dtype=bool)
for i in indices2:
    y2 = (x == i) | y2

np.all(y2 == y1) 

是的

y1 

数组([真、真、假、真、假、假])

那么,有没有更高效、更 numpy 风格的方法来实现这一点(例如,没有 for 循环)?

编辑:
更正了一些错误并将示例替换为 cmets 中提到的较小的示例。

【问题讨论】:

  • (1) 为了演示,请将x 缩小很多,比如5个值,这样容易理解。 (2) 为什么这不仅仅是x1 == x2? (3) 如果您的问题中的第一个数组是x,那么第二个数组是什么?是indices吗?因为x 中的值都不在indices 中,因为它们具有不同的类型。
  • indices[x] 呢?
  • 那么你是问如何使用x 来索引indices
  • @Roberto:嗯,这似乎行得通。我期待一个简洁的答案,但这比所有都好!

标签: python numpy


【解决方案1】:

您似乎想用x 中的索引来索引indices。尝试:

indices[x]

【讨论】:

    【解决方案2】:

    这是我解决问题的方法:

    import numpy as np
    
    x = np.array([0, 0, 2, 0, 3, 0, 1, 0, 0, 0, 0, 0, 3, 0, 3, 1, 0, 0, 0, 0, 0, 0,
           0, 0, 1, 0, 0, 0, 3, 0, 3, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0,
           0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
           0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 2, 0, 1, 0, 0, 0, 2, 0, 2, 2, 0, 2,
           0, 0, 2, 2, 0, 2, 2, 0, 2, 0, 0, 2])
    
    indices = [True, True, False, False]
    
    x2 = np.copy(x)
    x2 = np.array(x2,dtype='object')
    
    for i,val in enumerate(x):
        x2[i] = indices[val]
        
    print(x2)
    

    如果您以后不需要x,那么您可以只使用x = np.array(x,dtype='object'),而不是使用单独的变量x2


    输出:

    [True True False True False True True True True True True True False True
     False True True True True True True True True True True True True True
     False True False True True True True True False True True True True True
     True True True True True True True True True True True True True True
     True True True True True True True True True True True True True True
     True True True False True True False True True True True True False True
     False False True False True True False False True False False True False
     True True False]
    

    编辑:

    在测试 5000 次时,上述代码平均花费了 0.12967189999994844 秒,而 Roberto 的代码平均花费了 0.05755720000001929 秒。所以你应该更喜欢他的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-24
      • 2016-05-16
      • 1970-01-01
      • 2018-09-29
      • 2019-11-11
      • 1970-01-01
      • 2013-05-09
      相关资源
      最近更新 更多