🧮 Comprehensive Guide to NumPy: The Core of Scientific Computing in Python
NumPy is the foundational library for scientific computing in Python, providing high-performance multidimensional array objects and a plethora of mathematical functions. This article will comprehensively introduce the core concepts, features, and usage of NumPy, helping you master this powerful tool.
1. Introduction to NumPy
NumPy (Numerical Python) is the fundamental library for scientific computing in Python.
1. What is NumPy?
- An open-source Python library for efficient array and matrix operations
- Created by Travis Oliphant in 2005
- Provides high-performance multidimensional array objects (ndarray)
- Includes functionalities for linear algebra, Fourier transforms, random number generation, and more
2. Why Use NumPy?
Compared to native Python lists, NumPy arrays:
- Are over 50 times faster (due to contiguous memory storage)
- Use less memory
- Provide a rich set of mathematical functions
- Support vectorized operations (no explicit loops required)
- Serve as the foundation for many scientific computing libraries (such as Pandas, SciPy, etc.)
3. Technical Implementation of NumPy
- The core is written in C/C++ to ensure computational efficiency
- The Python interface provides ease of use
- Source code is hosted on GitHub: https://github.com/numpy/numpy
2. Installing and Importing NumPy
1. Installing NumPy
Command line
pip install numpy
2. Importing NumPy
Python code
import numpy as np # It is recommended to use np as an alias
3. Basics of NumPy Arrays
1. Creating Arrays
Example code
import numpy as np
# Create an array from a list
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)
# Two-dimensional array
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d)
# Special arrays
zeros = np.zeros((3, 3)) # Array of zeros
ones = np.ones((2, 4)) # Array of ones
range_arr = np.arange(10) # Array similar to range
random_arr = np.random.rand(3, 3) # Random array
2. Array Attributes
| Attribute | Description | Example |
|---|---|---|
<span>ndim</span> |
Number of dimensions of the array | <span>arr2d.ndim</span> → 2 |
<span>shape</span> |
Shape of the array (size of each dimension) | <span>arr2d.shape</span> → (2, 3) |
<span>size</span> |
Total number of elements in the array | <span>arr2d.size</span> → 6 |
<span>dtype</span> |
Data type of the array | <span>arr1.dtype</span> → int64 |
3. Data Types
NumPy supports a richer set of data types than Python:
| Character | Type | Description |
|---|---|---|
<span>i</span> |
Integer | e.g., int8, int16, int32, int64 |
<span>u</span> |
Unsigned Integer | e.g., uint8, uint16, uint32, uint64 |
<span>f</span> |
Floating Point | e.g., float16, float32, float64 |
<span>b</span> |
Boolean | bool_ |
<span>c</span> |
Complex | complex64, complex128 |
4. Array Operations
1. Indexing and Slicing
Example code
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# Indexing
print(arr[0]) # First element → 0
print(arr[-1]) # Last element → 9
# Slicing [start:end:step]
print(arr[1:7:2]) # From index 1 to 7, step 2 → [1 3 5]
# Indexing in a two-dimensional array
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d[1, 2]) # Second row, third column → 6
2. Array Arithmetic
Example code
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Arithmetic operations (element-wise)
print(a + b) # [5 7 9]
print(a * b) # [4 10 18]
# Broadcasting
print(a + 10) # [11 12 13]
# Matrix multiplication
print(np.dot(a, b)) # 32
3. Reshaping Arrays
Example code
arr = np.arange(12)
# Reshape the array
arr_3x4 = arr.reshape(3, 4)
print(arr_3x4)
# Flatten the array
flatten = arr_3x4.flatten()
print(flatten)
# Transpose
transposed = arr_3x4.T
print(transposed)
5. Advanced Features of NumPy
1. Array Concatenation and Splitting
Example code
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
# Vertical stacking
v_stack = np.vstack((a, b))
print(v_stack)
# Horizontal stacking
h_stack = np.hstack((a, b.T))
print(h_stack)
# Array splitting
first, second = np.hsplit(v_stack, 2)
print(first)
print(second)
2. Sorting and Searching
Example code
arr = np.array([3, 1, 4, 1, 5, 9, 2])
# Sorting
sorted_arr = np.sort(arr)
print(sorted_arr)
# Get sorting indices
indices = np.argsort(arr)
print(indices)
# Searching
where = np.where(arr > 3)
print(where)
3. Statistical Functions
Example code
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sum(arr)) # Total → 21
print(np.mean(arr)) # Mean → 3.5
print(np.max(arr)) # Maximum → 6
print(np.min(arr)) # Minimum → 1
print(np.std(arr)) # Standard deviation → 1.707825127659933
print(np.median(arr)) # Median → 3.5
6. Applications of NumPy
1. Linear Algebra
Example code
from numpy import linalg
A = np.array([[1, 2], [3, 4]])
B = np.array([5, 6])
# Solve linear equations
x = linalg.solve(A, B)
print(x)
# Calculate determinant
det = linalg.det(A)
print(det)
2. Random Number Generation
Example code
# Uniform distribution
uniform = np.random.rand(3, 3)
# Normal distribution
normal = np.random.randn(3, 3)
# Random integers
integers = np.random.randint(0, 10, size=(2, 4))
# Random shuffle
arr = np.arange(10)
np.random.shuffle(arr)