gpt4 book ai didi

python - 查找满足条件的 2D numpy 数组的索引

转载 作者:太空宇宙 更新时间:2023-11-04 09:29:32 29 4
gpt4 key购买 nike

我有一个大的 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]

最佳答案

您可以使用 numpy 的内置 bool 运算:

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))

关于python - 查找满足条件的 2D numpy 数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56240706/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com