2
votes

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

3
What do you do with the indices at the edges? - mgilson
That's exactly the reason, why I'm using the for-loop until now. At the edge, there is no x+1 or z+1 so I'm iterating only until shape[0]-1. - Dschoni

3 Answers

5
votes

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
votes

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:, :]
0
votes

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 ?