gpt4 book ai didi

python - 使用 numpy 数组加速函数

转载 作者:行者123 更新时间:2023-12-01 02:23:05 25 4
gpt4 key购买 nike

from numba import jit

@jit
def interim_mk(x, unique_x):
"""

:param x:
:param unique_x:
:return:
"""
tp = np.zeros(unique_x.shape)

for i in range(len(unique_x)):
tp[i] = sum(x == unique_x[i])

return tp

在上面的函数中,我使用 jit 来尝试加快速度。然而,这似乎没有帮助。 x 和 unique_x 都是 numpy 数组,有没有办法加快计算速度(不使用 cython)

最佳答案

对于正数的情况

您可以使用np.bincount -

count = np.bincount(x)
out = count[count!=0]

使用unique_x -

out = np.bincount(x)[unique_x]

对于一般情况

out = np.bincount(np.searchsorted(unique_x, x))
<小时/>

当然,我们可以直接从 np.unique 调用中获取计数,如果这就是我们 unique_x 的方式 -

out = np.unique(x, return_counts=1)[1]

关于python - 使用 numpy 数组加速函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47744878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com