Skip to main content
 首页 » 编程设计

Python:根据某些列过滤 numpy 值

2024年12月31日7soundcode

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

假设我在 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”矩阵可能超过 100000 行。

是否有更有效的方法来执行此功能?

请您参考如下方法:

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

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

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