keepdims=True
时间: 2023-09-06 09:07:09 浏览: 44
The parameter `keepdims=True` is used in NumPy functions like `sum`, `mean`, `min`, and `max` to preserve the dimensions of the input array when performing the operation.
For example, consider a 2D array `arr` of shape (3, 4):
```
import numpy as np
arr = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
```
If we call the `sum` function on this array without `keepdims=True`, the resulting array will be a 1D array with shape `(12,)`:
```
arr_sum = arr.sum()
print(arr_sum.shape) # (12,)
```
However, if we set `keepdims=True`, the resulting array will have the same number of dimensions as the input array, with a size of 1 in the dimensions that were reduced by the operation. For example, if we call `arr.sum(axis=0, keepdims=True)` to sum along the first axis (rows), the resulting array will be a 2D array with shape `(1, 4)`:
```
arr_sum = arr.sum(axis=0, keepdims=True)
print(arr_sum.shape) # (1, 4)
```
Similarly, if we call `arr.sum(axis=1, keepdims=True)` to sum along the second axis (columns), the resulting array will be a 2D array with shape `(3, 1)`:
```
arr_sum = arr.sum(axis=1, keepdims=True)
print(arr_sum.shape) # (3, 1)
```
By setting `keepdims=True`, we can ensure that the resulting array has the same shape as the input array, which can be useful when working with higher-dimensional arrays.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)