gpt4 book ai didi

python - 除了 NumPy 矩阵中的特定列之外,是否有一种有效的方法来获取最大元素的位置?

转载 作者:行者123 更新时间:2023-12-04 02:34:28 26 4
gpt4 key购买 nike

例如,有一个二维 Numpy 矩阵 M :

[[1,10,3],
[4,15,6]]
除了 M[:][1] 之外的最大元素是 6 ,其位置为 (1,2) .所以答案是 (1,2) .
非常感谢您的帮助!

最佳答案

单程:

col = 1
skip_col = np.delete(x, col, axis=1)
row, column = np.unravel_index(skip_col.argmax(), skip_col.shape)
if column >= col:
column += 1
翻译:
  • 删除列
  • 找到最大参数(argmax 给出扁平结果,unravel_index 给出二维数组中的位置)
  • 如果该列大于或等于跳过的一列,则添加一个

  • 关注 Dunes comment ,我喜欢这个建议。它的行数几乎相同,但不需要副本(如 np.delete)。因此,如果您受内存限制(如在真正的大数据中):
    col = 1
    row, column = np.unravel_index(x[:, :col].argmax(), x[:, :col].shape) # left max, saving a line assuming it's the global max, but less readable
    right_max = np.unravel_index(x[:, col+1:].argmax(), x[:, col+1:].shape)
    if x[right_max] > x[row, column]:
    row, column = right_max
    column += col

    关于python - 除了 NumPy 矩阵中的特定列之外,是否有一种有效的方法来获取最大元素的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62485600/

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