麻巴
使用numba可以优化两种情况.从语法上讲,您只需要构造一个带有简单for循环的函数:
from numba import njit
@njit
def get_first_index_nb(A, k):
for i in range(len(A)):
if A[i] > k:
return i
return -1
idx = get_first_index_nb(A, 0.9)
Numba通过JIT(“及时”)编译代码并利用CPU-level optimisations来提高性能.不带@njit装饰器的常规for循环通常比您在条件较晚满足的情况下尝试过的方法要慢.
对于熊猫数字系列df [‘data’],您可以将NumPy表示形式简单地馈送到JIT编译的函数中:
idx = get_first_index_nb(df['data'].values, 0.9)
概括
由于numba允许functions as arguments,并且假设传递的函数也可以JIT编译,则可以找到一种方法,该方法可以计算第n个索引,其中满足任意函数的条件.
@njit
def get_nth_index_count(A, func, count):
c = 0
for i in range(len(A)):
if func(A[i]):
c += 1
if c == count:
return i
return -1
@njit
def func(val):
return val > 0.9
# get index of 3rd value where func evaluates to True
idx = get_nth_index_count(arr, func, 3)
对于倒数第3个值,您可以输入相反的值arr [::-1],并取反len(arr)-1的结果,而-1是解决0索引所必需的.
绩效基准
# Python 3.6.5, NumPy 1.14.3, Numba 0.38.0
(0)
arr = (10**7)
m = 0.9
n = 0.999999
@njit
def get_first_index_nb(A, k):
for i in range(len(A)):
if A[i] > k:
return i
return -1
def get_first_index_np(A, k):
for i in range(len(A)):
if A[i] > k:
return i
return -1
%timeit get_first_index_nb(arr, m) # 375 ns
%timeit get_first_index_np(arr, m) # 2.71 ?s
%timeit next(iter((arr > m)[0]), -1) # 43.5 ms
%timeit next((idx for idx, val in enumerate(arr) if val > m), -1) # 2.5 ?s
%timeit get_first_index_nb(arr, n) # 204 ?s
%timeit get_first_index_np(arr, n) # 44.8 ms
%timeit next(iter((arr > n)[0]), -1) # 21.4 ms
%timeit next((idx for idx, val in enumerate(arr) if val > n), -1) # 39.2 ms