import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
c = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a)
print(b)
print(c)
1. 列表转ndarray
b0 = [[1, 2, 3, 4], [5, 6, 7, 8]]
b = np.array(b0)
print(b)
2. 新建4维列表,并指定每一维的大小
print('指定4维列表,每一维的大小分别为1,2,3,4')
a = np.ndarray([1, 2, 3, 4])
print(a)
3. 生成等间隔数组
a = np.arange(0, 1, 0.1)
print(a)
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
4. 生成等差数组
# 方式一
b = np.linspace(0, 1, 10)
print(b)
# 方式二
print('endpoint为True的时候包含终止数字,False不包含终止数字')
c = np.linspace(0, 1, 10, endpoint=False)
print(c)
[0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
0.66666667 0.77777778 0.88888889 1. ]
endpoint为True的时候包含终止数字,False不包含终止数字
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
5. 生成等比数组
生成等比数组使用的是logspace函数,函数格式如下:
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
- start:序列的起始值为:base ** start
- stop:序列的终止值为:base ** stop。如果endpoint为true,该值包含于数列中
- num:要生成的等步长的样本数量,默认为50
- endpoint:该值为 true 时,数列中中包含stop值,反之不包含,默认是True。
- base:对数 log 的底数。
- dtype:ndarray 的数据类型 ```python d = np.logspace(0, 2, 5) print(d)
[ 1. 3.16227766 10. 31.6227766 100. ]
<a name="iScIV"></a>
# 6. 生成空数组
```python
print('空数组,由随机值填充')
a = np.empty(2, np.int)
print(a)
b = np.empty((2, 3))
print(b)
空数组,由随机值填充
[ 0 1079574528]
[[4.783e-321 4.783e-321 4.980e-321]
[4.980e-321 4.822e-321 4.822e-321]]
7. 生成全0数组
c = np.zeros(3)
print(c)
[0. 0. 0.]
8. 生成指定值数组
d = np.full(4, np.pi)
print(d)
[3.14159265 3.14159265 3.14159265 3.14159265]