0
import numpy as np

ref_cols = [11, 5, 12, 13, 15]
ref_rows = [1, 11, 2, 3, 5]
rows, cols = np.mgrid[1:6, 11:16]
print cols

[[11 12 13 14 15]
 [11 12 13 14 15]
 [11 12 13 14 15]
 [11 12 13 14 15]
 [11 12 13 14 15]]
print rows

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]
 [5 5 5 5 5]]

I want to get where the given cols and rows (11,1), (5,11), (12,2), (13,3), (15,5) exists. So the expected answer is follows:

[[True, False, False, False, False],
[False, True, False, False, False],
[False, False, True, False, False],
[False, False, False, False, False],
[False, False, False, False, True]]

I tried as:

rows_indices = np.in1d(rows, ref_rows).reshape(rows.shape)
cols_indices = np.in1d(cols, ref_cols).reshape(cols.shape)
answers = (rows_indices & cols_indices)
print answers

But answer is wrong.

How to do it guys?

2 Answers 2

2

The reason that your try goes wrong is that you first need to evaluate each pair separately and you cannot evaluate first all rows and columns separately and then combine them in a logical operation.

Here is one way to fix it:

out = np.zeros(rows.shape, dtype=bool)
for r, c in zip(ref_rows, ref_cols):
    out |= (r == rows) & (c == cols)
print out
Sign up to request clarification or add additional context in comments.

3 Comments

I could not understand the meaning of |=. Could you explain it?
Of course. The statement a = a | b (where | is the bitwise or-operator) can be shortened to a |= b.
Nice answer - might be a good idea to move the comment into the answer itself, because comments should be considered volatile...
2

Probably there exists a more elegent solution but this works for me and is written in an vectorized way ...

import numpy as np

ref_cols = np.array([11, 5, 12, 13, 15])
ref_rows = np.array([1, 11, 2, 3, 5])
rows, cols = np.mgrid[1:6, 11:16]

m = (cols[:,:,None]==ref_cols[None,None,:]) & (rows[:,:,None]==ref_rows[None,None,:])

answer = np.any(m,axis=2)
#array([[ True, False, False, False, False],
#       [False,  True, False, False, False],
#       [False, False,  True, False, False],
#       [False, False, False, False, False],
#       [False, False, False, False,  True]], dtype=bool)

3 Comments

this may be true ... but it is vectorized and fast
I have never used vectorized way, could you explain for me?
sloppy saying ... it means avoiding for loops by using numpy functions which are 'usually' much faster than any loops. Your attempt above is for instance written in a vectorized way ... the other answer using the for loop is not. This does not mean that is a bad solution! Often, for loops are easier to understand in contrast to vectorized solutions which can look very complicated sometimes. However, when dealing with a lot of numbers vectorized codes are faster ... mostly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.