Python equivalent of which() in R

孤者浪人 提交于 2019-12-18 11:19:11

问题


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

回答1:


The Python code below answers my question:

np.array([1 + np.sum(row[range(k)] < row[k]) for row in tmp])

Here tmp is a 2d array, and k is a variable which was set for column comparison.

Thanks to https://stackoverflow.com/users/601095/doboy for inspiring me with the answer!




回答2:


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



回答3:


From http://effbot.org/zone/python-list.htm:

To get the index for all matching items, you can use a loop, and pass in a start index:

i = -1
try:
    while 1:
        i = L.index(value, i+1)
        print "match at", i
except ValueError:
    pass


来源:https://stackoverflow.com/questions/12207014/python-equivalent-of-which-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!