numpy的ndarray如何创建
时间: 2023-10-04 20:05:09 浏览: 112
你可以使用NumPy库中的`ndarray`类来创建多维数组。以下是一些常见的创建`ndarray`的方法:
1. 使用`numpy.array`函数从Python列表或元组创建`ndarray`:
```python
import numpy as np
my_list = [1, 2, 3, 4, 5]
arr = np.array(my_list)
print(arr)
```
2. 使用`numpy.zeros`函数创建一个全是0的`ndarray`:
```python
import numpy as np
shape = (2, 3) # 指定数组的形状(行数和列数)
arr = np.zeros(shape)
print(arr)
```
3. 使用`numpy.ones`函数创建一个全是1的`ndarray`:
```python
import numpy as np
shape = (2, 3) # 指定数组的形状(行数和列数)
arr = np.ones(shape)
print(arr)
```
4. 使用`numpy.arange`函数创建一个按指定步长递增的`ndarray`:
```python
import numpy as np
start = 0
stop = 10
step = 2
arr = np.arange(start, stop, step)
print(arr)
```
这只是一些创建`ndarray`的方法,NumPy还提供了许多其他函数和选项来创建不同类型和形状的数组。你可以查阅NumPy文档来了解更多详细信息。
阅读全文
相关推荐















