本文源码请见我的GitHub
2.2 Numpy数组基础
2.2.1 Numpy数组属性
1 | import numpy as np |
1 | x1 = np.random.randint(10, size = 6) |
1 | print("x3 ,ndim: ", x3.ndim) |
x3 ,ndim: 3
x3 ,shape: (3, 4, 5)
x3 ,ndim: 60
1 | print(x1.dtype) |
int32
1 | #每个数组元素字节大小:itemsize 数组总字节大小:nbtytes; |
itemsize of x1: 4 bytes
nbytes of x2: 48 bytes
1 | '''一般可认为nbytes = itemsize * size''' |
'一般可认为nbytes = itemsize * size'
2.2.2 数组索引:获取单个元素
1 | x1 |
array([5, 0, 3, 3, 7, 9])
1 | x1[0] |
5
1 | x1[4] |
7
1 | x1[-1] |
9
1 | x1[-2] |
7
1 | #多维数组中使用逗号分隔的索引元组获取元素: |
array([[3, 5, 2, 4],
[7, 6, 8, 8],
[1, 6, 7, 7]])
1 | x2[0,0] |
3
1 | x2[2,3] |
7
1 | x2[2,-1] |
7
1 | x2[2,-1] = 12321 |
1 | x2 |
array([[ 3, 5, 2, 4],
[ 7, 6, 8, 8],
[ 1, 6, 7, 12321]])
1 | ''' |
'\nNumpy是固定类型的,浮点插入整型数会被截断\n'
2.2.3 数组切片:获取子数组
1 | x = np.arange(10) |
1 | x |
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
1 | x[:3] |
array([0, 1, 2])
1 | x[:-3] |
array([0, 1, 2, 3, 4, 5, 6])
1 | x[3:] |
array([3, 4, 5, 6, 7, 8, 9])
1 | x[3:7] |
array([3, 4, 5, 6])
1 | x[::2] |
array([0, 2, 4, 6, 8])
1 | x[1::2] |
array([1, 3, 5, 7, 9])
1 | x[::-1] |
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
1 | x2 |
array([[ 3, 5, 2, 4],
[ 7, 6, 8, 8],
[ 1, 6, 7, 12321]])
1 | x2[:2, :3] |
array([[3, 5, 2],
[7, 6, 8]])
1 | x2[:3,::2]#所有行,每隔一列 |
array([[3, 2],
[7, 8],
[1, 7]])
1 | x2[::-1,::-1] #全部逆序 |
array([[12321, 7, 6, 1],
[ 8, 8, 6, 7],
[ 4, 2, 5, 3]])
1 | '''3.获取数组的行和列''' |
'3.获取数组的行和列'
1 | print(x2[:,0]) #x2的第一列 |
[3 7 1]
1 | print(x2[0,:])#第一行 |
[3 5 2 4]
1 | '''4.非副本视图的子数组''' |
'4.非副本视图的子数组'
1 | print(x2) |
[[ 3 5 2 4]
[ 7 6 8 8]
[ 1 6 7 12321]]
1 | x2_sub = x2[:2,:2] |
array([[3, 5],
[7, 6]])
1 | #修改视图也会更改原数组 |
1 | x2_sub[0,1]= 100 |
1 | x2 |
array([[ 3, 100, 2, 4],
[ 7, 6, 8, 8],
[ 1, 6, 7, 12321]])
1 | #5.创建副本 |
1 | #可以通过创建数组的视图之后用copy()实现 |
[[ 99 100]
[ 7 6]]
[[ 3 100 2 4]
[ 7 6 8 8]
[ 1 6 7 12321]] 这里原数组没有被更改
2.2.4 数组的变形
1 | # reshape |
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
1 | #常见的变形是将一个一维数组转为二维的行或列的矩阵 |
array([1, 2, 3])
1 | x.reshape((1,3)) |
array([1, 2, 3])
1 | x[np.newaxis, :]#通过newaxis获得的行向量 |
array([[1, 2, 3]])
1 | #变形成列向量 |
array([[1],
[2],
[3]])
1 | x[:,np.newaxis] |
array([[1],
[2],
[3]])
2.2.5 数组的拼接和分裂
1 | x = np.array([1,2,3]) |
array([1, 2, 3, 3, 2, 1])
1 | z = [1212,344,343] |
array([ 1, 2, 3, 3, 2, 1, 1212, 344, 343])
1 | #分裂 |
1 | x1,x2,x3 = np.split(x,[3,5]) |
1 | print(x1,x2,x3) #索引列表记录的是分裂点的位置 |
[1 2 3] [4 5] [3 2 1]