3

I have arrays

a = numpy.array([1,3,5,7])
b = pandas.Series([1,2,3,4,5,6,7,8,9])

Is there a quick command to find all of the matching indices in b that contain a value in a? For example

a in b = [0,2,4,6]

2 Answers 2

3

You can use isin to find where values exist in an array-like object (also works for list):

In [14]:

a = np.array([1,3,5,7])
b = pd.Series([1,2,3,4,5,6,7,8,9])
# call .index if you are just interested in the index values
b[b.isin(a)].index
Out[14]:
Int64Index([0, 2, 4, 6], dtype='int64')

Without accessing the .index attribute you get a series returned:

In [15]:

b[b.isin(a)]
Out[15]:
0    1
2    3
4    5
6    7
dtype: int64
Sign up to request clarification or add additional context in comments.

Comments

2

You can use numpy's in1d:

>>> np.nonzero(np.in1d(b, a))[0]
array([0, 2, 4, 6], dtype=int64)

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.