根据多个条件查找矩阵中的列位置
Find column location in matrix based on multiple conditions
我有一个如下形式的矩阵:
import numpy as np
matrix = np.array([[-2,2,6,7,8],[-3,7,1,0,-2]])
我想在第一行中找到具有最高可能值的列的位置,条件是第二行中的非负数,例如在我的例子中,我希望算法找到第 4 行。
solution = np.array([7,0])
column_location = 3
我尝试使用像 np.min(), np.max(),np.take()
这样的 numpy 函数,但在对矩阵进行子采样时丢失了位置信息。
这是一个草图:
pos_inds = np.where(matrix[1, :] >= 0)[0] # indices where 2nd row is positive
max_ind = matrix[0, pos_inds].argmax() # max index into row with positive values only
orig_max_ind = pos_inds[max_ind] # max index into the original array
print(orig_max_ind) # 3
print(matrix[:, orig_max_ind]) # [7, 0]
简单地说:
nn = np.where(matrix[1] >= 0)[0]
ix = nn[matrix[0, nn].argmax()]
关于您的数据:
>>> ix
3
这里我用masks来处理numpy,同时考虑到如果第二列所有的数都是负数,就无解了:
import numpy as np
import numpy.ma as ma
from copy import deepcopy
min_int = -2147483648
matrix = np.array([[-2, 2, 6, 7, 8], [-3, 7, 1, 0, -2]])
# we keep the original matrix untouched
matrix_copy = deepcopy(matrix)
masked_array = ma.masked_less(matrix[1], 0)
matrix_copy[0][masked_array.mask] = min_int
column_location = np.argmax(matrix_copy[0])
if matrix_copy[0][column_location] == min_int:
print("No solution")
else:
solution = np.array([matrix[0][column_location], matrix[1][column_location]])
print(solution) # np.array([7,0])
print(column_location) # 3
我有一个如下形式的矩阵:
import numpy as np
matrix = np.array([[-2,2,6,7,8],[-3,7,1,0,-2]])
我想在第一行中找到具有最高可能值的列的位置,条件是第二行中的非负数,例如在我的例子中,我希望算法找到第 4 行。
solution = np.array([7,0])
column_location = 3
我尝试使用像 np.min(), np.max(),np.take()
这样的 numpy 函数,但在对矩阵进行子采样时丢失了位置信息。
这是一个草图:
pos_inds = np.where(matrix[1, :] >= 0)[0] # indices where 2nd row is positive
max_ind = matrix[0, pos_inds].argmax() # max index into row with positive values only
orig_max_ind = pos_inds[max_ind] # max index into the original array
print(orig_max_ind) # 3
print(matrix[:, orig_max_ind]) # [7, 0]
简单地说:
nn = np.where(matrix[1] >= 0)[0]
ix = nn[matrix[0, nn].argmax()]
关于您的数据:
>>> ix
3
这里我用masks来处理numpy,同时考虑到如果第二列所有的数都是负数,就无解了:
import numpy as np
import numpy.ma as ma
from copy import deepcopy
min_int = -2147483648
matrix = np.array([[-2, 2, 6, 7, 8], [-3, 7, 1, 0, -2]])
# we keep the original matrix untouched
matrix_copy = deepcopy(matrix)
masked_array = ma.masked_less(matrix[1], 0)
matrix_copy[0][masked_array.mask] = min_int
column_location = np.argmax(matrix_copy[0])
if matrix_copy[0][column_location] == min_int:
print("No solution")
else:
solution = np.array([matrix[0][column_location], matrix[1][column_location]])
print(solution) # np.array([7,0])
print(column_location) # 3