Python equivalent of which() in R

Bokononisms picture Bokononisms · Aug 31, 2012 · Viewed 21.4k times · Source

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

Answer

Vishal Mishra picture Vishal Mishra · Oct 17, 2016
    >>> 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]