gpt4 book ai didi

python替换二维numpy数组中的值

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:37 26 4
gpt4 key购买 nike

我想用 -1 替换 2d numpy 数组每一列的最大值:

b = numpy.array([[1,2,3,4],[5,6,7,8], [9,10,11,12]])
#get the max value of each column
maxposcol = b.argmax(axis = 0)
maxvalcol = b.max(axis = 0)
#replace max values with -1
for i in numpy.arange(b.shape[1]):
b[maxposcol[i]][i] = -1

有没有其他方法可以替换由maxposcol[i]给定位置的最大值?

如果我想找到矩阵每一列的 n 个最大值,您会建议我做什么?使用排序?迭代地重复搜索最大值并在每一步替换它们?

最佳答案

你可以这样做:

>>> a=np.argmax(b, axis=0)
>>> b[a] = -1
>>> b
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[-1, -1, -1, -1]])

关于python替换二维numpy数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10984750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com