
这是我正在寻找的:
a=np.array([[4,6],[2,[5,2]])b=np.array([[1,7],[1,8],1],4],[4,9],2],1]])
完成这个技巧的确切matlab函数是:
[~,index] = ismember(a,b,'rows')
哪里
index = [6,3,9]解决方法
import numpy as npdef asvoID(arr): """ VIEw the array as dtype np.voID (bytes) This vIEws the last axis of ND-arrays as bytes so you can perform comparisons on the entire row. https://stackoverflow.com/a/16840350/190597 (Jaime,2013-05) Warning: When using asvoID for comparison,note that float zeros may compare UNEQUALLY >>> asvoID([-0.]) == asvoID([0.]) array([False],dtype=bool) """ arr = np.ascontiguousarray(arr) return arr.vIEw(np.dtype((np.voID,arr.dtype.itemsize * arr.shape[-1])))def in1d_index(a,b): voIDa,voIDb = map(asvoID,(a,b)) return np.where(np.in1d(voIDb,voIDa))[0] a = np.array([[4,2]])b = np.array([[1,1]])print(in1d_index(a,b))
版画
[2 5 8]
这相当于Matlab的[3,6,因为Python使用基于0的索引.
一些警告:
>指数按递增顺序返回.他们不对应
到b的项目的位置.
> asvoID将用于整数dtypes,但是如果使用asvoID则要小心
在float dtypes上,因为asvoID([ – 0.])== asvoID([0.])返回
阵列([FALSE]).
> asvoID在连续数组上效果最佳.如果数组不连续,则数据将被复制到连续数组,这将降低性能.
尽管存在警告,但为了速度,人们可能会选择使用in1d_index:
def ismember_rows(a,b): # https://stackoverflow.com/a/22705773/190597 (ashg) return np.nonzero(np.all(b == a[:,np.newaxis],axis=2))[1]In [41]: a2 = np.tile(a,(2000,1))In [42]: b2 = np.tile(b,1))In [46]: %timeit in1d_index(a2,b2)100 loops,best of 3: 8.49 ms per loopIn [47]: %timeit ismember_rows(a2,b2)1 loops,best of 3: 5.55 s per loop
因此in1d_index快〜650倍(对于数千的长数组),但再次注意比较并不完全是苹果对苹果,因为in1d_index按递增顺序返回索引,而ismember_rows返回a的顺序行中的索引.出现在b.
总结以上是内存溢出为你收集整理的带有’rows’和index的ismember的Python版本全部内容,希望文章能够帮你解决带有’rows’和index的ismember的Python版本所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)