[Python] numpy of Python

Yngz_ Miao 2020-11-13 07:54:59
python numpy python


Numpy stay python Is a very common bag , Whether it's machine learning collocation pandas, Or data visualization collocation pylab It's a very normal match .


Numpy

numpy Official Chinese document of :NumPy chinese

NumPy It's using Python Basic software package for Scientific Computing . Among other things , It includes :

  • Powerful N Dimensional array object ;
  • Precise broadcast function ;
  • Integrate C/C+ and Fortran Code tools ;
  • Powerful Linear Algebra 、 Fourier transform and random number function .

More simply ,Numpy yes Python Of Matlab Math package . Use it ,python The matrix vector can be calculated more simply and conveniently .

Generally speaking , We refer to the package and abbreviate it to np

import numpy as np

Numpy Of ndarry object

ndarray The creation of

Numpy The most important data type in is :N Dimensional array object ndarray. It's a collection of data of the same type , With 0 The subscript is to start indexing the elements in the collection .

It has the following two characteristics :

  • ndarray Object is a multidimensional array used to hold elements of the same type ;
  • ndarray Each element in has an area of the same storage size in memory .

Create a ndarray object :

np.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

Parameter description :

name describe
object An array or nested sequence of numbers
dtype Data type of array element , Optional
copy Whether the object needs to be copied , Optional
order Create an array style ,C In the direction of the line ,F For column direction ,A In any direction ( Default )
subok By default, it returns an array consistent with the base class type
ndmin Specifies the minimum dimension of the generated array

generally speaking , You don't need to remember so many optional parameters :

import numpy as np
if __name__ == "__main__":
x = np.array([1, 2, 3])
print(x)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[1 2 3]

Of course , In addition to the previous array Method creation ndarray Beyond the object , There are several other ways to create :

np.empty(shape, dtype = float, order = 'C') # Uninitialized array of specified shapes 
np.zeros(shape, dtype = float, order = 'C') # All of the specified shapes 0 Array 
np.ones(shape, dtype = None, order = 'C') # All of the specified shapes 1 Array 
np.arange(start = 0, stop, step = 1, dtype) # From the starting value to the ending value ( It doesn't contain ) when , Create an array from a range in steps 
np.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None) # From the starting value to the ending value ( Default includes ) Create a one-dimensional array of isometric arrays 
np.logspace(start, stop, num = 50, endpoint = True, base = 10.0, dtype = None) # From the starting value to the ending value ( Default includes ) Create a one-dimensional array of proportional arrays 

Numpy Also provided from python Other types are converted directly to ndarray The way :

np.asarray(a, dtype = None, order = None) # Tabular form 
np.frombuffer(buffer, dtype = float, count = -1, offset = 0) # Read in as a stream 
np.fromiter(iterable, dtype, count=-1) # From iteratable objects , Read in as an iterator 

for example :

import numpy as np
if __name__ == "__main__":
a = [[1, 2 ,3], [4, 5]]
b = 'Hello World'
c = iter(range(5))
x = np.asarray(a)
y = np.frombuffer(b, dtype = 'S1')
z = np.fromiter(c, dtype = float)
print(x)
print(y)
print(z)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[list([1, 2, 3]) list([4, 5])]
['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
[0. 1. 2. 3. 4.]

ndarray Data structure of

Numpy Support a lot of data types , Here's a simple list :

name describe
bool_ Boolean data type (True perhaps False)
int_/int8/int16/int32/int64 Signed integers
uint8/uint16/uint32/uint64 Unsigned integer
float_/float16/float32/float64 Floating point numbers
complex_/complex64/complex128 The plural

But if it's a custom data type , It needs to pass dtype To make sure :

numpy.dtype(object, align, copy)

Parameter description :

name describe
object Data type object to convert to
align If true, Fill in the fields to make them look like C The structure of the body
copy Copy dtype object , If false, Is a reference to a built-in data type object

for example , You can create a student The object of :

import numpy as np
if __name__ == "__main__":
student = np.dtype([('name', 'S20'), ('age', 'i8'), ('score', 'f4')])
a = np.array([('zhangsan', 18, 80), ('lisi', 19, 85)], dtype=student)
print(a)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[('zhangsan', 18, 80.) ('lisi', 19, 85.)]

ndarray Properties of

ndarray There are two very common properties ,shape and size.shape Represents the dimensions of an array , For two-dimensional arrays , It's the number of rows and columns ;size Represents the total number of array elements , For two-dimensional arrays , It's the multiplication of the number of rows and columns .

for example :

import numpy as np
if __name__ == "__main__":
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
print(a.size)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
(2, 3)
6

Of course ,ndarray Objects provide two ways to do this without changing the content of the data , Change the format of an array . But the two ways are different :

import numpy as np
if __name__ == "__main__":
a = np.array([[1, 2, 3], [4, 5, 6]])
a.shape = (3, 2) # Directly change the noumenon 
print(a)
b = a.reshape(2, 3) # The noumenon does not change , Return the changed object to 
print(b)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[[1 2]
[3 4]
[5 6]]
[[1 2 3]
[4 5 6]]

ndarray Content access for

ndarray The contents of an object can be accessed and modified by index or slice , And python in list The slice operation is the same .

ndarray It can be sliced based on the subscript , It's fine too Through the built-in slice function , And set up start,stop And step Parameters , Cut a new array from the original array .

for example :

import numpy as np
if __name__ == "__main__":
a = np.arange(10)
b = a[1:7:1]
s = slice(1,7,1)
c = a[s]
print(a)
print(b)
print(c)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[0 1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6]
[1 2 3 4 5 6]

For colons : The explanation of :

  • If it's a one-dimensional array , If you put only one parameter , Such as [2], A single element corresponding to the index... Will be returned . If [2:], Indicates that all items from the beginning of the index will be extracted . If two parameters are used , Such as [2:7], Then extract two indexes ( Does not include stop indexing ) Between the items ;
  • If it's a multidimensional array , Use , Distinguishing dimensions .

for example :

import numpy as np
if __name__ == "__main__":
a = np.arange(25)
a.shape = (5, 5)
b = a[1:4, 2:4]
print(a)
print(b)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
[[ 7 8]
[12 13]
[17 18]]

ndarray Except for slicing based on subscripts , There are also some advanced indexing methods , Like Boolean indexes 、 Fancy index .

for example :

import numpy as np
if __name__ == "__main__":
a = np.arange(25)
a.shape = (5, 5)
b = a[a > 6]
c = a[[3, 2, 4]]
print(a)
print(b)
print(c)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
[ 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
[[15 16 17 18 19]
[10 11 12 13 14]
[20 21 22 23 24]]

other

Judge whether the element objects are all NaN

np.isnan(...)

take ndarray The object of the is changed to list

obj.tolist()

Numpy Broadcast of

If two ndarraya and b The same shape , The meet a.shape==b.shape, that a And b The result is a And b Arrays do arithmetic operations on bits . This requires The dimensions are the same , And the length of each dimension is the same .

for example :

import numpy as np
if __name__ == "__main__":
a = np.array([1, 2, 3])
b = np.array([1, 2, 3])
c = a + b
d = a * b
print(c)
print(d)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[2 4 6]
[1 4 9]

and , Radio is Numpy For different shapes (shape) Of ndarray How to do numerical calculation , Yes ndarray To perform arithmetic operations on the corresponding elements .

How is it a corresponding element ?

although , Broadcasting is about different shapes (shape) for , But in fact, two conditions have to be met : Same number of columns , There is a line number of 1. Under this premise , The elements of the same column in each row are the corresponding elements .

It's impossible to read the text directly , Take a look at an example :

import numpy as np
if __name__ == "__main__":
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([1, 2, 3])
c = a + b
d = a * b
print(c)
print(d)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[[ 2 4 6]
[ 5 7 9]
[ 8 10 12]]
[[ 1 4 9]
[ 4 10 18]
[ 7 16 27]]

The so-called broadcasting is : When the number of columns is the same , The number of rows is 1 Of ndarray Will expand the line operation , The content of the increased number of lines is the same as that of the original line .

Extension can be realized by tile Function implementation :

np.tile(obj, ( That's ok , Column )) # Repeat on the row and column a certain number of times 

therefore , The above broadcast can also be replaced by the following ways :

import numpy as np
if __name__ == "__main__":
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([1, 2, 3])
bb = np.tile(b, (3, 1))
c = a + bb
d = a * bb
print(bb)
print(c)
print(d)

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test$ python numpy_test.py
[[1 2 3]
[1 2 3]
[1 2 3]]
[[ 2 4 6]
[ 5 7 9]
[ 8 10 12]]
[[ 1 4 9]
[ 4 10 18]
[ 7 16 27]]

ndarray Function of

ndarray Provides a lot of mathematical functions 、 Arithmetic functions 、 Sorting function , In order to do the calculation .

ndarray The mathematical function of , for example :

np.pi # PI 
np.sin(obj) # Trigonometry 
np.cos(obj)
np.tan(obj)
np.arcsin(obj) # Inverse trigonometry 
np.arccos(obj)
np.arctan(obj)
np.degrees(obj) # Convert radian value to angle value 
np.around(obj, decimals) # return ndarray The rounding value of each element ,decimals Is the rounding number of decimal places , The default is 0
np.floor(obj) # Rounding down 
np.ceil(obj) # Rounding up 

ndarray The arithmetic function of , for example :

np.add(obj1, obj2) # Addition, subtraction, multiplication and division , And +-*/ The effect is consistent , Need to comply with broadcasting principles 
np.subtract(obj1, obj2)
np.multiply(obj1, obj2)
np.divide(obj1, obj2)
np.mod(obj1, obj2) # Remainder operation 
np.reciprocal(obj) # Take the reciprocal of the elements 
np.power(obj1, obj2) # Before calculation, the parameter is the base , The latter parameter is a power value 

ndarray The sort function of , for example :

np.sort(obj, axis=1, kind='quicksort', order)

Parameter description :

name describe
obj An array or nested sequence of numbers
axis axis=0 Sort by column ,axis=1 Sort by row
kind ‘quicksort’、‘mergesort’、‘heapsort’
order If the array contains fields , The fields to be sorted

Related reading

python Medium numpy modular

版权声明
本文为[Yngz_ Miao]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database