目录
- import numpy as np
-
- x = np.empty(shape=(3, ), dtype=int, order='C')
- x = np.empty(shape=(3, 2), dtype=int, order='C')
- y = np.empty_like(x)
- # 参数order表示按列排,Colum
empty方法会在内存中开辟一块储存矩阵的空间,但是并不会对其赋值,empty生成的矩阵中每一个元素的值都是其分配时所占内存id的原始值。
格式:full(shape,fill_value)。
- import numpy as np
-
- x = np.full(shape=(3, 3), fill_value=8, dtype=int)
- print(x)
- # [[8 8 8]
- # [8 8 8]
- # [8 8 8]]
单位阵必定是一个方阵,且主对角元素均为1。另外identity方法也可以创建单位矩阵。
- import numpy as np
-
- n1 = np.eye(3, dtype=int)
- n2 = np.identity(3, dtype=int)
- print(n1, '\n\n\n', n2)
- # [[1 0 0]
- # [0 1 0]
- # [0 0 1]]
格式:np.linspace(start, stop, num, endpoint=True, retstep=False, dtype=None)。
参数解释如下:

- import numpy as np
-
- x = np.linspace(1, 10, 10)
- print(x)
- # endpoint=True 间隔 end-start/(num-1)
- x = np.linspace(1, 6, 5, endpoint=True)
- print(x)
- # endpoint=False 间隔 end-start/num
- x = np.linspace(1, 6, num=5, endpoint=False)
- print(x)
- # [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
- # [1. 2.25 3.5 4.75 6. ]
- # [1. 2. 3. 4. 5.]
格式:np.logspace(start, stop, num=50,endpoint=True, base=10.0, dtype=None)。
参数解读如下:

- import numpy as np
-
- x = np.logspace(start=0, stop=9, num=10, base=2) # 序列的起始值为:base ** start
- # [ 1. 2. 4. 8. 16. 32. 64. 128. 256. 512.]
- print(x)
- x = np.logspace(0, 3, num=4)
- print(x)
与python自带的list列表切片一模一样。ndarray数组可以基于0 - n 的下标进行索引,并设置 start, stop 及 step 参数,从原数组中切割出一个新数组。
- import numpy as np
-
- x = np.arange(10)
- print(f'x is{x}')
- print(x[2],
- x[2:7:2],
- x[2:], sep='\n')
- # x is[0 1 2 3 4 5 6 7 8 9]
- # 2
- # [2 4 6]
- # [2 3 4 5 6 7 8 9]
另外切片也支持负索引。
- import numpy as np
- x = np.arange(10)
- x[-2]
- x[-2:]

使用[][]来访问。
- import numpy as np
-
- a = np.arange(0, 12).reshape(3, 4)
- print('获取第二行')
- print(a[1])
- print('获取第三行第二列')
- print(a[2][1])
使用坐标获取数组[x,y]。
- import numpy as np
-
- a = np.arange(0, 20).reshape(4, 5)
- print('所有行的第二列')
- print(a[:, 1])
- print('获取第三行第二列')
- print(a[2, 1])
- print('奇数行的第一列')
- print(a[::2, 0])
- print('同时获取第三行第二列,第四行第一列')
- print(a[(2, 3), (1, 0)])
- # 所有行的第二列
- # [ 1 6 11 16]
- # 获取第三行第二列
- # 11
- # 奇数行的第一列
- # [ 0 10]
- # 同时获取第三行第二列,第四行第一列
- # [11 15]
负索引的使用。
- import numpy as np
-
- a = np.arange(0, 20).reshape(4, 5)
- print('获取最后一行')
- print(a[-1])
- print('行与行倒序')
- print(a[::-1])
- print('行列都倒序')
- print(a[::-1, ::-1])
- # 获取最后一行
- # [15 16 17 18 19]
- # 行与行倒序
- # [[15 16 17 18 19]
- # [10 11 12 13 14]
- # [ 5 6 7 8 9]
- # [ 0 1 2 3 4]]
- # 行列都倒序
- # [[19 18 17 16 15]
- # [14 13 12 11 10]
- # [ 9 8 7 6 5]
- # [ 4 3 2 1 0]]
数组的复制。
- import numpy as np
-
- a = np.arange(1, 13).reshape(3, 4)
- sub_array = a[:2, :2]
- sub_array[0][0] = 1000
- print(sub_array)
- sub_array = np.copy(a[:2, :2]) # np.copy()
- sub_array[0][0] = 2000
- print(sub_array)