Python - 在Python中实现R语言的函数"which"

3

我希望你能够帮忙将R语言中的"which"函数翻译成Python的等价函数。有没有人知道如何进行调整呢?

例如:

set_false_over <- length(datapoints[which(labels==FALSE & datapoints>=unique_values[i])])

它是什么类型的数据? - lazarus
你可以使用列表推导式...带有过滤条件。 - lazarus
1个回答

7
你可以使用numpy.where,但在你的用例中这是不必要的:
In [8]: import numpy as np

In [9]: x = np.arange(9.).reshape(3, 3)

In [10]: x
Out[10]: 
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])

In [11]: x[np.where(x>5)]
Out[11]: array([ 6.,  7.,  8.])

In [12]: x[x>5]
Out[12]: array([ 6.,  7.,  8.])
> 运算符首先返回一个 bool 矩阵:
In [16]: x>5
Out[16]: 
array([[False, False, False],
       [False, False, False],
       [ True,  True,  True]], dtype=bool)

np.where则会返回一个元组,其中包含某些条件匹配的X和Y:

In [15]: np.where(x>5)
Out[15]: (array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接