Introduction to the basic usage of Numpy

import numpy as np 
'''
Array Basic Operations
    np.array() creates an array
    arr.shape returns the size (rows, columns) of the array arr
    arr.reshape(size) Change the size of the array, the number of elements should be consistent
    arr.dtype() View element type dtype

'''
import numpy as np
from numpy.random import randn
'''
Common functions:
    np.arange(a,b,step=) creates an arithmetic array
    np.sqrt(arr) square root of each element in the array
    np.exp(arr) each element in the array takes the exponent of e
    randn(size()) randomly generates a normally distributed array of size()
    np.maximum(x,y) Each element takes the larger of x and y
    np.where(cond,x,y) ternary expression x if cond else y
'''
import numpy as np
'''
Mathematical Statistical Methods
sum summation
mean find the mean
std standard deviation
var variance
min,max minimum value, maximum value
argmin, argmax min, max so
cumsum cumulative sum of all elements
cumprod cumulative product of all elements
'''
'''
Boolean operations: Boolean values ​​are coerced to 1 (True), 0 (False)
any: used to test if True exists in the array
all: Check if the elements in the array are all True
'''
'''
sort
sort: sort is handled in the array itself, if the original array is still useful
       you need to copy and save the array
'''
'''
unique
unique(x) computes the unique elements in x and returns an ordered result
intersect1d(x,y) Calculate the common elements of x,y and return the ordered result
union1d(x,y) computes the union of x,y and returns an ordered result
in1d(x,y) Whether the element of x is contained in y, returns boolean
setdiff1d(x,y) The difference of the set, the element is in and no longer in y
setxor1d(x,y) Symmetric difference of sets, i.e. elements in one element but not in both arrays
'''
'''
array of files
np.save('file_name',arr)
    By default, arrays are saved in uncompressed raw binary format with the extension
    .npy file in
np.load('file_name.npy')
    read array from file
np.savez('file_name.npz',a=arr1,b=arr2,...)
    savez compresses multiple files into a single folder, wrapping the array with keyword arguments
    form incoming. load. npz file, you get a dictionary-like object
'''
'''
read text file
    load.txt('file_name.txt',delimiter=',')
save array to file
    savetxt('file_name',arr1)
'''
'''
Linear Algebra
    matrix multiplication
    Matrix factorization
    determinant
    ...
matrix multiplication
    dot(x,y) the multiplication of matrix x and matrix y
        x = np.array([[1,2,3],[4,5,6]])
        y = np.array([[1,2],[3,4],[5,6]])
        np.dot(x,y)
Transpose of a matrix:
    Transpose of xT x
Inverse of a matrix:
    from numpy.linalg import inv,qr
    inv(x) inverse of x
QR decomposition
    q,r = qr(x) qr decomposition of x
Summarize
    diag returns the diagonal elements of a square matrix in one bit
                Or convert a one-bit array to a matrix (off-diagonal elements are 0)
    dot matrix multiplication
    trace trace, sum of diagonal elements
    determinant of the det matrix
    eig eigenvalues ​​and eigenvectors
    inv inverse
    pinv Moore-Penrose pseudoinverse
    qr qr decomposition
    svd svd decomposition
    slove solve the equation Ax=b
    lstsq computes the least squares solution

'''
'''
Generation of random numbers
Functions in the numpy.random module
    seed determines the seed of the random number generator
    permutation returns a random permutation of a sequence or returns a randomly sorted range
    shuffle sorts a sequence randomly
    rand produces uniformly distributed sample values
    randint randomly picks an integer from a given range of upper and lower bounds
    randn produces sample values ​​that are normally distributed (mean 0, standard deviation 1), similar to the matlab excuse
    binomial produces binomial sample values
    normal produces normally distributed sample values
    beta yields sample values ​​from a beta distribution
    chisquare produces sample values ​​from a chi-square distribution
    gamma produces sample values ​​from a Gamma distribution
    unifrom produces uniformly distributed sample values
'''
' ****************An example---random walk python implementation ******************** '
import numpy as np
from numpy.random import randn

import random position = 0 walk = [position] steps = 1000 for i in range(steps): step = 1 if random.randint(0,1) else -1 position += step walk.append(position) ' numpy implementation ' nsteps = 1000 draws = np.random.randint(0,2,size= nsteps) steps = np.where(draws>0,1,-1) walks = steps.cumsum() print(walks.min()) print(walks.max()) n1 = (np.abs(walks)>=10).argmax() print(n1) ' ************simulate multiple random walks at once ************* ' nwalks = 5000 nsteps = 1000 draws = np.random.randint(0,2,size=(nwalks,nsteps)) steps = np.where(draws>0,1,-1) walks = steps.cumsum(1) print(walks.max(),walks.min())

This article refers to the book "Data Analysis with Python"

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325109875&siteId=291194637