1

Having the following arrays (I understand the first one is call a matrix)

ids = np.array([['Peter Parker','Spiderman'],['Ben Reilly','Scarlet Spider'],['Norman Osborn','Green Goblin'],['Bruce Banner','Hulk']])

And

heroes=np.array(['Spiderman','Scarlet Spider','Capitan America','Iron Man'])

I'm able to find the "heroes" values that matches rows in "ids" but I can only print the matches like

 print(ids[np.where(ids==(np.row_stack(heroes)))])

Which outputs

['Spiderman' 'Scarlet Spider']

Is it (and how) possible to print them like ?

['Peter Parker' 'Ben Reilly']

note This is a given exercise, I don't expect other requirements like having the qty of elements on the heroes array diff from the # of rows in the ids array (this would it break my current code due the use of row_stack).

But I noticed that my where would not find duplicated values on the ids array (like if I have 2 "Spiderman" with diff name and both names appears in the heroes array), feel free to extend to this but main question is what I just wrote with no other given restrictions.

1 Answer 1

2

You can use np.argwhere and indexing to get the names. The inner [:,0] gives you the two subarrays containing the names and the outer [:,0] gives you the first element (name) from each of the subarrays.

ids[np.argwhere(ids==(np.row_stack(heroes)))[:,0]][:, 0]
# array(['Peter Parker', 'Ben Reilly'])
Sign up to request clarification or add additional context in comments.

2 Comments

Hi sorry, but I got a similar result by doing ids[np.where(ids==(np.row_stack(heroes))),1][0] but I am unable to know if this is somehow equivalent to your answer or I am doing something unnecessary , I will appreciate any thought, thanks again
@Allende: np.where and np.argwhere gives different results. For my answer, you should use np.argwhere. It generates a 2d matrix of indices whereas np.where generates an array of 1-d subarrays

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.