Numpy and pandas study notes

#导入numpy库
import numpy as np

(1) Create a matrix:

a=np.array([
[1,2,3],
[2,3,4],
[4,5,6]],dtype=np.int64)
function illustrate
np.ones((3,4)) A matrix of all 1s
np.zeros((3,4)) A matrix of all 0s
np.empty((3,4)) A matrix with all elements almost close to 0
np.random.random((3,4)) 3*4 random number matrix (values ​​between 0~1)
np.arange(0,12,1).reshape((3,4)) Left closed and right open, the step size is 2 to generate a list, reshape() changes the row and column shape to 3*4
e.g. linspace (1,10,5) Left closed and right open, 5 segments increase to get the list
a.dtype Element type, int32, int64, float32, float64, etc.

(2) Matrix shape

function illustrate
a.ndim The return is a few-dimensional array
a.size returns the number of elements
a.shape Return the number of rows and columns (m,n)

(3) Matrix operation

operation function
plus minus power ce, c + e, c ** 2
Trigonometric functions np.sin (a)
Transpose np.transpose(A)或A.T
Multiply one by one c=a*b
matrix multiplication c_dot=np.dot(a,b)
sum np.sum(a)
Find the most value np.min(g), np.max(g, axis=1), where axis=0: internal summation of each column, 1: internal summation of each row
Extract elements A[2,:] 、A[2,1] 、A[1,1:3])
output index e.g., argmin (A) 、 e.g., argmax (A)
mean median np.mean(A)、np.median(A)
cumulative difference np.cumsum(A)、np.diff(A)
Sort row by row in ascending order np.sort(A)
print(c<18) Determine which element is less than 18 and greater than or equal to 18
print(np.clip(A,5,9)) The number >9 becomes 9, the number <5 becomes 5, and the middle number remains unchanged
A.flatten() Flatten the matrix A into only one row, A.flat means that the iterator produced by A.flatten() is used for for loops, etc.
A.flatten()
for item in A.flat:
    print(item)

(4) Matrix merging and division
The following functions can realize simultaneous multi-matrix merging, assuming that the A matrix is ​​3*4

function illustrate
np.array([1,1,1]) The output shape is (3,) that there is only one dimension
np.array ([1,1,1]) [:, np.newaxis] Add a dimension in the column direction, the shape is (3,1) or directly use reshape((3,1))
np.vstack((A,B)) Merge vertically
np.hstack((A,B)) merge horizontally
np.concatenate((A,B),axis=0) axis=0 is arranged and merged vertically, axis=1 is merged horizontally
function illustrate
np.split(A,3,axis=0) or np.vsplit(A,3) Split vertically
np.split(A,2,axis=1) or np.hsplit(A,2) split horizontally
np.array_split(A,3,axis=1) The 3*4 matrix is ​​unequally divided into 2 1 1 in the horizontal direction
Published 23 original articles · 25 likes · 863 visits