python r indices which

Python equivalente de lo que() en R



indices which (3)

Estoy intentando tomar la siguiente instrucción R y convertirla a Python usando NumPy:

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

¿Hay un Python equivalente al cual ()? Aquí, x es la fila en la matriz tmp , y k corresponde al número de columnas en otra matriz.

Anteriormente, probé el siguiente código de Python y recibí un error de valor (los operandos no se podían transmitir junto con las formas):

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


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

Para obtener el índice de todos los elementos coincidentes, puede usar un bucle y pasar un índice de inicio:

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


El siguiente código de Python responde a mi pregunta:

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

Aquí tmp es una matriz 2d, y k es una variable que se estableció para la comparación de columnas.

Gracias a Doboy por inspirarme con la respuesta.


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