R 的 which() 和 which.min() 在 Python 中等价

新手上路,请多包涵

我在 这里 阅读了类似的主题。我认为问题不同或至少 .index() 无法解决我的问题。

这是 R 中的一个简单代码及其答案:

 x <- c(1:4, 0:5, 11)
x
#[1]  1  2  3  4  0  1  2  3  4  5 11
which(x==2)
# [1] 2 7
min(which(x==2))
# [1] 2
which.min(x)
#[1] 5

它只是返回满足条件的项目的索引。

如果 x 是 Python 的输入,我如何获得满足条件的元素的 x==2 以及数组中最小的元素 which.min .

 x = [1,2,3,4,0,1,2,3,4,11]
x=np.array(x)
x[x>2].index()
##'numpy.ndarray' object has no attribute 'index'

原文由 Hadij 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 636
2 个回答

Numpy 确实有它的内置函数

x = [1,2,3,4,0,1,2,3,4,11]
x=np.array(x)
np.where(x == 2)
np.min(np.where(x==2))
np.argmin(x)

np.where(x == 2)
Out[9]: (array([1, 6], dtype=int64),)

np.min(np.where(x==2))
Out[10]: 1

np.argmin(x)
Out[11]: 4

原文由 erocoar 发布,翻译遵循 CC BY-SA 3.0 许可协议

一个简单的循环会做:

 res = []
x = [1,2,3,4,0,1,2,3,4,11]
for i in range(len(x)):
    if check_condition(x[i]):
        res.append(i)

一个有理解力的班轮:

 res = [i for i, v in enumerate(x) if check_condition(v)]

这里有一个 活生生的例子

原文由 Netwave 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏