在numpy数组中将min值替换为另一个

时间:2015-11-19 03:28:16

标签: python arrays numpy min

假设我们有这个数组,我想用数字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的范围....

任何寻求帮助的想法?

1 个答案:

答案 0 :(得分:6)

您需要使用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]])

(我相信我的原始答案不正确,我对行和列感到困惑,这是对的)