【问题标题】:Update max value to -1 in 2D array将二维数组中的最大值更新为 -1
【发布时间】:2015-02-21 11:52:08
【问题描述】:

我有一个二维数组:

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 arrays numpy multidimensional-array


【解决方案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]])

【讨论】:

  • 我现在无法测试它,但我认为 np.where 并不完全需要。如果我没记错的话R[R == R.max()] = -1 也应该做这个工作。
【解决方案2】:

使用纯 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]]

【讨论】:

  • 这仅考虑每行的max
  • 感谢@iluengo 我已将整个集合的最大确定性修复为max,而不是每一行
  • 现在它可以工作了:D 但是,您可以只计算一次最大值,而不是每行一次。 (只是建议改进它,希望你不要太讨厌我)。
猜你喜欢
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
  • 2016-06-21
  • 2021-02-18
  • 1970-01-01
  • 2016-04-14
  • 2017-12-28
相关资源
最近更新 更多