【问题标题】:Python: Filtering numpy values based on certain columnsPython:根据某些列过滤 numpy 值
【发布时间】:2018-12-20 13:58:59
【问题描述】:

我正在尝试创建一种方法来评估大约一周后到期的项目的坐标。

假设我在 3D 笛卡尔坐标系中工作 - 其值存储为 numpy 数组中的行。在给定相应的预定“x”(n[i,0]) 和“y”(n[i,1]) 值的情况下,我正在尝试读取“z”(n[i,2]) 值是否存在。

在分配的值是标量的情况下,我很乐意认为:

# Given that n is some numpy array
x, y = 2,3 
out = []
for i in range(0,n.shape[0]):
 if n[i, 0] == x and n[i,1] == y:
  out.append(n[i,2])

然而,悲伤的地方在于必须检查另一个 numpy 数组中的值是否在原始 numpy 数组“n”中。

# Given that n is the numpy array that is to be searched
# Given that x contains the 'search elements'
out = []
for i in range(0,n.shape[0]):
 for j in range(0, x.shape[0]):
  if n[i, 0] == x[j,0] and n[i,1] == x[j,1]:
   out.append(n[i,2])

这样做的问题是我的应用程序中的“n”矩阵很可能超过 100 000 行。

有没有更有效的方法来执行这个功能?

【问题讨论】:

  • 您希望您的阵列x 达到什么数量级?它的大小与n 相似,还是更小?
  • n中的点可以在x中出现多次吗? (即,是否应该在注册事件后取消内部循环,或者尽可能多地取消)
  • n 的形状为 (9050, 3) 而 x 的形状为 (103, 2) 是的,x 中的点可以多次出现在 n 中我还考虑过可能将 x 数组拆分为 2列数组并使用第一列迭代 n 数组 - 然后通过第二列迭代第一次迭代的输出
  • 我不太明白你在这里的建议,特别是你所说的拆分是什么意思。似乎输出的一般顺序似乎不相关,还是我弄错了?因为那样的话,您可以通过对值进行排序然后只比较这么多值(也许)来获得更好的性能。
  • 我基本上想将数组“解压缩”到它的组成列中。非常感谢您的帮助 - 发布的解决方案有效:)

标签: python numpy search filtering


【解决方案1】:

这可能比嵌套循环更有效:

out = []
for row in x:
    idx = np.equal(n[:,:2], row).all(1)
    out.extend(n[idx,2].tolist())

请注意,这假定x 的形状为(?, 2)。否则,如果它有两列以上,只需将循环体中的row 更改为row[:2]。

【讨论】:

    【解决方案2】:

    Numpythonic 解决方案没有循环。

    此解决方案适用于 x 和 y 坐标为非负数的情况。

    import numpy as np
    # Using a for x and b for n, to avoid confusion with x,y coordinates and array names
    a = np.array([[1,2],[3,4]])
    b = np.array([[1,2,10],[1,2,11],[3,4,12],[5,6,13],[3,4,14]])
    
    # Adjust the shapes by taking the z coordinate as 0 in a and take the dot product with b transposed
    a = np.insert(a,2,0,axis=1)
    dot_product = np.dot(a,b.T)
    
    # Reshape a**2 to check the dot product values corresponding to exact values in the x, y coordinates
    sum_reshaped = np.sum(a**2,axis=1).reshape(a.shape[0],1)
    
    # Match for values for indivisual elements in a. Can be used if you want z coordinates corresponding to some x, y separately
    indivisual_indices = ( dot_product == np.tile(sum_reshaped,b.shape[0]) )
    
    # Take OR of column values and take z if atleast one x,y present
    indices  = np.any(indivisual_indices, axis=0)
    print(b[:,2][indices]) # prints [10 11 12 14]
    

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      相关资源
      最近更新 更多