Getting the indices of array elements corresponding to a value
I spent a couple of days looking at the indexing documentation but didn't find what I was looking for.
Consider this:
import numpy
fac=numpy.asarray(['a','a','a','b','b','c','c','c'])
f_ind = [x for x in range(len(fac)) if fac[x] == 'c']
it returns [5,6,7]
as i want. However, it seems that NumPy arrays should have a mechanism to achieve the same result in a more concise (and efficient?) Way. Boolean arrays can be part of the solution:
ba = (fac == 'c')
f_vals = fac[ba]
But that only rips off elements fac
that are equal 'c'
- not very useful.
Any suggestions on how to do this using NumPy? Or will I just be happy with what I have?
source to share
The function you are looking for is numpy where.
https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.where.html
np.where(fac=='c')
Would return a tuple containing an array of indices corresponding to this value and data type.
source to share
There are several ways to specify this using NumPy, depending on your needs, which you could use:
>>> import numpy as np
>>> fac = np.asarray(['a','a','a','b','b','c','c','c'])
source to share