替换numpy数组中每行的最大值w/out for循环

2024-07-08 09:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数组,对它进行了整形,需要将每行中的最大值(轴=1?)替换为0。我不能用for循环

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只给出每行的最大值。但我如何才能真正替换这些值,而不只是在数组中循环


Tags: fornprandomuniform数组arrayprintoriginal
3条回答

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

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

在与np.isin组合的情况下,尝试使用np.isin:

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

下面是一种在一次通过中完成此操作的方法,与这里的其他答案不同,这些答案首先查找最大值,然后搜索最大值

此解决方案在每行中查找最大值的索引,然后为该索引指定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 ]])

相关问题 更多 >

    热门问题