Python 中提供了 list 容器,可以当作数组使用。但列表中的元素可以是任何对象,因此列表中保存的是对象的指针,这样一来,为了保存一个简单的列表 [1,2,3]。就需要三个指针和三个整数对象。对于数值运算来说,这种结构显然不够高效。
构建数组
直接从 list 中构建
array 中的参数是数组的数据
x = np.array([2, 3, 4])
x = np.array([[2, 3, 4], [5, 6, 7]])
x = np.array([2, 3, 4], dtype=np.uint8)
x = np.array([2, 3, 4], dtype=np.uint8)
empty, zeros, ones
empty 可以构建形状为 shape 的数组,其值取决于内存原始值。zeros,ones 可以将内存初始化
x = np.empty(shape=100, dtype=np.uint8)
x = np.empty(shape=(10, 10))
x = np.empty(shape=(10, 10), dtype=np.uint16)
x = np.zeros(shape=(10, 10))
x = np.ones(shape=(10, 10))
random
randint 可以构建形状为 size 的数组,其值为 [low, high)
的随机整数
x = np.random.randint(5)
x = np.random.randint(low=2, high=10, size=5)
x = np.random.randint(low=2, high=10, size=(3, 4))
randn 从标准正太分布中返回数值
x = np.random.randn(5, 5)
rand 从 [0, 1) 中随机选择
x = np.random.rand(5, 5)
选择数组元素
...
和 :
...
和 :
用来快速操作 numpy
x = np.random.randn(3, 3, 2)
x[..., 1]
表示前两维保持不变,最后一维取 1 号元素,变成 3*3 矩阵,效果等同于 x[:, :, 1]
x[1, ...]
表示第一维取 1 号元素,其余维度保持不变,变成 3*2 矩阵,效果等同于 x[1, :, :]
,x[1]
x[1, ..., 1]
表示第一维和最后一维取 1 号元素,其余维度保持不变,变成 3 维矩阵,效果等同于 x[1, :, 1]
list
使用 list 操作 array,返回值依旧是 array
x = np.random.randn(10, 5)
a = [1, 3, 5]
x[a]
x[a, :]
x[:, a]
x[..., a]
数组拓展维度
打开 ipython
x = np.random.randn(5)
x.shape # (5,)
y = np.expand_dims(x, axis=0)
y.shape # (1,5)
y = np.expand_dims(x, axis=-1)
y.shape # (5,1)