Numpy 使用
引入 :import numpy as np
0.1.1 reshape改变数组的形状
arr.reshape()
原始数组的大小必须和变形后数组的大小一致。
只是在逻辑上改变数组的形状(相当于视图)
为了确保大家都能生成一样的数组, 我们先设置随机数种子
np.random.seed(0)
x1 = np.random.randint(10, size=6) # 一维数组
x2 = np.random.randint(10, size=(3, 4)) # 二维数组
x3 = np.random.randint(10, size=(3, 4, 5)) # 三维数组
x1
array([5, 0, 3, 3, 7, 9])
x1.reshape((2,3))
array([[5, 0, 3],
[3, 7, 9]])
技巧:在使用 reshape 时,可以将其中的一个维度指定为 -1,Numpy 会自动计算出它的真实值
x2.reshape(3,-1)
array([[3, 5, 2, 4],
[7, 6, 8, 8],
[1, 6, 7, 7]])
**
0.1.5 拉伸成一维数组(数组的平铺)
arr.ravel()
**x2 = np.random.randint(10, size=(3, 4)) # 二维数组
array([[3, 5, 2, 4],
[7, 6, 8, 8],
[1, 6, 7, 7]])
不管原来是几维, 都展开成一维数据
x2.ravel()
array([3, 5, 2, 4, 7, 6, 8, 8, 1, 6, 7, 7])
0.1.6 转置 arr.T
交换数据的行和列
x2.shape
(3, 4)
x2.T.shape
(4, 3)