1

Here's my current code:

a = np.array(['apples', 'pear', 'oranges', 'grapes', 'apples', 'banana'])
b = np.array([1,2,3,4,5,6])
my_list = ['apples', 'oranges', 'grapes']

How do I create a line of code that will return the following result:

result = np.array([1,3,4,5])

The method must use my_list as the basis for slicing array b based on array a. (It should work regardless of the length of my_list)

Thanks in advance!

3
  • So you don't want to include 5 for apples in your output too? Commented Jan 28, 2016 at 9:12
  • oops! sorry my bad. edited it! 5 should be part. :) thanks! Commented Jan 28, 2016 at 9:13
  • What if a = np.array(['oranges', 'apples', 'pear', 'grapes', 'apples', 'banana']). i.e. the items in a and not in the order of my_list? Commented Jan 28, 2016 at 9:21

1 Answer 1

1

You could slice using np.in1d():

In [15]: b[np.in1d(a, my_list)]
Out[15]: array([1, 3, 4, 5])
Sign up to request clarification or add additional context in comments.

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.