Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R's which() and which.min() Equivalent in Python

Tags:

python

r

numpy

I read the similar topic here. I think the question is different or at least .index() could not solve my problem.

This is a simple code in R and its answer:

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 

Which simply returns the index of the item which meets the condition.

If x be the input for Python, how can I get the indeces for the elements which meet criteria x==2 and the one which is the smallest in the array 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' 
like image 748
Hadij Avatar asked Jan 30 '18 10:01

Hadij


People also ask

What is \r is doing in the Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

What is equivalent command in Python?

Use the shutil. which() Function to Emulate the which Command in Python. We can emulate this command in Python using the shutil. which() function.

Is Na in R equivalent in Python?

What is python's equivalent of R's NA? To be more specific: R has NaN, NA, NULL, Inf and -Inf. NA is generally used when there is missing data.


1 Answers

Numpy does have built-in functions for it

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 
like image 135
erocoar Avatar answered Sep 20 '22 03:09

erocoar