Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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 将二维数组中的最大值更新为-1_Python_Arrays_Numpy_Multidimensional Array - Fatal编程技术网

Python 将二维数组中的最大值更新为-1

Python 将二维数组中的最大值更新为-1,python,arrays,numpy,multidimensional-array,Python,Arrays,Numpy,Multidimensional Array,我有一个二维阵列: L = array([[ 4, 5, 3, 10, 1], [10, 1, 10, 10, 5], [ 1, 6, 3, 2, 7], [ 5, 1, 1, 5, 1], [ 8, 8, 8, 10, 5]]) 我需要将最大值更改为-1。结果数组如下所示: R = array([[ 4, 5, 3, -1, 1], [-1,

我有一个二维阵列:

L = array([[ 4,  5,  3, 10,  1],
           [10,  1, 10, 10,  5],
           [ 1,  6,  3,  2,  7],
           [ 5,  1,  1,  5,  1],
           [ 8,  8,  8, 10,  5]])
我需要将最大值更改为-1。结果数组如下所示:

R = array([[ 4,  5,  3, -1,  1],
           [-1,  1, -1, -1,  5],
           [ 1,  6,  3,  2,  7],
           [ 5,  1,  1,  5,  1],
           [ 8,  8,  8, -1,  5]])

我的数组L将是一个5*5大小的随机数组。。我如何做到这一点?

使用纯Python而不使用Numpy,我会这样做

>>> import numpy as np
>>> L = np.array([[ 4,  5,  3, 10,  1],
...               [10,  1, 10, 10,  5],
...               [ 1,  6,  3,  2,  7],
...               [ 5,  1,  1,  5,  1],
...               [ 8,  8,  8, 10,  5]])
>>> R = L.copy()
>>> R[R==R.max()]=-1
>>> R
array([[ 4,  5,  3, -1,  1],
       [-1,  1, -1, -1,  5],
       [ 1,  6,  3,  2,  7],
       [ 5,  1,  1,  5,  1],
       [ 8,  8,  8, -1,  5]])
# 1) the list as supplied
L = [[ 4,  5,  3, 10,  1],
     [10,  1, 10, 10,  5],
     [ 1,  6,  3,  2,  7],
     [ 5,  1,  1,  5,  1],
     [ 8,  8,  8, 10,  5]]

# 2) helper function
def check(item, row, L):
    maximum = max([x for y in L for x in y])
    return -1 if item is maximum else item

# 3) apply the check to all elements of L, save as R
R = [[check(item,row,L) for item in row] for row in L]
结果

>>> R

[[ 4,  5,  3, -1,  1],
 [-1,  1, -1, -1,  5],
 [ 1,  6,  3,  2, -1],
 [-1,  1,  1, -1,  1],
 [ 8,  8,  8, -1,  5]]

你需要提供你迄今为止所做的努力。我现在不能测试它,但我认为np.where不是完全需要的。如果我没有错的话,R[R==R.max]=-1也应该做这项工作。这只考虑每行的最大值。感谢@iluengo,我已经修复了最大值确定为整个集合的最大值,而不是每行的最大值。现在它可以工作了:D但是,您可以只计算一次最大值,而不是每行一次。只是一些改进的建议,希望你不要太恨我。