在2D数组中将最大值更新为-1

时间:2014-12-23 10:38:33

标签: python arrays numpy multidimensional-array

我有一个2D数组:

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大小数组..我该怎么做?

2 个答案:

答案 0 :(得分:1)

>>> 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 :(得分:1)

使用纯Python(没有Numpy)我会这样做

# 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]]