This article is used to learn the basic usage of the Python toolkit Numpy! ! !
import numpy as np #from numpy import * # store data in txt file arr=np.arange(3) np.savetxt("array.txt",arr) #Read the data in the txt file in the form of a matrix or array arr=np.loadtxt('array.txt') print(arr) #arange function creates an array of 0-n integers, accepts 1, 2, 3 arguments similar to range() print( np.arange(1,5,2) ) # Array the list print( np.array([0,1,2,3,4]) ) #Create a three-dimensional array, similar to the relationship between sheet and row and column in Execel print( np.arange(24).reshape(2,3,4) ) #Get the data type in the array, the number of array elements, and get the dimension of the array arr = np.array([np.arange(6),np.arange(6)]) print( arr.dtype ) print( arr.size ) print( arr.shape ) #Customize the array of heterogeneous data types, customize the data type of each element of the array np.dtype([('name',np.str_,40),('age',np.int32),('weight',np.float32)]) print( np.array([('liyu',23,68.1)]) ) #Slice operation of one-dimensional array, select elements from subscript 0-5, step size is 2, negative subscript flips the array arr = np.arange(6) print( arr[:5:2] ) print( arr[::-1] ) #Multidimensional array slicing operation, select all rows and columns in the first sheet arr = np.arange(24).reshape(2,3,4) print( arr[0,::] ) print( arr[0,...] ) # Flatten multidimensional array with ravel function or flatten function arr = np.arange(9).reshape(3,3) print( arr.ravel() ) print( arr.flatten() ) #Transpose of multidimensional array 4x3x2 print( arr.transpose() ) print( arr.T ) #Array of horizontal combination, vertical combination, depth combination (3,3) -> (3,3,2) print( np.hstack((arr,arr)) ) print( np.c_[arr,arr] ) print( np.concatenate((arr,arr),axis=1) ) print( np.vstack((arr,arr)) ) print( np.concatenate((arr,arr),axis=0) ) print( np.dstack((arr,arr)) ) #Horizontal division, vertical division, depth division of the array print( np.hsplit(arr,3) ) print( np.split(arr,3,axis=1) ) print( np.vsplit(arr,3) ) print( np.split(arr,3,axis=0) ) #NumPy array converted to Python list print( arr.tolist() ) #Array weighted average, each element has a corresponding weight arr = np.arange(3) print( np.average(arr) ) print( np.average(arr,weights=arr) ) #arithmetic mean, max, min, print( np.mean(arr) ) print( arr.mean() ) print( np.max(arr) ) print (np.min (arr)) #range, median, variance, covariance, logarithm, print( np.ptp(arr) ) print( np.median(arr) ) print (np.var (arr)) print( np.mean((arr-arr.mean())**2) ) print (np.cov (arr, arr)) print (np.log (arr)) #Sort from small to large, difference between adjacent elements, square root, exponent, factorial, sign function print( np.msort(arr) ) print( np.diff(arr) ) print( np.sqrt(arr) ) print( np.exp(arr) ) print (arr.cumprod ()) print( np.sign(arr) ) The #where function returns the index in the vector that is greater than the threshold, and the take function extracts the corresponding element for i in range(len(arr)): indices=np.where(arr>0) np.take(arr,indices) for i,j in enumerate(arr): if i>0: print(j) print( indices ) print( np.take(arr,0) ) #linspace function, returns an array evenly distributed in the specified range print( np.linspace(0,1,5) ) #argmax function returns the subscript corresponding to the maximum value in the array, the minimum value print( np.argmax(arr) ) print( np.argmin(arr) ) #extract function extracts elements from an array based on generated conditions condition=(arr%2)==0 print( np.extract(condition,arr) ) # extract non-zero elements from the array print( np.nonzero(arr) ) # Normalize processing print( arr/arr.sum() ) #Create identity matrix, zero matrix, 1 matrix print( np.eye(3) ) print( np.zeros(3) ) print( np.ones(3) ) #Create a matrix with spaces between elements and semicolons between rows Mat=np.mat('1 2 3;4 5 6;7 8 9') print( type(Mat) ) #View the diagonal elements of the matrix, calculate the trace, and calculate the correlation coefficient print( Mat.diagonal() ) print( Mat.trace() ) print (np.corrcoef (Mat, Mat)) #Transpose matrix, inverse matrix, compound matrix, create the same zero matrix as Mat print( Mat.T ) print( Mat.I ) print( np.linalg.inv(Mat) ) print (np.bmat ('Mat Mat; Mat Mat')) print( np.zeros_like(Mat) ) #Column sum, store the result of the intermediate operation print( np.add.reduce(Mat) ) print( np.add.accumulate(Mat) ) #Division operation, division only retains integers, division retains decimals print (np.divide (Mat, Mat)) print (np.true_divide (Mat, Mat)) #modulo operation, the remaining function mode function% is equivalent, the fmod function makes the positive and negative of the remainder determined by the dividend print( np.remainder(Mat,Mat) ) print( np.fmod(Mat,2) )#The second parameter is the divisor #Bit operation, xor inequality operator, and operator print( -Mat ) print (Mat ^ Mat) print (np.less (np.bitwise_xor (Mat, Mat), 0)) print( (Mat&Mat)==0 ) print( np.equal(np.bitwise_and(Mat,Mat),0) ) The #np.random module generates an array of random numbers print( np.random.random(5) ) print( np.random.randint(5,size=5) ) #Get random numbers in the interval [0,1) and return an array with 2 rows and 4 columns print( np.random.rand(2,4) ) Function of the #np.linalg module to solve a system of linear equations A = Matt b=np.ones(Mat.shape[0]) x=np.linalg.solve(A,b) print( x ) print( np.dot(A,x) ) # Solve for eigenvalues and eigenvectors, returned as a tuple eigenvalues,eigenvectors=np.linalg.eig(A) # Solve singular value decomposition U,Sigma,V=np.linalg.svd(A,full_matrices=False) print( U*np.diag(Sigma)*V ) # Solve the generalized inverse matrix print( np.linalg.pinv(A) ) # determinant print (np.linalg.det (A))
References:
1. "Numpy Learning Guide"