【问题标题】:replace min value to another in numpy array将最小值替换为numpy数组中的另一个
【发布时间】:2016-02-21 01:20:33
【问题描述】:

假设我们有这个数组,我想用数字 50 替换最小值

import numpy as np
numbers = np.arange(20)
numbers[numbers.min()] = 50

所以输出是[50,1,2,3,....20]

但现在我遇到了问题:

numbers = np.arange(20).reshape(5,4)
numbers[numbers.min(axis=1)]=50

获取[[50,1,2,3],[50,5,6,7],....]

但是我得到了这个错误:

IndexError: 索引 8 超出轴 0 的范围,大小为 5 ....

有什么建议吗?

【问题讨论】:

  • numbers.min() 返回最小值而不是数组的索引。在您的第一个示例中,它之所以有效,是因为数组的索引和值是相同的。你需要找到最小数字的索引。
  • numbers.min() 返回 numpy 数组中的最小值,而不是 index。仅当您有一个具有严格连续递增值的数组时,它才有效。最好使用返回最小值位置的函数,然后用它来替换新值。

标签: python arrays numpy min


【解决方案1】:

您需要使用numpy.argmin 而不是numpy.min

In [89]: numbers = np.arange(20).reshape(5,4)

In [90]: numbers[np.arange(len(numbers)), numbers.argmin(axis=1)] = 50
In [91]: numbers
Out[91]: 
array([[50,  1,  2,  3],
       [50,  5,  6,  7],
       [50,  9, 10, 11],
       [50, 13, 14, 15],
       [50, 17, 18, 19]])

In [92]: numbers = np.arange(20).reshape(5,4)

In [93]: numbers[1,3] = -5 # Let's make sure that mins are not on same column

In [94]: numbers[np.arange(len(numbers)), numbers.argmin(axis=1)] = 50

In [95]: numbers
Out[95]: 
array([[50,  1,  2,  3],
       [ 4,  5,  6, 50],
       [50,  9, 10, 11],
       [50, 13, 14, 15],
       [50, 17, 18, 19]])

(我相信我原来的答案是不正确的,我混淆了行和列,这是正确的)

【讨论】:

  • 啊!我没有考虑 argmin() 函数,谢谢你救了我一夜!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 2021-07-04
  • 2017-09-21
  • 2020-03-18
  • 2021-10-13
相关资源
最近更新 更多