【问题标题】:Using numpy.argpartition ignoring NaNs使用 numpy.argpartition 忽略 NaN
【发布时间】:2019-05-30 12:05:17
【问题描述】:

我有一个包含大约 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]

【问题讨论】:

  • 检查np.nanargmax

标签: python python-3.x numpy sorting numpy-ndarray


【解决方案1】:

使用 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.]))

【讨论】:

    猜你喜欢
    • 2015-04-03
    • 2018-07-05
    • 2019-09-24
    • 2019-08-30
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2015-02-10
    相关资源
    最近更新 更多