开发者社区> 问答> 正文

如何使用欧几里得距离访问最相似的行上的特定项目?

我有一个数组的L列表:

L = ( array1,
      array2,
      array3,
      array4... )

此列表是从Pandas数据框开始创建的,因此,旧数据框的每一行现在都是列表内的数组。

使用欧几里得距离,我想要:

  1. Iterate through all the arrays
  2. Select only arrays in which the *2nd item* is included between ` 10 ` and ` 100 `
  3. Given an array ` arr1 ` , select the most similar one (let's say ` arr4 ` )
  4. Replace the *2nd* item in ` arr4 ` with *2nd* item in ` arr1 `

可视化它:

  1. Iterate through all the arrays

     L = ([87, 30,  45,  99],
     [11,  21,  31,  41],
     [560, 47,  85,  328],
     [167, 32,  98,  379] )
    
  2. Select only arrays in which the 2nd item is included between ` 10 ` and ` 100 `

    L = ([87,  30,  45,  99],
     [11,  21,  31,  41],
     [560, 47,  85,  328],
     [85,  33,  43,  97] )
    
  3. Given an array ` arr1 ` , select the most similar one (let's say ` arr4 ` )

    array 1 = ( [87, 30,  45,  99] )
    

    array 4 = ( [85, 32, 43, 97] )

现在让我们呼吁简单:

  • P * = 30(数组1,第二元素)

  • X * = 32(数组4,第二个元素)

    1. Replace the *2nd* item in ` arr4 ` (P) inside ` arr1 ` 2nd position (X)

      array 1 = ([87, 32, 45, 99])

许多人感谢并前进可能有用的任何提示!

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 10:08:23 318 0
1 条回答
写回答
取消 提交回答
  • import numpy as np
    
    L = np.array([
      [87, 30,  45,  99],
      [11,  21,  31,  41],
      [560, 47,  85,  328],
      [167, 32,  98,  379]
    ])
    

    对于第2点,您可以使用np.where,它返回一个condition.nonzero()数组,该数组指示condition为* True *的位置。然后,您可以将该数组作为索引。

    result = L[np.where((L[:,1]>10)&(L[:,1]<100))]
    

    对于给定的数组,例如arr1,我们可以使用以下方法(我不知道它是否是最好的,但是它可以工作)。

    L2 = np.array([
      [87,  30,  45,  99],
      [11,  21,  31,  41],
      [560, 47,  85,  328],
      [85,  33,  43,  97]
    ])
    
    def dist(a):
      return np.linalg.norm(L2[0]-a)
    
    distances = np.apply_along_axis(dist, 1, L2)
    index = np.ma.MaskedArray(result, result==0).argmin() #remove first element which dist is min (0)
    print(L2[index])
    

    回答来源:stackoverflow

    2020-03-24 10:08:31
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
重新定义计算的边界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载