Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在numpy中查找最大值跳过某些行和列_Python_Numpy_Matrix - Fatal编程技术网

Python 在numpy中查找最大值跳过某些行和列

Python 在numpy中查找最大值跳过某些行和列,python,numpy,matrix,Python,Numpy,Matrix,我想在numpy矩阵中找到最大行和列索引。但它不在一组行或列中。因此,在计算最大值时,它应该跳过这些行和列 例如: 但是它应该跳过删除的行和列 我不想为计算创建一个新的子矩阵。让a作为输入数组,rows\u rem和cols\u rem分别作为要跳过的行和列索引。我们会有一种使用掩蔽的方法,就像这样- m,n = a.shape d0,d1 = np.ogrid[:m,:n] a_masked = a*~(np.in1d(d0,rows_rem)[:,None] | np.in1d(d1,col

我想在numpy矩阵中找到最大行和列索引。但它不在一组行或列中。因此,在计算最大值时,它应该跳过这些行和列

例如:

但是它应该跳过删除的行和列

我不想为计算创建一个新的子矩阵。

让a作为输入数组,rows\u rem和cols\u rem分别作为要跳过的行和列索引。我们会有一种使用掩蔽的方法,就像这样-

m,n = a.shape
d0,d1 = np.ogrid[:m,:n]
a_masked = a*~(np.in1d(d0,rows_rem)[:,None] | np.in1d(d1,cols_rem))
max_row, max_col = np.where(a_masked == a_masked.max())
max_row, max_col = np.unravel_index(a_masked.argmax(),a.shape)
样本运行-

In [204]: # Inputs
     ...: a = np.random.randint(11,99,(4,5))
     ...: rows_rem = [1,3]
     ...: cols_rem = [1,2,4]
     ...: 

In [205]: a
Out[205]: 
array([[36, 51, 72, 18, 31],
       [78, 42, 12, 71, 72],
       [38, 46, 42, 67, 12],
       [87, 56, 76, 14, 21]])

In [206]: a_masked
Out[206]: 
array([[64,  0,  0, 90,  0],
       [ 0,  0,  0,  0,  0],
       [17,  0,  0, 40,  0],
       [ 0,  0,  0,  0,  0]])

In [207]: max_row, max_col
Out[207]: (array([0]), array([3]))
请注意,如果有多个元素具有相同的最大值,则输出中将包含所有这些元素。因此,如果您想要其中任何一个或第一个,我们可以使用argmax,就像这样-

m,n = a.shape
d0,d1 = np.ogrid[:m,:n]
a_masked = a*~(np.in1d(d0,rows_rem)[:,None] | np.in1d(d1,cols_rem))
max_row, max_col = np.where(a_masked == a_masked.max())
max_row, max_col = np.unravel_index(a_masked.argmax(),a.shape)
通过筛选出要删除的索引,获取感兴趣的行和列索引:

r, c = a.shape
r = [x for x in range(r) if x not in remove_rows]
c = [x for x in range(c) if x not in remove_cols]

>>> r,c
([0, 1], [2, 3, 4])
>>>
现在r和c可以用于,有助于实现这一点

>>> a[np.ix_(r,c)]
array([[89, 66, 20],
       [78, 90, 44]])
>>>
钉住ndarray.max以获得最大值:

>>> a[np.ix_(r,c)].max()
90
>>>
最后,使用numpy.where查找它在原始数组中的位置:

>>> row, col = np.where(a == a[np.ix_(r,c)].max())
>>> row, col
(array([1]), array([3]))
>>>
如果删除非连续的行或列,此方法也会起作用。 例如:

remove_rows = [0,3]
remove_cols = [1,4]

数组/矩阵是否有负数?@Divakar否,它只包含非负数。是否可以更改输入数组?删除的行和列是否始终连续?[2,3,4]而不是[2,4,6]?通过切片、跳过这些行和列可以进行任何操作。请检查问题中的编辑。它给出的元素不是矩阵本身,同样的情况也发生在你的编辑答案上。它给出了矩阵本身以外的元素。请用a=np.array[[11,1.],[1,5.],[1,11.].@AbhishekBhatia,我不明白:你想让我怎么检查a=np.array[[11,1.],[1,5.],[1,11.]?