numpy 计算极值点
时间: 2023-07-29 07:12:19 浏览: 52
如果要计算 numpy 数组的极值点,可以通过 `numpy.argmax` 和 `numpy.argmin` 函数实现。其中 `numpy.argmax` 函数返回数组中最大值的索引,而 `numpy.argmin` 函数返回数组中最小值的索引。下面是一个例子,展示如何计算数组的最大值和最小值及其所在的位置:
```
import numpy as np
a = np.array([1, 2, 3, 2, 1])
max_idx = np.argmax(a)
min_idx = np.argmin(a)
max_val = a[max_idx]
min_val = a[min_idx]
print("Max value: ", max_val, ", at index: ", max_idx)
print("Min value: ", min_val, ", at index: ", min_idx)
```
输出结果为:
```
Max value: 3 , at index: 2
Min value: 1 , at index: 0
```
如果要在多维数组中计算极值点,可以指定 `axis` 参数来计算某个轴向上的极值点。例如,计算二维数组 b 每一列的最大值和最小值及其所在的位置:
```
import numpy as np
b = np.array([[1, 2, 3], [4, 5, 6], [7, 0, 9]])
max_idx = np.argmax(b, axis=0)
min_idx = np.argmin(b, axis=0)
max_val = b[max_idx, np.arange(b.shape[1])]
min_val = b[min_idx, np.arange(b.shape[1])]
print("Max values: ", max_val, ", at indices: ", max_idx)
print("Min values: ", min_val, ", at indices: ", min_idx)
```
输出结果为:
```
Max values: [7 5 9] , at indices: [2 1 2]
Min values: [1 0 3] , at indices: [0 2 0]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)