假设:
a = [[0, 1], [2, 2], [4, 2]]
b = [[0, 1, 2, 3], [2, 2, 3, 4], [4, 2, 3, 3], [2, 3, 3, 3]]
解决方案是:
for (i,j) in zip(a[:, 0], a[:, 1]):
print b[np.logical_and( a[:, 0] == i, a[:, 1] == j)]
结果应为
[[0 1 2 3]]
[[2 2 3 4]]
[[4 2 3 3]]
在不使用for
- 循环的情况下,是否有解决此问题的方法?
答案 0 :(得分:1)
您可以使用NumPy broadcasting
作为矢量化解决方案,如此 -
# 2D mask corresponding to all iterations of :
# "np.logical_and( a[:, 0] == i, a[:, 1] == j)"
mask = (a[:,None,0] == a[:,0]) & (a[:,None,1] == a[:,1])
# Use column indices of valid ones for indexing into b for final output
_,C_idx = np.where(mask)
out = b[C_idx]
示例运行 -
In [67]: # Modified generic case
...: a = np.array([[0, 1], [3, 2], [3, 2]])
...: b = np.array([[0, 1, 2, 3], [2, 2, 3, 4], [4, 2, 3, 3], [2, 3, 3, 3]])
...:
...: for (i,j) in zip(a[:, 0], a[:, 1]):
...: print b[np.logical_and( a[:, 0] == i, a[:, 1] == j)]
...:
[[0 1 2 3]]
[[2 2 3 4]
[4 2 3 3]]
[[2 2 3 4]
[4 2 3 3]]
In [68]: mask = (a[:,None,0] == a[:,0]) & (a[:,None,1] == a[:,1])
...: _,C_idx = np.where(mask)
...: out = b[C_idx]
...:
In [69]: out
Out[69]:
array([[0, 1, 2, 3],
[2, 2, 3, 4],
[4, 2, 3, 3],
[2, 2, 3, 4],
[4, 2, 3, 3]])
答案 1 :(得分:0)
假设:
a = np.array(([0, 1], [2, 2], [4, 2]))
b = np.array(([0, 1, 2, 3], [2, 2, 3, 4], [4, 2, 3, 3], [2, 3, 3, 3]))
计算:
temp = np.in1d(b[:,0], a[:,0]) * np.in1d(b[:,1], a[:,1])
result = b[temp]
print 'result:', result
输出:
result: [[0 1 2 3]
[2 2 3 4]
[4 2 3 3]]