Skip to main content
 首页 » 编程设计

python之使用 numpy.argpartition 忽略 NaN

2024年11月24日14bjzhanghao

我有一个包含大约 4900 万个项目 (7000*7000) 的大型数组,我需要在其中找到最大的 N 个项目及其索引(忽略所有 NaN)。我无法事先删除这些 NaN,因为我需要第一个数组中最大的 N 项的索引值来从另一个数组中提取数据,该数组在与第一个数组相比具有不同索引的 NaN。我试过了

np.argpartition(first_array, -N)[-N:]

这对于没有 NaN 的数组非常有效,但如果有 NaN,则 nan 将成为最大的项目,因为它在 python 中被视为无穷大。

x = np.array([np.nan, 2, -1, 2, -4, -8, -9, 6, -3]).reshape(3, 3) 
y = np.argpartition(x.ravel() , -3)[-3:] 
z = x.ravel()[y] 
# this is the result I am getting  === [2, 6, nan] 
# but I need this ==== [2, 2, 6] 

请您参考如下方法:

使用 NaN 的计数来抵消并计算索引和提取值 -

In [200]: N = 3 
 
In [201]: c = np.isnan(x).sum() 
 
In [204]: idx = np.argpartition(x.ravel() , -N-c)[-N-c:-c] 
 
In [207]: val = x.flat[idx] 
 
In [208]: idx,val 
Out[208]: (array([1, 3, 7]), array([2., 2., 6.]))