current position：Home>Python numpy module basic usage
Python numpy module basic usage
20220202 14:13:50 【Ice sky】
List of articles
Python Numpy
One 、 Array
1. establish
Numpy Including a variety of ways to create arrays
np.array(list)
Initialize an array by passing in a list ：
import numpy as np
# Declare an array
arr = np.array([[1,2,3], [4,5,6]])
''' 1 2 3 4 5 6 '''
np.ones(shape)/np.zeros(shape)
All elements that generate the desired shape are 1(0) Array of ：
ones = np.ones((2,2))
''' output 1 1 1 1 '''
zeros = np.zeros((3,3))
''' output 0 0 0 0 0 0 0 0 0 '''
np.arange(begin, end, stride)
Generate a onedimensional array according to the given interval and step size , The default from the 0 Start , In steps of 1, among ：
begin
: Starting value , optionalend
： Cutoff value , Requiredstride
： step , optional
range = np.arange(0, 10, 2)
''' output: 0 2 4 6 8 10 '''
np.linespace(begin, end, count)
Similarly, this function also specifies an interval , But here's the difference ,linspace
The third parameter refers to ： from begin Start to end Number of intermediate equal parts , That is, an array with the specified number of elements is returned , The step length is the average of the interval length for the number of specified elements , for example ：
ls1 = np.linspace(0, 10, 2)
ls1.size()
''' output 0, 10 size: 2 '''
ls2 = np.linspace(0, 10, 6)
ls2.size()
''' output 0, 2, 4, 6, 8, 10 size: 6 '''
ls3 = np.linspace(0, 10, 11)
ls3.size()
''' output 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 size: 11 '''
np.random.radint(min, max, shape)
When we need to create an array with random element size , It can be generated by this random number group ：
rand = np.random.radint(0, 10, 3)
''' output 4 2 0 3 8 1 9 0 1 '''
2. attribute
Numpy The array object contains several very useful properties that describe the characteristics of the array ：
ndim
： Dimension of arraysize
： Array size , That is, the number of elements includedshape
： The shape of the arraydtype
： The type of array
for example ：
temp = np.ones((2,2))
''' temp.ndim: 2 temp.size: 4 temp.shape: (2,2) temp.dtype: float '''
3. Method
3.1 Shape transformation method ：reshape(shape), flatten()
Shape change , You can adjust the shape of the array , An array commonly used to convert a range to a desired shape ：
range = np.arange(0, 10, 3) # [0, 3, 6, 9], size: 4, shape: (1,4)
range.reshape((2,2))
''' output 0 3 6 9 '''
range.flatten()
''' output 0 3 6 9 '''
3.2 Statistical methods ：min, max, ptp, median, mean, std, var, sum
$A little…$
3.3 Set operations
# example
# a: 1,2,3,4,5,6
# b: 5,6,7,8,9
# intersection
numpy.intersect1d(a,b)
''' output 5, 6 '''
# Difference set
numpy.sestdiff1d(a,b)
''' output 1, 2, 3, 4, 7, 8, 9 '''
From the function name , obviously , The function is used to calculate the intersection between onedimensional arrays , If the input array dimension is not onedimensional , At this time, the function will first modify the array
flatten
operation , Unified into a onedimensional array and then calculated .setdiff1d
Empathy
3.4 Correlation coefficient calculation and mask array
The correlation coefficient is known ：
$ρ=σ_{X},σ_{Y}Cov(X,Y) $
also ：
$Cov(X,Y)=E(XY)−E(X)E(Y)$
be ：
$ρ=σ_{X}σ_{Y}E(XY)−E(X)E(Y) $
When the correlation coefficient is calculated by code , At this point, you can create a file containing $X,Y$ Two arrays of x
and y
, be $XY$ by x * y
, Then, according to the statistics member function of the array mentioned above, we can get ：
# E(XY)
e_xy = (x * y).mean()
# E(X)E(Y)
e_x_y = x.mean() * y.mean()
# X Standard deviation
sigma_x = x.std()
# Y Standard deviation
sigma_y = y.std()
Finally, the correlation coefficient can be calculated ：
corrcoef = (e_xy  e_x_y) / (sigma_x * sigma_y)
Now combine Numpy The correlation coefficient matrix calculation function provided ：
np.corrcoef(x, y)
''' output 1 corr(x,y) corr(x,y) 1 '''
The corresponding correlation coefficient can be obtained at the corresponding row and column position , The diagonal is the self correlation coefficient , by $1$
copyright notice
author[Ice sky],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202021413475327.html
The sidebar is recommended
 Python actual combat case, mplcyberpunk module, python realizes cyberpunk data visualization
 What are the differences between golang and python 3?
 Detailed explanation of Python + fidder 4 web crawler (the most complete in Station C)
 Pycham operation and configuration guide can't do this. It must be slow to write python
 "Top level introduction to Python" is the devil's step step by step
 Summary of the most complete Python Library in Station C  standard library + advanced library (10000 word long text, recommended Collection)
 Python realizes GIF dynamic drawing and video card communication, kicks two feet to break the dimensional wall  machine learning
 Python realizes the cartoon of photos and breaks the dimensional wall with one punch  machine learning
 Python to achieve picture beautification, drunk do not know the sky in the water? (attach code)  machine learning
 Python projects are packaged into executable exe files
guess what you like

Python video conversion resolution (with code)  Python tool

Python modify picture resolution (with code)  Python tool

Python file upload Minio and Ali OSS tools  Python tools

Python video add audio (with code)  Python tool

Python game development, python to achieve Snake games and eat beans with source code

What language is Python

[untitled] Python magic method__ new__ method

Use Python to get the information of popular positions and see what skills you need from a high salary

Notes on Python deep learning (11): loss function

Python foundation 2.4  tuple
Random recommended
 Case 58 of 120 Python crawlers, mobile app crawler, preparation of "arsenal" and test of skin shrimp app
 Asynchronous programming in Python
 Python  concave polygon boundary extraction of plane point cloud
 Python learning (4)
 How to solve the problem of customization? (Language Python)
 Asynchronous programming in Python
 Python crawler programming analysis and cases Chapter 1 mitmproxy + Python crawler programming
 Python tiktok programming analysis and case mitmproxy + python+Appium grab shake fan information
 Analysis of Python crawler programming and installation of mitmproxy
 Programming with Python and C language
 PIP installation pypesq reported an error python3 seven
 It took three months, the most detailed and complete, 402 pages of Python learning materials. You'll lose money if you don't read it
 The accuracy of Python naive Bayes is too low
 Have you learned the common English vocabulary of Python?
 Python 32bit desert plugin registration
 A popular but very easytouse builtin function in Python
 Introduction to Python testing framework pytest
 Recommended 4 books for Python
 Three ways of generating Excel files with Python
 Python training artificial intelligence 7
 Offline Python training in Chengdu
 Python Dalian training
 Shenzhen learning Python training
 Shanghai weekend Python training
 Mago Python training
 Python best training
 Python Big Data Engineer Training
 Python multi process realizes the word frequency statistics function of document library under MapReduce model
 Python  Pandas  time series
 Python  Pandas  data processing
 Introduction to Python learning functions
 Zero basics Python web development online examination system  Introduction to Django framework project lesson 2  model and management site (really take you on the road to play practical project development)
 Python lists and tuples
 Sentry developer contribution Guide  back end services (Python / go / rust / nodejs)
 A popular but very easytouse builtin function in Python
 Introduction to Python testing framework pytest
 Python interface automation  post request parameters are passed to JSON or data. How to distinguish
 Is there any common Python tutorial that even a fool can understand?
 Wanzi teaches you how to use Python to realize linear programming
 Sentry developer contribution Guide  back end services (Python / go / rust / nodejs)