Backend Development
Python Tutorial
Detailed explanation of the operation of arrays by Python Numpy libraryDetailed explanation of the operation of arrays by Python Numpy library

1. Introduction
NumPy (Numerical Python) is an extension library for the Python language that supports a large number of Dimensional array and matrix operations, in addition to providing a large number of mathematical function libraries for array operations. The main data structure is the ndarray array.
NumPy is often used together with SciPy (Scientific Python) and Matplotlib (plotting library), a combination widely used as a replacement for MatLab.
SciPy is an open source Python algorithm library and mathematical toolkit. SciPy includes modules for optimization, linear algebra, integration, interpolation, special functions, fast Fourier transform, signal processing and image processing, solving ordinary differential equations, and other calculations commonly used in science and engineering.
Matplotlib is a visual operating interface for the Python programming language and its numerical mathematics extension package NumPy.
2. Create
Create one-dimensional array
(1) Create directly: np.array([1, 2, 3, 4, 5, 6])
(2) Create from python list: np.array(list([1, 2, 3, 4, 5, 6]))
Create constants One-dimensional data of value
(1) Create a constant value with 0: np.zeros(n,dytpe=float/int)
(2) Create a constant value with 1 Value: np.ones(n)
(3) Create an empty array: np.empty(4)
Create an array with increasing elements
( 1) Incremental array starting from 0: np.arange(8)
(2) Given interval, custom step size: np.arange(0,1,0.2)
(3) Given an interval, customize the number: np.linspace(-1,1,50)
Create a multi-dimensional array: Create a single-dimensional array and then add it to the multi-dimensional array
# 数组的结构一定是np.array([]) 无论数组中间存放的是多少“层”数据 # 二维数组相当于存放的是“两层”数组而已 arr1=np.array(list([1, 2, 3, 4, 5])) arr2=np.array([arr1,[1,0,0,1,0]]) # 2*5的两维数组 arr3=np.array(list([[0,0,1,1,1],[1,1,1,0,0],[2,3,4,5,6]])) # 3*5的两维数组 arrx=np.array([arr1,list([1, 2, 3, 4, 5],[1,1,1,0,0])]) # 报错 arry=np.array([list([[ 1,2,3, 7, 11],[2,3,4,5,6]]),[1, 2, 3, 4, 5]]) # 报错
Related recommendations: "Python Video Tutorial"
Create (n*m)-dimensional data with constant values
(1) Create a constant value of 0: np.zeros((n*m),dytpe=float/int)
(2) Create a constant value with 1: np.ones((n*m))
(3 )Create an empty array: np.empty((n*m))
Create an array of random numbers
Generate a random number seed:
(1) np.random.seed()
(2) np.random.RandomState()
Generate random numbers:
Generates yes Random array with regular distribution
(1) Binomial distribution: np.random.binomial(n, p, size)
(2) Normal distribution: np.random.normal(loc , scale, size)
Convert csv files into arrays or arrays
Use np.genfromtxt('csv file name', delimiter = 'delimiter in the file') function Convert the file into an array
csv_array = np.genfromtxt('sample.csv', delimiter=',') print(csv_array)
3. Transformation of the array
Generates the function of array/matrix transposition, that is, the exchange of row and column numbers, use .T
a = np.array([[32, 15, 6, 9, 14],
[12, 10, 5, 23, 1],
[2, 16, 13, 40, 37]])
print(a.T)
-------------------
# 结果如下
[[32 12 2]
[15 10 16]
[ 6 5 13]
[ 9 23 40]
[14 1 37]] Change the shape of the array:
(1) arr.resize(n,m): The arr.resize(n,m) function modifies the array in place, requiring: the number of elements must be consistent
a=np.arange(8) a.resize(2,4) print(a) --------------------------- [[0 1 2 3] [4 5 6 7]]
(2) arr.reshape(n,m): If the parameter of a certain dimension is -1, it means that the total number of elements will be calculated based on the other dimension.
a=np.arange(8).reshape(-1,1) print(a) ----------------- [[0] [1] [2] [3] [4] [5] [6] [7]]
Will one Raising the dimension to two dimensions: np.newaxis
np.newaxis actually means directly increasing the dimension. We generally do not add too many dimensions to the array. Here is an example of increasing one dimension to two dimensions:
(1) Increase the row dimension: arr[np.newaxis, :]
(2) Increase the column dimension: arr[:, np.newaxis]
a=np.arange(8) a # array([0, 1, 2, 3, 4, 5, 6, 7]) a.shape # (8,) a[np.newaxis, :] # array([[0, 1, 2, 3, 4, 5, 6, 7]]) a.shape # (8,) a[: , np.newaxis] # array([[0],[1],[2],[3],[4],[5],[6],[7]]) a.shape # (8,)
Dimensionality reduction : arr.ravel()
arr.ravel() function when reducing dimensions: the default is to generate a new array in row order (that is, read line by line); if the parameter "F" is passed in, the column order is reduced Dimensions generate new array
a=np.array([[1,2],[3,4]]) a.ravel() a.ravel('F') ---------------------------- # 结果 array([1, 2, 3, 4]) # 结果 array([1, 3, 2, 4])
4. Calculation
Perform calculation operations on arrays
(1) Add and subtract elements
a=np.arange(8).reshape(2,4) # array([[0, 1, 2, 3], [4, 5, 6, 7]])
b=np.random.randint(8,size=(2,4)) # array([[1, 2, 5, 3], [4, 1, 0, 6]])
a+b
a-b
----------------------------
# a+b和a-b结果分别是:
array([[ 1, 3, 7, 6],
[ 8, 6, 6, 13]])
array([[-1, -1, -3, 0],
[ 0, 4, 6, 1]]) (2) Multiplication: square/multiply the elements in the matrix
a=np.arange(8).reshape(2,4) # array([[0, 1, 2, 3], [4, 5, 6, 7]])
b=np.random.randint(8,size=(2,4)) # array([[1, 2, 5, 3], [4, 1, 0, 6]])
a**2
a*b
-----------------------
# a矩阵平方/a*b矩阵中元素相乘结果分别:
array([[ 0, 1, 4, 9],
[16, 25, 36, 49]])
array([[ 0, 2, 10, 9],
[16, 5, 0, 42]])(3) Matrix*matrix:
# 要求a矩阵的行要等于b矩阵的列数;且a矩阵的列等于b矩阵的行数
a=np.arange(8).reshape(2,4) # array([[0, 1, 2, 3], [4, 5, 6, 7]])
b=np.random.randint(8,size=(4,2)) # array([[3, 0],[3, 3],[5, 6],[6, 7]])
c1 = np.dot(a,b)
c2 = a.dot(b)
----------------------
# ab矩阵相乘的结果:c1=c2
array([[ 31, 36],
[ 99, 100]])(4) Logical calculation
[Note] The list cannot be used as a whole to make logical judgments on the individual elements in it!
# 结果返回:一个数组,其中每个元素根据逻辑判断的布尔类型的结果
a > 3
-----------------------------
# 结果如下:
array([[False, False, False, False],
[ True, True, True, True]])5. Value
Get an element in a one-dimensional array: The operation is the same as the index of the list list
a = np.array([5, 2, 7, 0, 11]) a[0] # 结果为 5 a[:4] # 结果为 从头开始到索引为4结束 a[2:] # 结果为 从索引为2的开始到结尾 a[::2] # 结果为 从头开始到结尾,每2个取一个值
Get a multi-dimensional array An element, a row or a column value
a = np.array([[32, 15, 6, 9, 14],
[12, 10, 5, 23, 1],
[2, 16, 13, 40, 37]])
a[2,1] # 结果是一个元素 16
a[2][1] # 结果是一个元素 16
a[1] # 第2行 array([12, 10, 5, 23, 1])
a[:,2] # 取出全部行,第2列 [15,10,16]
a[1:3, :] # 取出[1,3)行,全部列
a[1,1:] # array([10, 5, 23, 1])Get the
# 需要注意的是,我们数据进行逻辑计算操作得到的仍然是一个数组
# 如果我们想要的是一个过滤后的数组,就需要将"逻辑判断"传入数组中
a = np.array([[32, 15, 6, 9, 14],
[12, 10, 5, 23, 1],
[2, 16, 13, 40, 37]])
a[a > 3]
a[(a > 3) | (a < 2)]
------------------------------
# 结果分别是:
array([32, 15, 6, 9, 14, 12, 10, 5, 23, 16, 13, 40, 37])
array([32, 15, 6, 9, 14, 12, 10, 5, 23, 1, 16, 13, 40, 37])that satisfies the logical operation Traversal: the result is output in rows
a = np.array([[32, 15, 6, 9, 14],
[12, 10, 5, 23, 1],
[2, 16, 13, 40, 37]])
for x in a:
print(x)
--------------------
[32 15 6 9 14]
[12 10 5 23 1]
[ 2 16 13 40 37]6. Copy/ Split/Merge
Copy: arr.cope()
Split:
(1) Equal parts: np.split(arr, n, axis=0 /1) (That is, only when the number of rows or columns can be divided evenly by n)
(2) Unequal division: np.array_split(arr, n) Default is divided into n parts by row
a = np.array([[32, 15, 6, 9, 14, 21],
[12, 10, 5, 23, 1, 10],
[2, 16, 13, 40, 37, 8]])
# 可以看到a矩阵是(3*6),所以使用np.split()只能尝试行分成3份;或者列分成2/3/6份
np.split(a,3,axis=0)
np.split(a,3,axis=1)
np.array_split(a,2)
np.array_split(a,4,axis=1)
-------------------------------------------
[array([[32, 15, 6, 9, 14, 21]]),
array([[12, 10, 5, 23, 1, 10]]),
array([[ 2, 16, 13, 40, 37, 8]])]
[array([[32, 15],
[12, 10],
[ 2, 16]]), array([[ 6, 9],
[ 5, 23],
[13, 40]]), array([[14, 21],
[ 1, 10],
[37, 8]])]
[array([[32, 15, 6, 9, 14, 21],
[12, 10, 5, 23, 1, 10]]), array([[ 2, 16, 13, 40, 37, 8]])]
[array([[32, 15],
[12, 10],
[ 2, 16]]), array([[ 6, 9],
[ 5, 23],
[13, 40]]), array([[14],
[ 1],
[37]]), array([[21],
[10],
[ 8]])]
Merge: np.concatenate((arr1, arr2, arr3), axis=0/1) Default is connected to the data
a=np.random.rand(2,3)
b=np.random.randint(1,size=(2,3))
np.concatenate((a,b,a)) # 接在下面
np.concatenate((a,b,a),axis=1) # 接在后面
------------------------
array([[0.95912866, 0.81396527, 0.809493 ],
[0.4539276 , 0.24173315, 0.63931439],
[0. , 0. , 0. ],
[0. , 0. , 0. ],
[0.95912866, 0.81396527, 0.809493 ],
[0.4539276 , 0.24173315, 0.63931439]])
array([[0.95912866, 0.81396527, 0.809493 , 0. , 0. ,
0. , 0.95912866, 0.81396527, 0.809493 ],
[0.4539276 , 0.24173315, 0.63931439, 0. , 0. ,
0. , 0.4539276 , 0.24173315, 0.63931439]])The above is the detailed content of Detailed explanation of the operation of arrays by Python Numpy library. For more information, please follow other related articles on the PHP Chinese website!
Python vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AMPython is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.
Python vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AMPython and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.
Python for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AMPython's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.
Python and C : Finding the Right ToolApr 19, 2025 am 12:04 AMWhether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.
Python for Data Science and Machine LearningApr 19, 2025 am 12:02 AMPython is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.
Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AMIs it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.
Python for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AMKey applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code
Python vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AMPython is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool





