np.expand_dims
时间: 2023-09-09 19:09:51 浏览: 79
The numpy function np.expand_dims() is used to add an extra dimension to an existing numpy array.
Syntax:
```python
np.expand_dims(arr, axis)
```
Parameters:
- arr: the numpy array to be expanded
- axis: the axis along which the new dimension will be added. If axis is not specified, a new dimension will be added at the beginning of the array.
Returns:
- A new numpy array with the same data as the original array, but with an additional dimension inserted.
Example:
```python
import numpy as np
arr = np.array([1, 2, 3])
print(arr.shape) # Output: (3,)
# Add a new dimension to the array
new_arr = np.expand_dims(arr, axis=0)
print(new_arr.shape) # Output: (1, 3)
# Add a new dimension to the array at the end
new_arr2 = np.expand_dims(arr, axis=1)
print(new_arr2.shape) # Output: (3, 1)
```
In this example, we first define a numpy array `arr` with shape (3,). We then use np.expand_dims() to add a new dimension to the array at axis=0 and axis=1. The resulting arrays are `new_arr` with shape (1, 3) and `new_arr2` with shape (3, 1).
阅读全文