【问题标题】:Find indices of 2D numpy arrays that meet a condition查找满足条件的 2D numpy 数组的索引
【发布时间】:2019-10-07 23:46:48
【问题描述】:

我有一个大型 2D numpy 数组,并希望找到其中满足条件的 1D 数组的索引:例如,至少有一个大于给定阈值 x 的值。

我已经可以通过以下方式做到这一点,但有没有更短、更有效的方式来做到这一点?

import numpy

a = numpy.array([[1,2,3,4,5], [1,2,3,4,20], [1,2,2,4,5]])

indices = []
i = 0
x = 10
for item in a:
    if any(j > x for j in item):
        indices.append(i)
    i += 1

print(indices) # gives [1]

【问题讨论】:

  • 更简单的索引检索案例1, 2, 3

标签: python arrays numpy matrix


【解决方案1】:

你可以使用 numpy 的内置布尔运算:

import numpy as np
a = np.array([[1,2,3,4,5], [1,2,3,4,20], [1,2,2,4,5]])

indices = np.argwhere(np.any(a > 10, axis=1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2013-11-15
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多