替换不带循环的numpy数组每行中的最大值

时间:2020-09-13 07:07:35

标签: python numpy

我有一个像这样的数组,将其整形,需要将每行的最大值(所以axis = 1?)替换为0。我不能用于循环。

x = np.random.uniform(1.0, 21.0, 20)
print("Original array: ", x)

xMatrix = x.reshape(4, 5)
print(xMatrix)

maxNum = np.amax(xMatrix, axis=1)

因此,很明显,maxNum只给我每一行的最大值。但是,我将如何真正替换那些值而不简单地遍历数组呢?

4 个答案:

答案 0 :(得分:1)

尝试将np.where与np.isin结合使用:

np.where(np.isin(xMatrix,maxNum), 0, xMatrix)

答案 1 :(得分:1)

跟随是一种单次执行此操作的方法,与此处的其他答案不同,先找到最大值然后搜索它。

此解决方案在每一行中找到最大值的INDEX,然后将0分配给该索引。

import numpy as np

x = np.random.uniform(1.0, 21.0, 20)
print("Original array: ", x)

xMatrix = x.reshape(4, 5)
print(xMatrix)

给予

xMatrix
Out[28]: 
array([[10.10437809,  6.4552141 , 15.1040498 ,  1.94380305, 15.27380855],
       [12.08934681, 19.20744506, 14.12271304,  8.45470779,  6.2887767 ],
       [ 7.74326665, 14.63460522, 12.07651464, 15.80510958,  2.24595519],
       [16.12620326, 16.29083185,  7.96133555, 10.61357712, 14.6664017 ]])

然后

max_ind = np.argmax(xMatrix, axis=1)
row_ind = np.arange(xMatrix.shape[0])
multi_ind = np.array([row_ind, max_ind])
linear_ind = np.ravel_multi_index(multi_ind, xMatrix.shape)
xMatrix.reshape((-1))[linear_ind] = 0
xMatrix
Out[37]: 
array([[10.10437809,  6.4552141 , 15.1040498 ,  1.94380305,  0.        ],
       [12.08934681,  0.        , 14.12271304,  8.45470779,  6.2887767 ],
       [ 7.74326665, 14.63460522, 12.07651464,  0.        ,  2.24595519],
       [16.12620326,  0.        ,  7.96133555, 10.61357712, 14.6664017 ]])

答案 2 :(得分:0)

您可以像这样使用map和lamda函数

list(map(lambda x : max(x), xMatrix))

答案 3 :(得分:0)

我得到了你要找的东西 使用简单的比较运算符及其完成

xMatrix[xMatrix == max_num[:, None]] = 0
相关问题