简体   繁体   English

如何从二维数组+最大值索引中获取每一列的最大值

[英]how to get the max of each column from an 2d array + index of the max value

I have for example 我有例如

A = [[1 2 3 4 5]
     [2 4 5 8 7]
     [9 8 4 5 2]
     [1 2 4 7 2]
     [5 9 8 7 6]
     [1 2 5 4 3]]

So the shape of A = (5,6) What I want is now the max of each column and return the result as eg: 因此,A =(5,6)的形状现在是每列的最大值,并返回结果,例如:

A = [[9 9 8 8 7]] with as shape (5,1) A = [[9 9 8 8 7]] ,形状为(5,1)

And at the same time I would like to receive the index of the max value from each column. 同时,我想从每一列接收最大值的索引。

Is this possible? 这可能吗? I don't find immediatly the sollution within the np.array basic doc. 我没有在np.array基本文档中立即找到解决方案。

You could use ndarray.max() . 您可以使用ndarray.max()

The axis keyword argument describes what axis you want to find the maximum along. axis关键字参数描述您要沿着哪个轴找到最大值。

keepdims=True lets you keep the input's dimensions. keepdims=True可让您保留输入的尺寸。

To get the indizes of the maxima in the columns, you can use the ndarray.argmax() function. 要获取列中最大值的信息,可以使用ndarray.argmax()函数。 You can also pass the axis argument ot this function, but there is no keepdims option. 您也可以通过此函数传递axis参数,但是没有keepdims选项。

In both commands axis=0 describes the columns, axis=1 describes the rows. 在两个命令中, axis=0描述列,而axis=1描述行。 The standard value axis=None would search the maximum in the entire flattened array. 标准值axis=None不会在整个展平数组中搜索最大值。

Example: 例:

import numpy as np

A = np.asarray(
    [[1, 2, 3, 4, 5],
     [2, 4, 5, 8, 7],
     [9, 8, 4, 5, 2],
     [1, 2, 4, 7, 2],
     [5, 9, 8, 7, 6],
     [1, 2, 5, 4, 3]])
print(A)

max = A.max(axis=0, keepdims=True)
max_index = A.argmax(axis=0)

print('Max:', max)
print('Max Index:', max_index)

This prints: 打印:

[[1 2 3 4 5]
 [2 4 5 8 7]
 [9 8 4 5 2]
 [1 2 4 7 2]
 [5 9 8 7 6]
 [1 2 5 4 3]]
Max: [[9 9 8 8 7]]
Max Index: [2 4 4 1 1]

you can use numpy as well. 您也可以使用numpy。

Example: 例:

import numpy as np

A = [[1, 2, 3, 4, 5],
 [2, 4, 5, 8, 7],
 [9, 8, 4, 5, 2],
 [1, 2, 4, 7, 2],
 [5, 9, 8, 7, 6],
 [1, 2, 5, 4, 3]]

print(A)

A=np.array(A)

print(A.max(axis=0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM