1. import numpy as np
  2. a = np.array([1, 2, 3, 4])
  3. b = np.array([5, 6, 7, 8])
  4. c = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
  5. print(a)
  6. print(b)
  7. print(c)

image.png

1. 列表转ndarray

  1. b0 = [[1, 2, 3, 4], [5, 6, 7, 8]]
  2. b = np.array(b0)
  3. print(b)

image.png

2. 新建4维列表,并指定每一维的大小

  1. print('指定4维列表,每一维的大小分别为1,2,3,4')
  2. a = np.ndarray([1, 2, 3, 4])
  3. print(a)

image.png

3. 生成等间隔数组

  1. a = np.arange(0, 1, 0.1)
  2. print(a)
  3. [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

4. 生成等差数组

  1. # 方式一
  2. b = np.linspace(0, 1, 10)
  3. print(b)
  4. # 方式二
  5. print('endpoint为True的时候包含终止数字,False不包含终止数字')
  6. c = np.linspace(0, 1, 10, endpoint=False)
  7. print(c)
  8. [0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
  9. 0.66666667 0.77777778 0.88888889 1. ]
  10. endpointTrue的时候包含终止数字,False不包含终止数字
  11. [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

5. 生成等比数组

生成等比数组使用的是logspace函数,函数格式如下:

  1. 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. ]

  1. <a name="iScIV"></a>
  2. # 6. 生成空数组
  3. ```python
  4. print('空数组,由随机值填充')
  5. a = np.empty(2, np.int)
  6. print(a)
  7. b = np.empty((2, 3))
  8. print(b)
  9. 空数组,由随机值填充
  10. [ 0 1079574528]
  11. [[4.783e-321 4.783e-321 4.980e-321]
  12. [4.980e-321 4.822e-321 4.822e-321]]

7. 生成全0数组

  1. c = np.zeros(3)
  2. print(c)
  3. [0. 0. 0.]

8. 生成指定值数组

  1. d = np.full(4, np.pi)
  2. print(d)
  3. [3.14159265 3.14159265 3.14159265 3.14159265]