Numpy/Python:没有 for 循环的数组迭代 [英] Numpy/Python: Array iteration without for-loop

查看:35
本文介绍了Numpy/Python:没有 for 循环的数组迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是另一个 n 维数组问题:我希望能够将 n 维数组中的每个值与其邻居进行比较.例如,如果 a 是二维数组,我希望能够检查:

So it's another n-dimensional array question: I want to be able to compare each value in an n-dimensional arrays with its neighbours. For example if a is the array which is 2-dimensional i want to be able to check:

a[y][x]==a[y+1][x]

对于所有元素.所以基本上检查所有维度的所有邻居.现在我正在通过:

for all elements. So basically check all neighbours in all dimensions. Right now I'm doing it via:

for x in range(1,a.shape[0]-1):
   do.something(a[x])

使用了数组的形状,这样我就不会在边缘遇到超出范围的索引.所以如果我想在 n-D 中为数组中的所有元素做这样的事情,我确实需要 n 个似乎不整洁的 for 循环.有没有办法通过切片来做到这一点?像 a==a[:,-1,:] 或者我理解这完全错误?有没有办法告诉切片在最后停止?或者是否会有另一种让事情以完全不同的方式工作的想法?掩码数组?问候乔尼

The shape of the array is used, so that I don't run into an index out of range at the edges. So if I want to do something like this in n-D for all elements in the array, I do need n for-loops which seems to be untidy. Is there a way to do so via slicing? Something like a==a[:,-1,:] or am I understanding this fully wrong? And is there a way to tell a slice to stop at the end? Or would there be another idea of getting things to work in a totally other way? Masked arrays? Greets Joni

推荐答案

类似:

a = np.array([1,2,3,4,4,5])
a == np.roll(a,1)

哪个返回

array([False, False, False, False,  True, False], dtype=bool

您也可以为更高的维度指定一个轴,但正如其他人所说,您需要以某种方式处理边缘,因为值会环绕(正如您可以从名称中猜到的那样)

You can specify an axis too for higher dimensions, though as others have said you'll need to handle the edges somehow as the values wrap around (as you can guess from the name)

更完整的二维示例:

# generate 2d data
a = np.array((np.random.rand(5,5)) * 10, dtype=np.uint8)

# check all neighbours
for ax in range(len(a.shape)):
    for i in [-1,1]:
        print a == np.roll(a, i, axis=ax)

这篇关于Numpy/Python:没有 for 循环的数组迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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