【问题标题】:Obtaining indexes of changed data between two numpy arrays获取两个 numpy 数组之间更改数据的索引
【发布时间】:2011-02-22 04:29:29
【问题描述】:

我有两个 3d numpy 数组 a1 和 a2,其中 len(a1) == len(a2)a1[x, y, z] = id

我正在使用此代码来确定任何 z 层中是否有更改的数据

eq = a1 == a2
if eq.any():
    #find the indexes of the changed data

正如评论和标题所说,我需要找到更改数据的索引。 基本上我有一个与数组中的位置相对应的对象列表,我需要根据从数组中提取的 id 更新这些对象。我想尽可能快地做到这一点,因为这个列表可以变得非常大,可能超过 120,000 个条目。但是这些条目中只有大约一百个可能随时更改。因此,我想获取已更改索引的列表,以便可以调用该索引处的对象并对其进行更新。

我确实需要维护索引的三个组成部分

有没有办法在不循环列表的情况下做到这一点?也许与numpy.nonzero()

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    另外两个选项:

    np.argwhere(a1!=a2)
    np.where(a1!=a2)
    

    它们都做同样的事情,但产生不同格式的结果(一种适合索引数组,另一种更易读)

    【讨论】:

    • np.argwhere() 似乎是我正在寻找的。谢谢你。它返回一个数组数组,其索引与我需要的条件匹配。
    【解决方案2】:

    我不明白你的问题的细节(例如,你的数组的大小/形状);这个解决方案应该足够通用。无论如何,它是无循环的:

    # two 2d arrays
    x = NP.random.randint(0, 10, 20).reshape(5, 4)
    y = NP.random.randint(0, 10, 20).reshape(5, 4)
    
    ndx1, ndx2 = NP.nonzero((x - y))
    
    # all indices in which the values of x & y differ, each index is a tuple
    ndx = zip(ndx1, ndx2)  
    
    # you can also use argwhere, returns each index as a 1d array vs. tuple:
    NP.argwhere(dxy)
    
    # finally, just generating an array the same size as the diff array with e.g.,
    # '1' for each diff element and '0' for each non-diff:
    dxy = x - y
    NP.where(dxy=0, 0, 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 2019-05-26
      • 2011-01-20
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多