Happy journey of simple Python: numpy topic of Python basic syntax

Defonds 2020-11-13 04:49:16
happy journey simple python numpy



In the use of 2D Array or multidimensional array ,Python Of Numpy The library is very useful . such as , In the work of image processing , You have to store the pixel values in a two-dimensional or three-dimensional array .
Python Only one dimensional arrays are supported . It doesn't support multidimensional arrays .Numpy It's right Python An extension of array , It not only supports multidimensional arrays , It also provides mathematical operations based on multidimensional arrays .

1. Pycharm Import Numpy modular

Writing Numpy Before the program ,Pycharm You need to import Numpy modular , Otherwise, you may encounter No module named ‘numpy’ Error of . Please refer to the blog for details 《PyCharm To write Numpy Program times No module named ‘numpy‘ Wrong solution 》.

2. Python Numpy brief introduction

By default ,Python There is no concept of arrays , And there is no built-in support for multidimensional arrays .
Python Numpy Is an easy library for handling multidimensional arrays . It has a rich set of functions , You can easily handle arrays . Especially with Python Increased use in data analysis and scientific projects ,numpy Has become a processing array Python An integral part of .
Python Numpy Is an easy library for handling multidimensional arrays . It has a rich set of functions, which can easily handle arrays . Especially with Python Increased use in data analysis and scientific projects ,numpy Has become a processing array Python An integral part of .
Next we'll take a series of Numpy Examples to help you understand the use of numpy Kuhe Python programing language .

3. Numpy - Create a one-dimensional array

seeing the name of a thing one thinks of its function , A one-dimensional array contains only one-dimensional elements . Or say ,Numpy Arrays are shaped as tuples containing only one value .
To create a one-dimensional array , You can use Numpy Of array()、arange() or linspace() Any function of .

3.1. Use array() Function creation 1D Numpy Array

Numpy array() The function takes the element parameters of a list and returns a one-dimensional array .
In the following example, we will introduce numpy Library and use array() Function to create a one-dimensional array .

import numpy as np
# create numpy array
a = np.array([5, 8, 12])
print(a)

Execution and output :
 Create a one-dimensional array .png

3.2. Use arange() Function creation 1D Numpy Array

arange() Function takes parameters start、end As the value range and take the parameter interval To create a one-dimensional step numpy Array .
[start, start+interval, start+2*interval, … ]
Next we introduce numpy Library and use arange() Function to create a one-dimensional numpy Array .

import numpy as np
# create numpy array
a = np.arange(5, 14, 2)
print(a)

Execution and output :
 use arange() Function to create a one-dimensional numpy Array .png

so , The array starts with 5, With 2 Step length , until 14 until .

3.3. Use linspace() Function creation 1D Numpy Array

Numpy Of linspace() Function takes parameters start、end As the beginning of an array 、 Final element , And with parameters number Create a one-dimensional, evenly spaced array of numbers as the total number of elements to create the array .
Next we introduce numpy Library and use linspace() Function to create a one-dimensional numpy Array .

import numpy as np
# create numpy array
a = np.linspace(5, 25, 4)
print(a)

Execution and output :
 Use linspace() Function creation 1D Numpy Array .png

3.4. Summary

In this section , We learned from a simple, detailed example of using different built-in functions to create a numpy One dimensional array .

4. Create an array of random values

4.1. numpy in Of shape

shape Included in numpy library , It's an attribute of a matrix , You can get the shape of the matrix , The result is a tuple .
To create a specific... With random values shape Of numpy Array , Use numpy.random.rand(), And put the array of shape Pass as a parameter .
In this section , We'll learn about creating a random value of numpy An example of an array .

4.2. numpy.random.rand() The grammar of

rand() The syntax of the function is as follows :

numpy.random.rand(d0,d1,d2,...,dN)

among ,d0、d1、d2、… Is the size of each dimension in the array .
such as ,numpy.random.rand(2,4) It means a shape 2x4 Two dimensional array of , and numpy.random.rand(51,4,8,3) It means a shape by 51x4x8x3 The thinking array of .
so , This function returns a specified shape And use 0 To 1 Between random floating point numbers numpy Array .

4.3. Create a one-dimensional random value numpy Array

To create a one-dimensional random value numpy Array , Just pass the array size to rand() Function .
In this example , We will create a length of 7 One dimensional random value array of .

import numpy as np
# numpy array with random values
a = np.random.rand(7)
print(a)

Execution and output :
 Create a one-dimensional random value numpy Array .png

4.4. Create a two-dimensional random value numpy Array

To create a two-dimensional random value numpy Array , Just pass the size of the two dimensions to rand() Function .
In this example , We're going to create one dimension-0 The length is 2,dimension-1 The length is 4 Two dimensional random value array of .

import numpy as np
# numpy array with random values
a = np.random.rand(2, 4)
print(a)

Execution and output :
 Create a two-dimensional random value numpy Array .png

4.5. Create a three-dimensional random value numpy Array

To create a three-dimensional random value numpy Array , Just pass the respective sizes of the three dimensions to rand() Function .
In this example , We will create a dimension with a length of 4、2、3 Three dimensional random value array of .

import numpy as np
# numpy array with random values
a = np.random.rand(4, 2, 3)
print(a)

Execution and output :
 Create a three-dimensional random value numpy Array .png

4.6. Summary

In the example in this section , We learned how to use numpy.random.rand() To create arrays of random values of different dimensions .

5. take Numpy The array is stored in a file & Read from file Numpy Array

You can use numpy.save() take numpy The array is stored in a file , It can also be used at a later time numpy.load() Load the contents of the file into numpy Array .
Here is a code snippet to illustrate , First we use save() Function to write an array to a file , Then we use load() Function to load the file into a numpy Array .

# save array to file
numpy.save(file, array)
# load file to array
array = numpy.load(file)

5.1. Save array to file

In the next example , We will initialize an array , And then to write binary Pattern creates and opens a file , And finally we use numpy.save() Method to write the array to a file .

import numpy as np
# initialize an array
arr = np.array([[[11,11,9,9],[11,0,2,0]],
[[10,14,9,14],[0,1,11,11]]])
# open a binary file in write mode
file = open("arr", "wb")
# save array to the file
np.save(file, arr)
# close the file
file.close()

Execution and output :
 Save array to file .png

View the current program working directory ( The project directory ) It's called arr File generation for :
 The project directory was found to be named arr File generation for .png

Please note that after saving the array to the file , Don't forget to close the file .

5.2. Load from file numpy Array

In this example , We're going to load an array from the file . We will save the array to a file based on the above , Continue to read the array from the file .

import numpy as np
# initialize an array
arr = np.array([[[11,11,9,9],[11,0,2,0]],
[[10,14,9,14],[0,1,11,11]]])
# open a binary file in write mode
file = open("arr", "wb")
# save array to the file
np.save(file, arr)
# close the file
file.close()
# open the file in read binary mode
file = open("arr", "rb")
# read the file to numpy array
arr1 = np.load(file)
print(arr1)
# close the file
file.close()

Execution and output :
 Load from file numpy Array .png

You can see , We have successfully read from the file numpy Array and use this array to generate an object .

5.3. Summary

In this section , We learned how to put a numpy Array saved to file , And how to load from a file numpy Array into an object in the program .

Reference material

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

  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