当前位置:网站首页>Numpy numerical calculation basis
Numpy numerical calculation basis
2022-06-12 12:29:00 【Great sunflower Princess】
Catalog
3, Conversion of array data type
3.1,np. data type ( Data objects )
3.2, Data objects .astype(np. data type )
4.1, Index and slice of arrays
4.3, Flattening and linking of arrays
4.4, Processing of array elements
5.1,random function : Generate [0,1) The random number in
5.2,rand function : Generate uniformly distributed [0,1) The random number in
5.3,randn function : Generating random numbers that obey normal distribution
5.4,randint function : Generate random numbers with given upper and lower bounds
5.5,choice function : Random sampling from a list or array
5.6,random The common random number generation function of the module
2, The vector product of a matrix
3, The quantity product of a matrix
1,save Function is to save an array of data in binary format
2,savez Function can save multiple arrays to a file
3,load The function reads data from a binary file
4,savetxt() Function to write an array to a delimited text file .
5,loadtxt() Function to load a file into a two-dimensional array .
5、 ... and ,numpy Statistical analysis in
3, Repetition and de duplication
One ,Numpy The concept of
Numpy It is a basic module for data scientific computing , It can not only complete the task of scientific calculation , And can be used as an efficient multidimensional data container , Can be used to store and process large matrices ,Numpy Data container can store any type of data , This makes Numpy Can quickly integrate various data .
Two , Array
1, Properties of array
| attribute | explain |
|---|---|
| ndim | return int, Represents the dimension of the array |
| shape | return tuple. Represents the size of an array , about n That's ok m Columns of the matrix , Shape is (n,m) |
| size | return int, Represents the total number of array elements , Equal to the product of array shape |
| dtype | return data-type, Describes the type of elements in an array |
| itemsize | return int, Represents the size of each element of the array ( In bytes ) |
2, Array creation
2.1 array function
Used to create one-dimensional or multi-dimensional arrays .np.array(object,dtype,ndim)
| Parameter name | explain |
|---|---|
| object | Used to receive arrays , Represents the array you want to create , No default |
| dtype | receive data-type, Represents the data type required by the array , The default is None |
| ndim | receive int. Specifies the minimum dimension that the generated array should have , The default is None |
# np.array Generate one dimensional array
arr1=np.array([1,2,3,4])# np.array Generate a two-dimensional array
arr2=np.array([[1,2,3,4],[4,5,6,7]])2.2 arrange function
Be similar to Python Self contained function range, By specifying the starting value 、 Final value and step size to create a one-dimensional arithmetic array . The created array does not contain a final value . The default step size is 1.
# np.arrange Create array
arr=np.arange(1,10)2.3 linspace function
By specifying the starting value 、 Final value and number of elements to create a one-dimensional arithmetic array . The created array contains the final value .
# adopt np.linspace The creation start value is 1, The final value is 10, The number is 5 One dimensional arithmetic array of .
arr=np.linspace(1,10,5)2.4 logspace function
And linspace Function similar to , But what it creates is an isometric sequence
# adopt np.logspace The creation start value is 1, The final value is 10, The number is 5 One dimensional proportional array of .
arr=np.logspace(1,10,5)2.5 zeros function
Creates an all zero array of the specified length or shape
# Create a length of 2 One dimensional all zero array
arr=np.zeros(2)# Create an all zero array of three rows and four columns
arr=np.zeros((3,4))2.6 ones function
Creates an entire array of the specified length or shape
# Create a length of 2 One dimensional full 1 Array
arr=np.ones(2)# Create three rows and four columns of full 1 Array
arr=np.ones((3,4))2.7 eye function
The elements used to create the main diagonal of the build are 1, The other elements are 0 Array of . Similar identity matrix
# Create the elements on the main diagonal of four rows and four columns as 1, The other elements are 0 Array of
arr=np.eye(4)2.8 diag function
Create diagonal matrix , That is, all the elements except the diagonal are 0.
# Create diagonal elements as 1 and 3, The other elements are 0 Diagonal matrix of .
arr=np.diag([1,3])3, Conversion of array data type
3.1,np. data type ( Data objects )
Create an array and see its data type
arr3=np.arange(1,10)
arr3.dtypeadopt np. data type ( Data objects ) The way to change its data type .
arr3=np.int64(arr3)The screenshot of the code running is as follows :
3.2, Data objects .astype(np. data type )
arr3.astype(np.int32)The screenshot of the code running is as follows :
4, Array processing
4.1, Index and slice of arrays
4.1.1 One dimensional array index : Array name [m:n], among m,n Subscript array elements
arr=np.arange(1,10)
arr[0:2]The operation results are as follows :
4.1.2 One dimensional array slices : Array name [start,end,step],( Semi open interval )
arr[0:3:1]The operation results are as follows :
4.1.3 2d array slice : Array name [ Row index , Column index ], Semi open interval
Create a 2D array , The truncated row index is equal to 0 An array consisting of all the following rows and all the columns after the first column .
arr=np.array([[1,2,3,4],[4,5,6,7]])
arr[0:,1:]The operation results are as follows :

4.1.4 Integer index : Take two integers from the corresponding positions of the two sequences to form row subscript and column subscript .
4.1.5 Boolean index : When the result object is a Boolean operation ( For example, the comparison operator ) When the result is , Use Boolean index
4.2, Modify array shape
4.2.1, Array name .reshape=( That's ok , Column ). Do not change the shape of the original array
# Create an array
arr=np.arange(12)arr.reshape(3,4)4.2.2, Array name .resize=( That's ok , Column ). Do not change the shape of the original array , Returns a new array of the specified size .
arr.resize(4,3)4.2.3 Set dimension f How to modify the shape of an array :
arr.shape=(3,4)The results are shown below :

4.3, Flattening and linking of arrays
4.3.1 ravel() function : You can flatten a multidimensional array into a one-dimensional array , primary arr unchanged . Flatten by row
#ravel() Function to flatten by line
arr3=arr1.ravel()The operation results are as follows :
4.3.2 flatten() function : You can flatten a multidimensional array into a one-dimensional array , And you can choose to flatten by row or column
#flatten() The function flattens by line by default
arr3=arr1.flatten()
#"F" Indicates flattening by column
arr3=arr1.flatten("F")The operation results are as follows :

4.3.3 hstack() function , Left and right splicing
np.hstack((arr1,arr2))The running results are as follows

4.3.4 vstack() function : Upper and lower splicing
np.vstack((arr1,arr2))The operation results are as follows :

4.3.5 concatenate() function : Used to connect two or more arrays of the same shape along the specified axis .
#axis = 1 Left and right splicing
np.concatenate((arr1,arr2),axis = 1)
#axis = 0 Upper and lower splicing
np.concatenate((arr1,arr2),axis = 0)The operation results are as follows :

4.3.6 spilt() function : Divide an array into subarrays along a specific axis
#axis = 1 Split column
np.split(arr1,3,axis=0)
#axis = 0 Split line
np.split(arr1,3,axis=1)The operation results are as follows :

4.3.7 transpose() function : Realize the transpose of array , primary arr unchanged
# Method 1
np.transpose(arr1)
# Method 2
arr1.TThe operation results are as follows :

4.4, Processing of array elements
4.4.1 append() function : Is to add a function at the end of the array
# Add by line
np.append(arr,[[0, 0, 0]],axis=0)
# Add... By column
np.append(arr,[[0],[0], [0]],axis=1)The operation results are as follows :

4.4.2 insert() function : Before a given index , Inserts elements in the input array along a given axis
# Press the line
np.insert(arr,3,[[0,0,0],[1,1,1],[2,2,2]],axis=0)
# By column
np.insert(arr,3,[[0,0,0],[1,1,1],[2,2,2]],axis=1)give the result as follows :

4.4.3 delete() function : Returns a new array that removes the specified subarray from the input array
# Delete the second line
np.delete(arr,1,axis=0)
# Use slices to represent element ranges
np.delete(arr,np.s_[1,1,1])The operation results are as follows :

4.5, Operation of array
Arrays of the same shape are calculated element by element at the element level , And arrays of different shapes , Then it is calculated according to the broadcast mechanism
5, Random number module
5.1,random function : Generate [0,1) The random number in

5.2,rand function : Generate uniformly distributed [0,1) The random number in
5.3,randn function : Generating random numbers that obey normal distribution
5.4,randint function : Generate random numbers with given upper and lower bounds

5.5,choice function : Random sampling from a list or array

5.6,random The common random number generation function of the module
| Function name | purpose |
| seed | Identify random seeds |
| permutation | Returns the random ordering of a sequence |
| shuffle | Randomly sort a sequence ( Change the original sequence ) |
3、 ... and , matrix
1, Create a matrix

2, The vector product of a matrix
The operator uses *, And * The number of columns of the matrix on the left should be equal to the number of rows on the right , The result of the operation is the cumulative sum of the multiplication of the corresponding elements in the matrix

3, The quantity product of a matrix
Also known as dot multiplication of matrices , That is, the elements are multiplied

Four , Read and write files
1,save Function is to save an array of data in binary format
Create a new one on your desktop called save Folder .
#np.save(" route \\ Result filename ",arr name )
np.save("C:\\Users\\Yan\\Desktop\\save\\save_arr1",arr)give the result as follows :

2,savez Function can save multiple arrays to a file
np.savez("C:\\Users\\Yan\\Desktop\\save\\save_arr2",arr1,arr2)give the result as follows :

3,load The function reads data from a binary file
The extension can be omitted during storage , However, it is not allowed to omit .
np.load("C:\\Users\\Yan\\Desktop\\save\\save_arr1.npy")give the result as follows :

4,savetxt() Function to write an array to a delimited text file .
np.savetxt("C:\\Users\\Yan\\Desktop\\save\\save_arr3.txt",arr,fmt="%d",delimiter="..")
5,loadtxt() Function to load a file into a two-dimensional array .
np.loadtxt("C:\\Users\\Yan\\Desktop\\save\\save_arr3.txt",delimiter="..")
#delimiter Medium is txt How to split storage give the result as follows :

5、 ... and ,numpy Statistical analysis in
1,sort() Direct sort

2, Indirect sort
argsort(): Returns the subscript of the value sorted in ascending order along the axis
np.argsort(arr1)lexsort(): Used to sort multiple sequences . Returns the subscript of the sorted value
np.lexsort((arr,arr1))3, Repetition and de duplication
duplicate removal :
unique Function to find unique values in an array , And return the results sorted in ascending order

repeat :
tile() Repeat the entire array
np.tile(arr,2)
# 2 The number of repetitions 
repeat(): Repetitive elements , Repeat by row or column can be specified

边栏推荐
- [translation] go references - the go memory model | memory model for Chinese translation of official golang documents
- About message
- 点云配准--gicp原理与其在pcl中的使用
- 屏蔽不显示VS警告warning
- What can LDAP and SSO integration achieve?
- Rust language learning
- sublime_ Textuse
- 鸡尾酒排序
- Tron API wave field transfer query interface PHP version package based on thinkphp5 attached interface document 20220528 version
- JS attribute operation and node operation
猜你喜欢

【C语言】关键字static&&多文件&&猜字游戏

InfluxDB2.x 基准测试工具 - influxdb-comparisons

Redis的主从复制原理

Invalid date of moment conversion timestamp

A. Prefix range

You can't just use console Log ()?

JS string array converted to numeric array and how to add the numbers in the array

In navigation, the solution of adding borders to affect the layout

promise的理解已经利用promise实现图片的预加载(顺序加载)

Promise knowledge
随机推荐
关系代数笛卡尔积和自然连接的例子
Is yuancosmos a short-term speculation or a future trend?
ELK搭建指南
MVC模式、加密、jsonwebtoken
C语言深度解剖篇——关键字&&补充内容
In depth anatomy of C language - key words & supplementary contents
Suggestions and skills for advanced version of go language test
Influxdb2.x benchmark tool - influxdb comparisons
导航中,添加边框影响布局的解决方法
Preliminary study on Regional Simulation of crop model
Promise knowledge
[译] Go语言测试进阶版建议与技巧
【C语言】关键字static&&多文件&&猜字游戏
[转]placement new
Common debugging tools and commands for ROS
What can LDAP and SSO integration achieve?
银行布局元宇宙:数字藏品、数字员工成主赛道!
Differences between server-side rendering and client-side rendering (advantages and disadvantages)
Stress - system pressure simulation tool
TRON-api-波场转账查询接口-PHP版本-基于ThinkPHP5封装-附带接口文档-20220602版本-接口部署好适用于任何开发语言