blah_crusader
blah_crusader

Reputation: 434

numpy: finding all pairs of numbers in a matrix that suffice on neighboring condition

Suppose you have a matrix:

import numpy as np
mat = np.array([[0, 0, 1], [2, 0, 1], [1, 0, 3]])

and you want to retrieve all pairs of numbers in this matrix that are neighboring each other, not equal and ignoring zero. In this case this would be 3 & 1 and 2 & 1, but I want to be able to apply this to a very large matrix. Any help greatly appreciated, thanks!

Upvotes: 1

Views: 50

Answers (1)

sacuL
sacuL

Reputation: 51335

This should do the trick, though admittedly, it's not the most elegant; I tested it on a 1000x1000 matrix of random integers, and it was pretty fast (just over a second). I'm not sure how you are thinking about the output, so I put it into a list called res.

import numpy as np
# To test on larger array
mat = np.array(np.random.random_integers(0, 9, 1000 * 1000)).reshape(1000, 1000)
res = []

for a in mat:
    # Take out the zeros
    no_zeros = a[a!=0]
    if len(no_zeros) > 1:
        for i in range(len(no_zeros) - 1):
            # Only append pairs of non-equal neighbours
            if no_zeros[i] != no_zeros[i+1]:
                res.append((no_zeros[i], no_zeros[i+1]))

Upvotes: 1

Related Questions