Numpy/Python: Array iteration without for-loop

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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]) 

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

回答1:

Something like:

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

which returns

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)

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) 


回答2:

This might also be useful, this will compare each element to the following element, along axis=1. You can obviously adjust the axis or the distance. The trick is to make sure that both sides of the == operator have the same shape.

a[:, :-1, :] == a[:, 1:, :] 


回答3:

How about just:

np.diff(a) != 0 

?

If you need the neighbours in the other axis, maybe diff the result of np.swapaxes(a) and merge the results together somehow ?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!