【问题标题】:How to compare one row of a numpy array to all the other rows如何将numpy数组的一行与所有其他行进行比较
【发布时间】:2021-01-05 13:05:32
【问题描述】:

我有一个带有一些坐标的 numpy 数组(xyz):

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

我想将此数组的每一行与下一行进行比较。然后,如果满足我的条件,我想打印满足条件的行数。我尝试了以下方法,但它只是将一行与下一行进行比较,而不是所有行:

for ind, val in enumerate (coord):
    if coord[ind][1] == coord[ind+1][1] and coord[ind+1][0]-coord[ind][1] < 1.2 * threshold:
        print (ind+13, ind+1+14)

我想从第一行开始,然后检查所有以下行。然后我想用下面的所有行来检查第二行,依此类推。在我的情况下,我想说如果当前行与下一行具有相同的y 值(coord[:,1])并且它们的x 距离(coord[ind+1][0]-coord[ind][1])不超过阈值,请打印索引这两对(我的代码称它们为ind+13ind+1+13 这是不正确的,因为我想将 13 添加到检测到的对的索引中)。最后我想打印这样一个结果:

13, 16
14, 17
16, 18
17, 19
18, 20

感谢任何帮助和贡献。

【问题讨论】:

    标签: python numpy enumerate


    【解决方案1】:

    使用 NumPy 数组时,使用broadcasting 方法通常比使用 Python 循环更有效。这是使用广播的问题的解决方案,并产生所需索引的数组:

    # Compute all indices that meet the conditions
    i, j = np.where(
        (coord[:, 1] == coord[:, np.newaxis, 1]) &
        (abs(coord[:, 0] - coord[:, np.newaxis, 0]) < 1.2 * threshold)
    )
    
    # Restrict to where i is before j
    i, j = i[i < j], j[i < j]
    
    # Combine and print the indices, with 13 added
    print(np.vstack([i, j]).T + 13)
    # [[13 16]
    #  [14 17]
    #  [16 18]
    #  [17 19]
    #  [18 20]]
    

    【讨论】:

      【解决方案2】:

      我认为你想要的是第二次循环,通过你当前的价值观背后的价值观:

      for ind, val in enumerate (coord):
          if ind < len(coord): 
              for ind1, val1 in enumerate (coord[ind+1:]):
                  if val[1] == val1[1] and (abs((val[0] - val1[0])) < (1.2 * threshold)):
                      print (ind+13, ind+ind1+14)
      

      【讨论】:

      • 亲爱的@KaRaOkEy,我非常感谢您的解决方案。但这并没有给我正确的答案。当我尝试时,它给了我 12 双,但我预计只有五双。对也不正确。
      • 在这种情况下,我认为您的问题不够具体。我编辑了我的答案;)如果我现在理解正确,你想要绝对差异(坐标)。如果没有,请随时再次发表评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多