我的问题可能很简单,但我想不出办法让这个操作更快
print a[(b==c[i]) for i in arange(0,len(c))]
其中 a,b 和 c 是三个numpy
数组。我正在处理具有数百万个条目的数组,上面的代码是我程序的瓶颈。
您是否试图获取a
where的值b==c
?
如果是这样,你可以这样做a[b==c]
:
from numpy import *
a = arange(11)
b = 11*a
c = b[::-1]
print a # [ 0 1 2 3 4 5 6 7 8 9 10]
print b # [ 0 11 22 33 44 55 66 77 88 99 110]
print c # [110 99 88 77 66 55 44 33 22 11 0]
print a[b==c] # [5]
您可能应该研究广播。我假设您正在寻找类似以下的内容?
>>> b=np.arange(5)
>>> c=np.arange(6).reshape(-1,1)
>>> b
array([0, 1, 2, 3, 4])
>>> c
array([[0],
[1],
[2],
[3],
[4],
[5]])
>>> b==c
array([[ True, False, False, False, False],
[False, True, False, False, False],
[False, False, True, False, False],
[False, False, False, True, False],
[False, False, False, False, True],
[False, False, False, False, False]], dtype=bool)
>>> np.any(b==c,axis=1)
array([ True, True, True, True, True, False], dtype=bool)
那么对于大型阵列,您可以尝试:
import timeit
s="""
import numpy as np
array_size=500
a=np.random.randint(500, size=(array_size))
b=np.random.randint(500, size=(array_size))
c=np.random.randint(500, size=(array_size))
"""
ex1="""
a[np.any(b==c.reshape(-1,1),axis=0)]
"""
ex2="""
a[np.in1d(b,c)]
"""
print 'Example 1 took',timeit.timeit(ex1,setup=s,number=100),'seconds.'
print 'Example 2 took',timeit.timeit(ex2,setup=s,number=100),'seconds.'
当 array_size 为 50 时:
Example 1 took 0.00323104858398 seconds.
Example 2 took 0.0125901699066 seconds.
当 array_size 为 500 时:
Example 1 took 0.142632007599 seconds.
Example 2 took 0.0283041000366 seconds.
当 array_size 为 5,000 时:
Example 1 took 16.2110910416 seconds.
Example 2 took 0.170011043549 seconds.
当 array_size 为 50,000 (number=5) 时:
Example 1 took 33.0327301025 seconds.
Example 2 took 0.0996031761169 seconds.
请注意,我必须更改 np.any() 的哪个轴,以便结果相同。反转 np.in1d 的顺序或切换 np.any 的轴以获得所需的效果。您可以从示例 1 中取出 reshape,但 reshape 确实非常快。切换以获得想要的效果。真的很有趣 - 我将来必须使用它。
怎么样np.where()
:
>>> a = np.array([2,4,8,16])
>>> b = np.array([0,0,0,0])
>>> c = np.array([1,0,0,1])
>>> bc = np.where(b==c)[0] #indices where b == c
>>> a[bc]
array([4,8])
这应该可以解决问题。不确定时间是否适合您的目的
>>> a = np.random.randint(0,10000,1000000)
>>> b = np.random.randint(0,10000,1000000)
>>> c = np.random.randint(0,10000,1000000)
>>> %timeit( a[ np.where( b == c )[0] ] )
100 loops, best of 3: 11.3 ms per loop