在 NumPy 数组中查找给定的坐标位置
Finding Given Coordinate Positions in NumPy Array
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]]
我想获取给定列和行 (11,1)、(5,11)、(12,2)、(13,3)、(15,5) 所在的位置。所以预期的答案如下:
[[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]]
我试过:
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
但是答案是错误的。
伙计们,怎么做?
你的尝试出错的原因是你首先需要分别计算每一对,你不能先单独计算所有行和列,然后将它们组合成一个逻辑运算。
这是一种修复方法:
out = np.zeros(rows.shape, dtype=bool)
for r, c in zip(ref_rows, ref_cols):
out |= (r == rows) & (c == cols)
print out
可能存在更优雅的解决方案,但这对我有用并且是以矢量化方式编写的...
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)
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]]
我想获取给定列和行 (11,1)、(5,11)、(12,2)、(13,3)、(15,5) 所在的位置。所以预期的答案如下:
[[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]]
我试过:
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
但是答案是错误的。
伙计们,怎么做?
你的尝试出错的原因是你首先需要分别计算每一对,你不能先单独计算所有行和列,然后将它们组合成一个逻辑运算。
这是一种修复方法:
out = np.zeros(rows.shape, dtype=bool)
for r, c in zip(ref_rows, ref_cols):
out |= (r == rows) & (c == cols)
print out
可能存在更优雅的解决方案,但这对我有用并且是以矢量化方式编写的...
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)