结果是大小为 300000 的二维 numpy 数组
for i in range(np.size(results,0)):
if results[i][0]>=0.7:
count+=1
我在这个 python 代码中花费了 0.7 秒,但我在 C++ 代码中运行它,它花费了不到 0.07 秒。
那么如何让这段 python 代码尽可能快呢?
最佳答案
当为了速度进行数值计算时,尤其是在 Python 中,如果可能的话,您绝对不想使用 for 循环。 Numpy 针对“矢量化”计算进行了优化,因此您希望将通常在 for 循环中执行的工作传递给特殊的 numpy 索引和函数,如 where
。
我对 300,000 x 600 的 0 到 1 随机值数组进行了快速测试,发现了以下内容。
您的代码,使用一个 for 循环进行非矢量化:
每次运行 226 毫秒
%%timeit
count = 0
for i in range(np.size(n,0)):
if results[i][0]>=0.7:
count+=1
emilaz 解决方案:
每次运行 8.36 毫秒
%%timeit
first_col = results[:,0]
x = len(first_col[first_col>.7])
Ethan 的解决方案:
每次运行 7.84 毫秒
%%timeit
np.bincount(results[:,0]>=.7)[1]
我想出了最好的
每次运行 6.92 毫秒
%%timeit
len(np.where(results[:,0] > 0.7)[0])
所有 4 种方法都得出相同的答案,根据我的数据,答案是 90,134。希望这对您有所帮助!
关于python - 在 numpy 二维数组中计算大于的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55698337/