Reputation: 1185
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?
Upvotes: 0
Views: 80
Reputation: 3363
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)
Upvotes: 2
Reputation: 1146
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
Upvotes: 2