NumPy Introduction 1
Array
First step: Import numpy
1 | import numpy as np |
Multi-dimensions array
1 | np.array([range(i,i+3)for i in[2,4,6]]) |
Creating repeated array
create an array with length10,and all the values are 0.
1 | np.zeros(10,dtype=int) |
create an array which is 3x5,type is float,and all the values are 1.
1 | np.ones((3,5),dtype=float) |
create an array which is 3x5,and all the values are 3.14.
1 | np.full((3,5),3.14) |
create an array with 5 numbers from 0~1 uniformly
1 | np.linspace(0,1,5) |
create an array which is 3x3 with random number
1 | np.random.random((3,3)) |
create an array which is 3x3 with random normal number from 0~1
1 | np.random.normal(0,1,(3,3)) |
create an array which is 3x3 with random integer between1and 10
1 | np.random.randint(0,10,(3,3)) |
create an array which is 4x4 ,its numbers have only one digit
1 | np.eye(4) |
create an array with 3 random number from the storage
1 | np.empty(3) |
The factors of array
ndim(the dimension),shape and size
1 | np.random.seed(0) |
Get one element
1 | x1 |
1 | x1[0] |
From the end
1 | x1[-1] |
Use the comma
1 | x2 |
1 | x2[0,0] |
1 | x2[2,-1] |
Change element(x1=([5, 0, 3, 3, 7, 9]))
1 | x1[0]=3.14 |
slice
1 | x = np.arange(10) |
multi-dimension:
1 | x2=array([[12, 5, 2, 4], |
.copy()
1 | x2_sub_copy = x2[:2, :2].copy() |
.reshape()
1 | grid = np.arange(1, 10).reshape((3, 3)) |
1 | x = np.array([1, 2, 3]) # 通过变形获得的行向量 |
.concatenate() (combine arrays)
1 | x = np.array([1, 2, 3]) |
1 | z = [99, 99, 99] |
.split()
1 | x = [1, 2, 3, 99, 99, 3, 2, 1] |
np.hsplit & np.vsplit
1 | grid = np.arange(16).reshape((4, 4)) |