当前位置:网站首页>Graphic array calculation module numpy (trigonometric function, rounding function, converting radian to angle, statistical analysis function, median, array sorting, argsort(), lexport())
Graphic array calculation module numpy (trigonometric function, rounding function, converting radian to angle, statistical analysis function, median, array sorting, argsort(), lexport())
2022-07-18 16:02:00 【Triumph19】
- This article is from 《Python Data analysis goes from beginner to proficient 》—— Edited by tomorrow Technology
8.5 NumPy Common statistical analysis functions
8.5.1 Mathematical operation function
- NumPy Functions that contain a large number of mathematical operations , Including trigonometric functions 、 Arithmetic operation function 、 Complex processing functions, etc , As shown in the table 8.2 Shown .

1. Arithmetic functions
(1) Add 、 reduce 、 ride 、 except
- NumPy Arithmetic functions contain simple addition 、 reduce 、 ride 、 In addition to the operation , Such as add() function 、subtract() function 、multiply() Functions and divide() function . What we should pay attention to here is , Arrays must have the same shape or conform to array broadcast rules .
import numpy as np
n1 = np.array([[1,2,3],[4,5,6],[7,8,9]]) # Create array
n2 = np.array([10, 10, 10])
print(' Add two arrays :')
print(np.add(n1, n2))
print(' Two arrays subtract :')
print(np.subtract(n1, n2))
print(' Multiply two arrays :')
print(np.multiply(n1, n2))
print(' Divide two arrays :')
print(np.divide(n1, n2))
Add two arrays :
[[11 12 13]
[14 15 16]
[17 18 19]]
Two arrays subtract :
[[-9 -8 -7]
[-6 -5 -4]
[-3 -2 -1]]
Multiply two arrays :
[[10 20 30]
[40 50 60]
[70 80 90]]
Divide two arrays :
[[0.1 0.2 0.3]
[0.4 0.5 0.6]
(2) Reciprocal
- reciprocal() Function is used to return the reciprocal of each element in the array .
import numpy as np
a = np.array([0.25, 1.75, 2, 100])
print(np.reciprocal(a))
[4. 0.57142857 0.5 0.01 ]
(3) Exponentiation
import numpy as np
n1 = np.array([10, 100, 1000])
print(np.power(n1, 3))
n2= np.array([1, 2, 3])
print(np.power(n1, n2))
[ 1000 1000000 1000000000]
[ 10 10000 1000000000]
(4) Remainder
- mod() Function is used to calculate the remainder after dividing the corresponding elements between arrays .
import numpy as np
n1 = np.array([10, 20, 30])
n2 = np.array([4, 5, -8])
print(np.mod(n1, n2))
[ 2 0 -2]
2. Rounding function
(1) rounding around() function
numpy.around(a,decimals)
- a: Array
- decimals: The number of decimal places rounded , The default value is 0, If a negative , Integers are rounded to the left of the decimal point .
import numpy as np
n = np.array([1.55, 6.823,100,0.1189,3.1415926,-2.345]) # Create array
print(np.around(n)) # Round to the nearest whole
print(np.around(n, decimals=2)) # Round to two decimal places
print(np.around(n, decimals=-1))# Round to the left of the decimal point
[ 2. 7. 100. 0. 3. -2.]
[ 1.55 6.82 100. 0.12 3.14 -2.35]
[ 0. 10. 100. 0. 0. -0.]
(2) Rounding up ceil() function
- ceil() Function is used to return the smallest integer greater than or equal to the specified expression , That is, round up .
import numpy as np
n = np.array([-1.8, 1.66, -0.2, 0.888, 15]) # Create array
print(np.ceil(n)) # Rounding up
[-1. 2. -0. 1. 15.]
(3) Rounding down floor() function
import numpy as np
n = np.array([-1.8, 1.66, -0.2, 0.888, 15]) # Create array
print(np.floor(n)) # Rounding down
[-2. 1. -1. 0. 15.]
3. Trigonometric functions
import numpy as np
n= np.array([0, 30, 45, 60, 90])
print(' Sine of different angles :')
# By riding pi/180 Into radians
print(np.sin(n * np.pi / 180))
print(' The cosine of the angle in the array :')
print(np.cos(n * np.pi / 180))
print(' The tangent of the angle in the array :')
print(np.tan(n * np.pi / 180))
Sine of different angles :
[0. 0.5 0.70710678 0.8660254 1. ]
The cosine of the angle in the array :
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
The tangent of the angle in the array :
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]
Convert radians to degrees
import numpy as np
n = np.array([0, 30, 45, 60, 90])
print(' Sine of different angles :')
sin = np.sin(n * np.pi / 180)
print(sin)
print(' Calculate the inverse sine of the angle , The return value is in radians :')
inv = np.arcsin(sin)
print(inv)
print(' Radians are converted to angles :')
print(np.degrees(inv))
Sine of different angles :
[0. 0.5 0.70710678 0.8660254 1. ]
Calculate the inverse sine of the angle , The return value is in radians :
[0. 0.52359878 0.78539816 1.04719755 1.57079633]
Radians are converted to angles :
[ 0. 30. 45. 60. 90.]
8.5.2 Statistical analysis function

1. Sum up sum() function
- Sum array elements 、 Sum the array elements by row and column , The program code is as follows :
- Parameters axis=0 when , Returns the sum of the columns of the array , Parameters axis=1 when , Returns the sum of the rows of the array .

import numpy as np
n=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(' Sum array elements :')
print(n.sum())
print(' Sum array elements by line :')
print(n.sum(axis=0))
print(' Sum array elements by column :')
print(n.sum(axis=1))
Sum array elements :
45
Sum array elements by line :
[12 15 18]
Sum array elements by column :
[ 6 15 24]
2. averaging mean() function
import numpy as np
n=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(' Average the array elements :')
print(n.mean())
print(' Average the array elements by row :')
print(n.mean(axis=0))
print(' Average the array elements by column :')
print(n.mean(axis=1))
Average the array elements :
5.0
Average the array elements by row :
[4. 5. 6.]
Average the array elements by column :
[2. 5. 8.]
3. For maximum max() Functions and minimum values min() function
import numpy as np
n=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(' Maximum value of array element :')
print(n.max())
print(' The maximum value of each row in the array :')
print(n.max(axis=0))
print(' The maximum value of each column in the array :')
print(n.max(axis=1))
print(' Minimum value of array element :')
print(n.min())
print(' The minimum value of each row in the array :')
print(n.min(axis=0))
print(' The minimum value of each column in the array :')
print(n.min(axis=1))
Maximum value of array element :
9
The maximum value of each row in the array :
[7 8 9]
The maximum value of each column in the array :
[3 6 9]
Minimum value of array element :
1
The minimum value of each row in the array :
[1 2 3]
The minimum value of each column in the array :
[1 4 7]
4. Take the weighted average average() function
Calculate the weighted average price of e-commerce activities
- An e-commerce company is in the school season 、6.18、 A double tenth 、 The prices of double twelve and other activities are different , Next, calculate the weighted average price , The program code is as follows :
import numpy as np
price=np.array([34.5,36,37.8,39,39.8,33.6]) # establish “ The unit price ” Array
number=np.array([900,580,230,150,120,1800]) # establish “ sales volumes ” Array
print(' Weighted average price :')
print(np.average(price,weights=number))
Weighted average price :
34.84920634920635
5. Median median() function
- The median is used to measure the medium or general level of data value , It can avoid the influence of extreme values . In data processing , When there are a few outliers in the data , It is not affected by it , Based on this feature , The median is generally used to evaluate the analysis results .
import numpy as np
n=np.array([34.5,36,37.8,39,39.8,33.6]) # establish “ The unit price ” Array
# After array sorting , Find the median
sort_n = np.msort(n)
print(' Array sorting :')
print(sort_n)
print(' The median of the array is :')
print(np.median(sort_n))
Array sorting :
[33.6 34.5 36. 37.8 39. 39.8]
The median of the array is :
36.9
6. variance 、 Standard deviation
import numpy as np
n=np.array([34.5,36,37.8,39,39.8,33.6]) # establish “ The unit price ” Array
print(' Array variance :')
print(np.var(n))
print(' Array standard deviation :')
print(np.std(n))
Array variance :
5.168055555555551
Array standard deviation :
2.2733357771247853
8.5.3 Sort of array
1.sort() function
- Use sort() Function to sort , Change the original array directly , Parameters axis Specify whether to sort by row or column .
import numpy as np
n=np.array([[4,7,3],[2,8,5],[9,1,6]])
print(' Array sorting :')
print(np.sort(n))
print(' Sort by row :')
print(np.sort(n,axis=0))
print(' Sort by column :')
print(np.sort(n,axis=1))
Array sorting :
[[3 4 7]
[2 5 8]
[1 6 9]]
Sort by row :
[[2 1 3]
[4 7 5]
[9 8 6]]
Sort by column :
[[3 4 7]
[2 5 8]
[1 6 9]]
2.argsort() function
- Use argsort() Function to sort the array , Returns the index value from small to large after ascending sorting .
import numpy as np
x=np.array([4,7,3,2,8,5,1,9,6])
print(' Index value after ascending sort :')
y = np.argsort(x)
print(y)
print(' Reconstruct the original array in the sorted order :')
print(x[y])
Index value after ascending sort :
[6 3 2 0 5 8 1 4 7]
Reconstruct the original array in the sorted order :
[1 2 3 4 5 6 7 8 9]
3.lexsort() function
- lexsort() Function to sort multiple sequences . Think of it as sorting a spreadsheet , Each column represents a sequence , When sorting, priority is given to the next column .
Solve the admission problem of students with the same grades by sorting
- A key high school , The students admitted to the elite class are admitted according to the total score . Due to the limited number of places , So when the total score is the same , Those with high math scores are preferred ; When the total score and math score are the same , Those with high English scores are preferred . Use lexsort() Function to sort student grades , The program code is as follows :
import numpy as np
math=np.array([101,109,115,108,118,118])
en=np.array([117,105,118,108,98,109])
total=np.array([621,623,620,620,615,615])
sort_total=np.lexsort((en,math,total))
print(' The sorted index value ')
print(sort_total)
print (' Get the sorted array through the sorted index :')
print(np.array([[en[i],math[i],total[i]] for i in sort_total]))
The sorted index value
[4 5 3 2 0 1]
Get the sorted array through the sorted index :
[[ 98 118 615]
[109 118 615]
[108 108 620]
[118 115 620]
[117 101 621]
[105 109 623]]
8.6 Comprehensive application
8.6.1 NumPy Achieve normal distribution
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['axes.unicode_minus'] = False # Used to display negative sign normally
sns.set_style('darkgrid')
n = np.random.normal(0, 0.1, 1000) # The mean value of the generation is 0, The standard deviation is 0.1 One dimensional normal distribution sample 1000 individual
print(n)
sns.distplot(n) # Histogram
plt.show()# Show

8.6.2 NumPy For image gray processing
- First, let's look at the image , The image is actually composed of several pixels , Each pixel has a specific position and assigned color value , Therefore, an image constitutes a pixel matrix . for example , A gray pixel block , Pictured 8.32 Shown .

- From the picture 8.32 hear : The data of the grayscale image is a two-dimensional array , The color value is 0~255, among 0 For the black ,255 White . from 0-255 Gradually from dark to bright . thus it can be seen , Can image grayscale processing be realized by array calculation ?
- Next , Understand a formula ,RGB Common formula for converting to gray image :
Gray = R*0.299 + G*0.587 + G*0.114
- among ,Gray Represents the grayscale value ,R、G、B It means red 、 green 、 Blue color value ,0.299、0.587、0.114 Represents the fixed value of the grayscale formula .
- Use NumPy combination Matplotlib Realize the gray processing of the image , The program code is as follows :
import numpy as np
import matplotlib.pyplot as plt
n1=plt.imread("flower.jpg") # Read the picture
plt.imshow(n1) # The incoming array displays the corresponding color
#n1 Is a three-dimensional array , The highest dimension is the height of the image , The next higher dimension is the width of the image , Minimum dimension [R,G,B] It's the color value
n2=np.array([0.299,0.587,0.114]) # Fixed value of gray formula
x=np.dot(n1,n2) # Will array n1(RGB Color value ) And an array n2( Fixed value of gray formula ) Point multiplication is performed on each element in
plt.imshow(x,cmap="gray") # The incoming array displays grayscale
plt.show() # Display images
- The above code , When displaying grayscale images , Need to be in imshow() Set parameters in function parameters camp=‘gray’.
- Run the program , The contrast effect is as follows :


8.7 Summary
- Through the study of this chapter , Be able to master NumPy Common operations of , That is, the basic operations and operations from array creation to array . For data statistical analysis , That's enough ; And for AI 、 machine learning , More in-depth study is needed NumPy Related knowledge . in addition , When the amount of data is very large ,NumPy It can bring more than a hundred times the speed increase .
边栏推荐
- Big guy said * computing talk Club | Sanxingdui fantasy trip: an experience that only cloud computing can bring
- Is it safe to open an account for 2980 yuan? Is it so expensive?
- 面试官:Redis 性能优化都有哪些方法?
- Principle analysis of Rex engine of osgearth (one, two, eight) Rex engine and layer projection and their relationship
- Defi中的关键 智能合约是什么?
- 成都 Meetup |分布式数据库,企业降本增效新引擎
- Deepin wine QQ/微信中文显示为方块的原因之一
- Kubedm install kubernetes 1.15 best practices
- C语言实训通讯录(静态和动态版本)
- redis实现浏览历史模块
猜你喜欢

Solution to slow running card of VMware virtual machine

From it R & D staff turnover thought

ReFi夏季升温:Uniswap v3和绿色资产池在Celo上启动

7.13 learning records

怎么设置域名解析?

深度学习中一些注意力机制的介绍以及pytorch代码实现

GPU accelerated opencv Library & reconfigure and generate opencv CUDA version using cmake and vs2019

uniapp扫码原生插件(Google MLKit、zxing;支持同时扫多个码)

FPGA 20个例程篇:8.SD卡任意地址的读写

軟件測試面試:請說一下你工作中發現的最有價值的bug?
随机推荐
Software testing interview: please talk about the most valuable bugs you found in your work?
How to handle code exceptions gracefully with assertion ideas
最近VS2019下载速度慢的解决办法
7.14 dichotomy, LCA, difference, thinking structure
What are the core technologies of okcc call center system
在okcc中你了解呼叫并发的含义吗?
Apache stress testing tool AB, with post parameter and token request
From it R & D staff turnover thought
7.14二分,LCA,差分,思维构造
分享一个超好用的 轮询 + 定时器管理器
ELK集群部署(十)之ELK服务化
Kubedm install kubernetes 1.15 best practices
ncnn 编译与使用 pnnx 编译与使用
The problem and solution of calling glcreateshader to crash
AutoJs学习-TTS抢语音红包
AutoJs学习-变声器模板
Brush questions of binary tree (I)
Web page making (II)
AcWing 133. earthworm
使用IDEA搭建WebService服务