将最小值替换为numpy数组中的另一个 [英] replace min value to another in numpy array
本文介绍了将最小值替换为numpy数组中的另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我们有这个数组,我想用数字50代替最小值
Lets say we have this array and I want to replace the minimum value with number 50
import numpy as np
numbers = np.arange(20)
numbers[numbers.min()] = 50
所以输出是[50,1,2,3,....20]
但是现在我对此有疑问:
But now I have problems with this:
numbers = np.arange(20).reshape(5,4)
numbers[numbers.min(axis=1)]=50
获取[[50,1,2,3],[50,5,6,7],....]
但是我收到此错误:
IndexError:索引8超出了轴5的大小5 ....
IndexError: index 8 is out of bounds for axis 0 with size 5 ....
有什么帮助的想法吗?
推荐答案
您需要使用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]])
(我相信我的原始答案不正确,我混淆了行和列,这是正确的)
(I believe my original answer was incorrect, I confused rows and columns, and this is right)
这篇关于将最小值替换为numpy数组中的另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文