Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of which() in R

Tags:

python

r

indices

I am trying to take the following R statement and convert it to Python using NumPy:

1 + apply(tmp,1,function(x) length(which(x[1:k] < x[k+1]))) 

Is there a Python equivalent to which()? Here, x is row in matrix tmp, and k corresponds to the number of columns in another matrix.

Previously, I tried the following Python code, and received a Value Error (operands could not be broadcast together with shapes):

for row in tmp:         print np.where(tmp[tmp[:,range(k)] < tmp[:,k]]) 
like image 580
Bokononisms Avatar asked Aug 30 '12 23:08

Bokononisms


People also ask

Which Python function is like R?

The Apply Function in Python The pandas package for Python also has a function called apply, which is equivalent to its R counterpart; the following code illustrates how to use it. In pandas, axis=0 specifies columns and axis=1 specifies rows.

Is there a Dplyr for Python?

Dplython. Package dplython is dplyr for Python users. It provide infinite functionality for data preprocessing.

Is Na in R to 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

     >>> which = lambda lst:list(np.where(lst)[0])      Example:     >>> lst = map(lambda x:x<5, range(10))     >>> lst     [True, True, True, True, True, False, False, False, False, False]     >>> which(lst)     [0, 1, 2, 3, 4] 
like image 165
Vishal Mishra Avatar answered Sep 20 '22 23:09

Vishal Mishra