简体   繁体   English

使用numpy在第一矩阵列中搜索数组,并获取下一列的值

[英]Search an array in first matrix column with numpy and get next column values

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 我能够找到与“ ids”中的行匹配的“ heroes”值,但是我只能打印出匹配项,例如

 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 ). 注意这是一个给定的练习,我不希望有其他要求,例如将ids数组中的#行中的heroes数组diff上的元素数量row_stack由于使用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. 但是我注意到我where无法在ids数组上找到重复的值(例如,如果我有2个带有diff名称的“ Spiderman”,并且两个名称都出现在heroes数组中),可以随意扩展到此,但是主要的问题是我只是没有其他限制的情况下撰写。

You can use np.argwhere and indexing to get the names. 您可以使用np.argwhere和索引来获取名称。 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. 内部[:,0]为您提供了两个包含名称的子数组[:,0]外部[:,0]为您提供了每个子数组中的第一个元素(名称)。

ids[np.argwhere(ids==(np.row_stack(heroes)))[:,0]][:, 0]
# array(['Peter Parker', 'Ben Reilly'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM