How to generate commonly used np.arrays ?
arange+reshape
1 2 |
n = np.arange(0, 30, 2)# start at 0 count up by 2, stop before 30 n = n.reshape(3, 5) # reshape array to be 3x5 |
linspace+resize
1 2 |
o = np.linspace(0, 4, 9) o.resize(3, 3) |
About Resize and Reshape
reshape is not inplace operation and will return an value
resize is inplace operation without feedback
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
>> X = np.random.randn(2, 3) >> X array([[ 1.23077478, -0.70550605, -0.37017735], [-0.61543319, 1.1188644 , -1.05797142]]) >> X.reshape((3, 2)) array([[ 1.23077478, -0.70550605], [-0.37017735, -0.61543319], [ 1.1188644 , -1.05797142]]) >> X array([[ 1.23077478, -0.70550605, -0.37017735], [-0.61543319, 1.1188644 , -1.05797142]]) >> X.resize((3, 2)) >> X array([[ 1.23077478, -0.70550605], [-0.37017735, -0.61543319], [ 1.1188644 , -1.05797142]]) |
ones, zeros eye diag random.randint
In
1 2 3 4 5 6 |
np.ones((3, 2)) np.zeros((2, 3)) np.eye(3)#3维单位矩阵 y = np.array([4, 5, 6]) np.diag(y)#以y为主对角线创建矩阵 np.random.randint(0, 10, (4,3)) |
Out
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
ones: [[ 1. 1.] [ 1. 1.] [ 1. 1.]] zeros: [[ 0. 0. 0.] [ 0. 0. 0.]] eye: [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 0. 1.]] diag: [[4 0 0] [0 5 0] [0 0 6]] randint [[1 3 5] [4 4 3] [9 3 0] [7 0 0]] |
Compound Matrix
In
1 2 3 |
p = np.ones([2, 3], int) np.hstack([p, 2*p])#水平拼接 np.vstack([p, 2*p])#竖直拼接 |
Out
1 2 3 4 5 6 7 8 |
hstack: [[1 1 1 2 2 2] [1 1 1 2 2 2]] vstack: [[1 1 1] [1 1 1] [2 2 2] [2 2 2]] |