Select positions of a vector. Python

2

I am translating from R studio to Python and I have a doubt, in R I am using which what what it does is give the indexes TRUE of a logical object, allowing the indexes of the array. For example, if I have a vector v=(0,5,6,7,81,4,8,2,4,1,3) and I put which(v>=6) and returns this result 3 4 5 7 returns the positions greater than 6,

How would this be done in Python?

    
asked by Fran Ahedo Guerrero 01.08.2017 в 18:41
source

3 answers

3

Here is a simple example of how you could recover these values

a = [1,2,3,4,5]
b = [x>3 for x in a] #[False,False,False,True,True]
c = [i for i, x in enumerate(a) if x<=3] #Recuperas los indices que cumplen la condicion

In case it seems to me that c would be what would serve you, this with implementation of standard code, but libraries like numpy could facilitate this and other tasks

With numpy the recovery of the indices could be done like this:

import numpy as np
a = np.array([1,2,3,4,5])
c = np.where(a>3) #Devuelve un arreglo de numpy con los indices que cumplen la condicion
#Puedes acceder a los datos asi:
c[0][0]#[fila][columna]

For this example it may seem more elaborate, but when working with more data numpy is more efficient and has cleaner syntax.

    
answered by 01.08.2017 / 19:07
source
3

The closest translation is the following:

lista = [0,5,6,7,81,4,8,2,4,1,3]
print([i for i, e in enumerate(lista,1)  if e >= 6])
[3, 4, 5, 7]

that is, we generate a new list by tracing the original listing each item from 1 (In R the vectors start with index 1, in Python with 0) and we are left with the index sun if the value e is > = 6.

    
answered by 01.08.2017 в 19:15
2

Here are some more options:

# Datos
v=(0,5,6,7,81,4,8,2,4,1,3)

# Numpy, forma breve.
np.array(np.array(v)>5).nonzero()
Out[1]: (array([2, 3, 4, 6], dtype=int64),)

# Compresion de listas
[idx for idx in range(len(v)) if v[idx] > 5]
Out[2]: [2, 3, 4, 6]

# map y filtrado
list(map(v.index, filter(lambda x : x>5, v)))
Out[3]: [2, 3, 4, 6]

If you plan to use it more often, a very useful function:

def indices(list, filtr=lambda x: bool(x)):
    return [i for i,x in enumerate(list) if filtr(x)]

print(indices(v, lambda x: x>5))
Out[4]:[2, 3, 4, 6]
    
answered by 02.08.2017 в 10:08