numpy的/ Python的:数组迭代,而不对环 [英] Numpy/Python: Array iteration without for-loop

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

问题描述

所以这是另外一个多维数组的问题:
我希望能够为每个值与邻国的n维数组进行比较。例如,如果一个是它是2维我想能够检查阵列

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维数组中的所有元素,确实需要换循环n这似乎是凌乱。有没有办法通过切片这样做呢?有点像一个== [: - 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)

有关在2D更完整的例子:

For a fuller example in 2D:

# 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的:数组迭代,而不对环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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