Python / numpy: Get array location of a list of values

Let's say I have an array of values nameArr = ['josh','is','a','person'], and I want a function like arrayLocation(nameArr,['a','is'])that to return [2 1].

This function already exists, if not, how can I effectively implement it?

+3
source share
4 answers

use numpy.where

In [17]: nameArr = np.array(['josh','is','a','person'])

In [18]: [np.where(nameArr==i) for i in ['a','is']]
Out[18]: [(array([2]),), (array([1]),)]
+6
source

There is a method in the lists indexthat you can use.

>>> nameArr = ['josh','is','a','person']
>>> # Using map
>>> map(nameArr.index, ['a', 'is'])
[2, 1]
>>> # Using list comprehensions
>>> [nameArr.index(x) for x in ['a', 'is']]
[2, 1]

BTW, indexinvokes ValueErrorif the item is not in the list. Therefore, if you want to provide non-list items to the index method, you may need to handle the error properly.

+3
source

, dict, :

d = dict(zip(nameArr, range(len(nameArr))))
items = ['a','is']
print [d.get(x, None) for x in items]
+2

- :

>>> f_idxs = np.ravel([np.where(master_data==i)[0] for i in search_list])
+1

All Articles