Master Numpy: From Arrays to Matrix Operations in Python
This guide introduces Numpy basics, covering installation, array creation, indexing, slicing, universal functions, and matrix operations such as addition, multiplication, inversion, determinants, and eigenvalue analysis, all illustrated with clear Python code examples.
1 Numpy
In Python we commonly use the Numpy library for array creation and function operations. It can be installed via the command line using:
<code>pip install numpy</code>If you already use Anaconda, the library is pre‑installed and can be imported as np :
<code>import numpy as np</code>2 Basic data type array
The basic data type in Numpy is array , similar to Python’s list but more powerful.
2.1 Creating array
Arrays can be created from a list:
<code>np.array([1,2,3])</code>Multi‑dimensional arrays can also be created:
<code>np.array([[1,2,3],[4,5,6]]) # 2 rows, 3 columns</code>2.2 Generating arithmetic sequences linspace and arange
Use linspace to generate a sequence with a specified number of elements:
<code>np.linspace(1,10,5) # [1., 3.25, 5.5, 7.75, 10.]</code>Or use arange to specify step size:
<code>np.arange(1,10,2) # [1, 3, 5, 7, 9]</code>2.3 Shape and size
<code>a = np.array([[1,2,3],[4,5,6]])
a.shape # (2, 3)
a.size # 6</code>Arrays can be reshaped, e.g., to 3 rows and 2 columns:
<code>a.reshape((3,2))</code>2.4 Indexing data
<code>a[1,2] # element in second row, third column
a[:,2] # third column
a[:,[1,2]] # second and third columns</code>2.5 Filtering data
<code>a[a>2] # values greater than 2
a[(a>2)&(a<6)] # values between 2 and 6</code>3 Universal functions
Numpy’s universal functions ( ufuncs ) operate on entire arrays, unlike Python’s math module which works on scalars.
<code>import math
import numpy as np
math.log(20)
np.log(20)
np.log([1,2,3])</code>4 Matrix creation and operations
Numpy’s linalg module handles matrix calculations.
4.1 Common matrix generation
<code>np.eye(3) # identity matrix
np.diag([1,2,3,4]) # diagonal matrix
np.zeros((3,4)) # 3×4 zero matrix</code>4.2 Matrix addition, subtraction, multiplication, inverse
<code>A = np.array([[1,3,2],[4,1,5],[3,3,1]])
B = np.array([[3,3,1],[5,2,6],[1,2,3]])
A + B # addition
A - B # subtraction
A @ B # matrix multiplication
np.linalg.inv(A) # inverse</code>4.3 Determinant, eigenvalues, eigenvectors
<code>np.linalg.det(A) # determinant
values, vectors = np.linalg.eig(A) # eigenvalues and eigenvectors</code>Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.