3

I have two 2D numpy arrays of the same shape. Is there a way to iterate through them simultaneously with getting e.g. a pair of elemets from both tables and their index?

For example, I have two arrays

before = np.array(
    [[0, 0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0, 0]],
    dtype=int
)
after = np.array(
    [[0, 0, 1, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 1, 0, 0, 1]],
    dtype=int
)

I want to get a list of indexes of every zero from before table that has been transformed to one in the after table - in this scenario that would be [(0, 2), (1, 4), (1, 7)].

numpy.ndenumerate is very close to what I'd like to achieve, but it can iterate through only one array at once.

1 Answer 1

4

You can pass both conditions to np.logical_and and then use np.argwhere to find indices that meet both conditions:

idx = np.argwhere(np.logical_and(before==0, after==1))

output:

[[0 2]
 [1 4]
 [1 7]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.