我想找到r2
中最大的元素,并将其与r2[0,0]
中的元素交换。我给出了预期的输出。
import numpy as np
r2 = np.array([[ 1.00657843, 63.38075613, 312.87746691],
[375.25164461, 500. , 125.75493382],
[437.6258223 , 250.50328922, 188.12911152]])
indices = np.where(r2 == r2.max())
期望输出为
array([[ 500., 63.38075613, 312.87746691],
[375.25164461, 1.00657843, 125.75493382],
[437.6258223 , 250.50328922, 188.12911152]]
可以直接返回最大值的索引然后与第一个索引交换
# get index of largest value.
index = np.unravel_index(r2.argmax(), r2.shape)
# swap with item at index 0,0
r2[index], r2[0,0] = r2[0,0], r2[index]
您可以将最大值存储在一个变量中,然后将[0, 0]
元素分配给您在where
中找到的索引,然后将[0, 0]
元素设置为存储的最大值:
maximum = r2.max()
indices = np.where(r2 == maximum)
r2[indices] = r2[0, 0]
r2[0, 0] = maximum
r2
输出:
array([[500. , 63.38075613, 312.87746691],
[375.25164461, 1.00657843, 125.75493382],
[437.6258223 , 250.50328922, 188.12911152]])
这样你就可以替换所有具有max值的元素
#get the max value of the array
max_value = np.max(r2)
#all the element with the max value will be replaced with the first value
r2[r2 == max_value] = r2[0][0]
#put the max value in the first position
r2[0][0] = max_value