One - One Code All

Blog Content

np.in1d在一个与某个列表匹配的numpy二维数组中查找所有元素

Python 统计学-科学计算   2014-03-03 19:36:02

np.in1d在一个与某个列表匹配的numpy二维数组中查找所有元素

np.inld(x,y):返回一个x集合的元素是否包含在y集合中的bool型数组.

 

 可以使用np.in1d –

A*np.in1d(A,[1,3,4]).reshape(A.shape)

此外,np.where可以使用 –


np.where(np.in1d(A,[1,3,4]).reshape(A.shape),A,0)

您还可以使用np.searchsorted通过使用其可选的“side”参数以及左右输入来查找此类匹配,并注意到匹配时,searchsorted将使用这两个输入输出不同的结果.因此,相当于np.in1d(A,[1,3,4])将是 –


M = np.searchsorted([1,3,4],A.ravel(),'left') != \

    np.searchsorted([1,3,4],A.ravel(),'right')

因此,最终的输出将是 –


out = A*M.reshape(A.shape)

请注意,如果未对输入搜索列表进行排序,则需要在np.searchsorted中使用带有argsort索引的可选argumentsorter.


In [321]: A

Out[321]: 

array([[1, 1, 0, 2, 2],

       [1, 1, 0, 2, 0],

       [0, 0, 0, 0, 0],

       [3, 3, 0, 4, 4],

       [3, 3, 0, 4, 4]])


In [322]: A*np.in1d(A,[1,3,4]).reshape(A.shape)

Out[322]: 

array([[1, 1, 0, 0, 0],

       [1, 1, 0, 0, 0],

       [0, 0, 0, 0, 0],

       [3, 3, 0, 4, 4],

       [3, 3, 0, 4, 4]])


In [323]: np.where(np.in1d(A,[1,3,4]).reshape(A.shape),A,0)

Out[323]: 

array([[1, 1, 0, 0, 0],

       [1, 1, 0, 0, 0],

       [0, 0, 0, 0, 0],

       [3, 3, 0, 4, 4],

       [3, 3, 0, 4, 4]])


In [324]: M = np.searchsorted([1,3,4],A.ravel(),'left') != \

     ...:     np.searchsorted([1,3,4],A.ravel(),'right')

     ...: A*M.reshape(A.shape)

     ...: 

Out[324]: 

array([[1, 1, 0, 0, 0],

       [1, 1, 0, 0, 0],

       [0, 0, 0, 0, 0],

       [3, 3, 0, 4, 4],

       [3, 3, 0, 4, 4]])

运行时测试和验证输出 –


In [309]: # Inputs

     ...: A = np.random.randint(0,1000,(400,500))

     ...: lst = np.sort(np.random.randint(0,1000,(100))).tolist()

     ...: 

     ...: def func1(A,lst):                         

     ...:   return A*np.in1d(A,lst).reshape(A.shape)

     ...: 

     ...: def func2(A,lst):                         

     ...:   return np.where(np.in1d(A,lst).reshape(A.shape),A,0)

     ...: 

     ...: def func3(A,lst):                         

     ...:   mask = np.searchsorted(lst,A.ravel(),'left') != \

     ...:          np.searchsorted(lst,A.ravel(),'right')

     ...:   return A*mask.reshape(A.shape)

     ...: 


In [310]: np.allclose(func1(A,lst),func2(A,lst))

Out[310]: True


In [311]: np.allclose(func1(A,lst),func3(A,lst))

Out[311]: True


In [312]: %timeit func1(A,lst)

10 loops, best of 3: 30.9 ms per loop


In [313]: %timeit func2(A,lst)

10 loops, best of 3: 30.9 ms per loop


In [314]: %timeit func3(A,lst)

10 loops, best of 3: 28.6 ms per loop




上一篇:numpy常用函数np.take
下一篇:pandas汇总和计算描述统计:统计函数sum求和

The minute you think of giving up, think of the reason why you held on so long.