如何更快地迭代具有 2 个维度的 Python numpy.ndarray [英] How to faster iterate over a Python numpy.ndarray with 2 dimensions

查看:57
本文介绍了如何更快地迭代具有 2 个维度的 Python numpy.ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我只是想让它更快:

So, i simply want to make this faster:

for x in range(matrix.shape[0]):
        for y in range(matrix.shape[1]):
            if matrix[x][y] == 2 or matrix[x][y] == 3 or matrix[x][y] == 4 or matrix[x][y] == 5 or matrix[x][y] == 6:
                if x not in heights:
                    heights.append(x)

简单地迭代一个 2x2 矩阵(通常是 18x18 或 22x22)并检查它的 x.但它有点慢,我想知道哪种方法最快.

Simply iterate over a 2x2 matrix (usually round 18x18 or 22x22) and check it's x. But its kinda slow, i wonder which is the fastest way to do this.

非常感谢!

推荐答案

对于基于 numpy 的方法,您可以这样做:

For a numpy based approach, you can do:

np.flatnonzero(((a>=2) & (a<=6)).any(1))
# array([1, 2, 6], dtype=int64)

<小时>

地点:

a = np.random.randint(0,30,(7,7))

print(a)

array([[25, 27, 28, 21, 18,  7, 26],
       [ 2, 18, 21, 13, 27, 26,  2],
       [23, 27, 18,  7,  4,  6, 13],
       [25, 20, 19, 15,  8, 22,  0],
       [27, 23, 18, 22, 25, 17, 15],
       [19, 12, 12,  9, 29, 23, 21],
       [16, 27, 22, 23,  8,  3, 11]])

<小时>

更大阵列上的计时:


Timings on a larger array:

a = np.random.randint(0,30, (1000,1000))

%%timeit
heights=[]
for x in range(a.shape[0]):
        for y in range(a.shape[1]):
            if a[x][y] == 2 or a[x][y] == 3 or a[x][y] == 4 or a[x][y] == 5 or a[x][y] == 6:
                if x not in heights:
                    heights.append(x)
# 3.17 s ± 59.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
yatu = np.flatnonzero(((a>=2) & (a<=6)).any(1))
# 965 µs ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

np.allclose(yatu, heights)
# true

使用 numpy 进行矢量化可产生大约 3200x 加速

Vectorizing with numpy yields to roughly a 3200x speedup

这篇关于如何更快地迭代具有 2 个维度的 Python numpy.ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆