3

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

Does that function already exist, if not how can I implement it efficiently?

4 Answers 4

6

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]),)]
Sign up to request clarification or add additional context in comments.

Comments

3

Lists have a index method that 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, index raises ValueError if the element is not in the list. So if you want to supply elements that are not in the list to the index method, you may need to handle the error appropriately.

1 Comment

Also, it always returns the first index of the item, if the item is in the list multiple times.
2

If the array is large, and do many times of location, you can create a dict that map the value to it's index first:

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

1 Comment

Given scalability as a measure of quality this is by far the best answer here.
1

Something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.