Skip to main content
 首页 » 编程设计

Python之Python 中来自 R 的函数 "which"

2025年05月04日58pengyingh

我正在寻找 Python 中 R“which”中的等效函数。有人知道如何适应它吗?

例如:

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

请您参考如下方法:

您可以使用 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) 

while np.where 返回 X 和 Y 的元组,其中某些条件匹配:

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