Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Function "which" from R in Python

Tags:

python

function

r

I'm looking for the equivalent function in R "which" in python. Does anybody know how to adapt it?

For example:

set_false_over <- length(datapoints[which(labels==FALSE & datapoints>=unique_values[i])])
like image 546
user3886573 Avatar asked Oct 27 '25 02:10

user3886573


1 Answers

You can use numpy.where, but it's unnecessary in your use case:

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

The > op returns you a matrix of bools first:

In [16]: x>5
Out[16]: 
array([[False, False, False],
       [False, False, False],
       [ True,  True,  True]], dtype=bool)

while np.where returns you a tuple of the Xs and Ys where some condition matches:

In [15]: np.where(x>5)
Out[15]: (array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))
like image 64
zhangxaochen Avatar answered Oct 29 '25 18:10

zhangxaochen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!