在另一个数组中查找一个数组的匹配索引

编程入门 行业动态 更新时间:2024-10-26 22:28:39
本文介绍了在另一个数组中查找一个数组的匹配索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个numpy数组A和B.A包含唯一值,而B是A的子数组. 现在,我正在寻找一种方法来获取A中B的值的索引.

I have two numpy arrays, A and B. A conatains unique values and B is a sub-array of A. Now I am looking for a way to get the index of B's values within A.

例如:

A = np.array([1,2,3,4,5,6,7,8,9,10]) B = np.array([1,7,10]) # I need a function fun() that: fun(A,B) >> 0,6,9

推荐答案

您可以使用 np.in1d 与 -

np.nonzero(np.in1d(A,B))[0]

您还可以使用 np.searchsorted ,如果您关心维护订单-

You can also use np.searchsorted, if you care about maintaining the order -

np.searchsorted(A,B)

对于一般情况,当A& B是未排序的数组,您可以在np.searchsorted中引入sorter选项,就像这样-

For a generic case, when A & B are unsorted arrays, you can bring in the sorter option in np.searchsorted, like so -

sort_idx = A.argsort() out = sort_idx[np.searchsorted(A,B,sorter = sort_idx)]

我也会添加我最喜欢的 broadcasting 在解决一般情况的过程中-

I would add in my favorite broadcasting too in the mix to solve a generic case -

np.nonzero(B[:,None] == A)[1]

样品运行-

In [125]: A Out[125]: array([ 7, 5, 1, 6, 10, 9, 8]) In [126]: B Out[126]: array([ 1, 10, 7]) In [127]: sort_idx = A.argsort() In [128]: sort_idx[np.searchsorted(A,B,sorter = sort_idx)] Out[128]: array([2, 4, 0]) In [129]: np.nonzero(B[:,None] == A)[1] Out[129]: array([2, 4, 0])

更多推荐

在另一个数组中查找一个数组的匹配索引

本文发布于:2023-11-30 10:10:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649610.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   组中   个数   索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!