在R中对应的Python。

时间:2022-04-27 21:24:07

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

我正在尝试使用下面的R语句并使用NumPy将其转换为Python:

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.

是否有一个Python等价于which()?这里,x是矩阵tmp中的行,k对应于另一个矩阵中的列数。

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

之前尝试过以下Python代码,收到一个值错误(操作数不能与图形一起广播):

for row in tmp:
        print np.where(tmp[tmp[:,range(k)] < tmp[:,k]])

3 个解决方案

#1


4  

The Python code below answers my question:

下面的Python代码回答了我的问题:

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.

这里tmp是一个2d数组,k是一个变量,它被设置为列比较。

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

感谢https://*.com/users/601095/doboy给我答案的启发!

#2


3  

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


1  

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

从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:

要获取所有匹配项的索引,可以使用循环,并传入一个start索引:

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

#1


4  

The Python code below answers my question:

下面的Python代码回答了我的问题:

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.

这里tmp是一个2d数组,k是一个变量,它被设置为列比较。

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

感谢https://*.com/users/601095/doboy给我答案的启发!

#2


3  

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


1  

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

从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:

要获取所有匹配项的索引,可以使用循环,并传入一个start索引:

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