gpt4 book ai didi

python - 替换numpy中的max和min,second max和second min等

转载 作者:行者123 更新时间:2023-12-05 03:33:41 24 4
gpt4 key购买 nike

我有一个 numpy 数组,我想在某种意义上反转它,我想交换最大值和最小值、第二个最大值和第二个最小值等等。

arr = [1, 2, 1, 3, 2, 4, 1, 4]
# Output should be [4, 3, 4, 2, 3, 1, 4, 1]

arr = [4, 4, 1, 2]
# Output should be [1, 1, 4, 2]

有没有办法对其进行矢量化?

最佳答案

假设您想要交换唯一值,您可以使用 np.unique 获取排序唯一值和索引在排序的唯一值中选择的唯一值。然后,您可以还原唯一值数组以交换最小值和最大值。之后,索引将引用交换的最小-最大值,因此您可以使用间接索引 提取它们。下面是生成的完全矢量化代码:

arr = np.array([1, 2, 1, 3, 2, 4, 1, 4])
uniqueItems, ids = np.unique(arr, return_inverse=True)
out = uniqueItems[::-1][ids]
# out: [4, 3, 4, 2, 3, 1, 4, 1]

关于python - 替换numpy中的max和min,second max和second min等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70307968/

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