简介
本全面教程将探讨如何使用NumPy在Python中进行强大的多维数组操作。无论你是数据科学家、研究人员还是程序员,了解如何高效处理复杂的数组结构对于高级计算任务和数据分析都至关重要。
本全面教程将探讨如何使用NumPy在Python中进行强大的多维数组操作。无论你是数据科学家、研究人员还是程序员,了解如何高效处理复杂的数组结构对于高级计算任务和数据分析都至关重要。
NumPy(数值 Python)是 Python 中科学计算的基础库,提供了用于处理多维数组的强大工具。数组是 NumPy 的核心数据结构,支持高效的数值运算和高级数学功能。
import numpy as np
## 创建一维数组
one_dim_array = np.array([1, 2, 3, 4, 5])
## 创建二维数组
two_dim_array = np.array([[1, 2, 3], [4, 5, 6]])
## 使用特定函数创建数组
zeros_array = np.zeros((3, 3)) ## 3x3 的零数组
ones_array = np.ones((2, 4)) ## 2x4 的一数组
range_array = np.arange(0, 10, 2) ## 从 0 到 10 步长为 2 的数组
| 数据类型 | 描述 | 示例 |
|---|---|---|
| int | 整数 | np.array([1, 2, 3], dtype=int) |
| float | 浮点数 | np.array([1.1, 2.2, 3.3], dtype=float) |
| complex | 复数 | np.array([1+2j, 3+4j]) |
## 基本数组属性
print(one_dim_array.shape) ## 数组维度
print(one_dim_array.dtype) ## 数据类型
print(one_dim_array.ndim) ## 维度数量
print(one_dim_array.size) ## 元素总数
## 重塑数组
original_array = np.arange(12)
reshaped_array = original_array.reshape(3, 4)
## 基本索引
print(two_dim_array[0, 1]) ## 访问特定元素
print(two_dim_array[:, 1]) ## 选择整列
## 高级切片
subset = two_dim_array[0:2, 1:3]
由于以下原因,NumPy 数组在数值运算方面比标准 Python 列表快得多:
学习 NumPy 时,实践是关键。LabEx 提供交互式环境来实验 NumPy 数组并提升你在科学计算方面的技能。
npimport numpy as np
## 基本算术运算
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
## 逐元素加法
add_result = a + b
## 逐元素乘法
mult_result = a * b
## 标量运算
scalar_mult = a * 2
## 高级数学运算
sin_values = np.sin(a)
exp_values = np.exp(a)
sqrt_values = np.sqrt(a)
## 比较运算
comparison = a > 2
masked_array = np.where(a > 2, a, 0)
| 函数 | 描述 | 示例 |
|---|---|---|
np.sum() |
计算总和 | np.sum(array) |
np.mean() |
计算平均值 | np.mean(array) |
np.max() |
找到最大值 | np.max(array) |
np.min() |
找到最小值 | np.min(array) |
## 矩阵运算
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
## 矩阵乘法
matrix_product = np.dot(matrix_a, matrix_b)
## 转置
transposed_matrix = matrix_a.T
## 特征值和特征向量
eigenvalues, eigenvectors = np.linalg.eig(matrix_a)
## 广播示例
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20, 30])
## 自动维度扩展
result = a + b
## 统计计算
data = np.array([1, 2, 3, 4, 5])
## 各种统计函数
mean_value = np.mean(data)
median_value = np.median(data)
std_deviation = np.std(data)
variance = np.var(data)
在实践数组运算时,LabEx 建议专注于向量化运算以获得最佳性能和可读性。
import numpy as np
## 创建示例数组
arr = np.array([10, 20, 30, 40, 50])
## 布尔索引
mask = arr > 25
filtered_arr = arr[mask]
## 整数数组索引
indices = np.array([0, 2, 4])
selected_elements = arr[indices]
## 创建结构化数组
employee_dtype = np.dtype([
('name', 'U10'),
('age', 'i4'),
('salary', 'f8')
])
employees = np.array([
('Alice', 30, 5000.0),
('Bob', 35, 6000.0)
], dtype=employee_dtype)
| 技术 | 描述 | 示例 |
|---|---|---|
flatten() |
创建展平数组的副本 | arr.flatten() |
ravel() |
创建展平数组的视图 | arr.ravel() |
reshape() |
更改数组维度 | arr.reshape(2,3) |
## 向量化条件赋值
arr = np.array([1, 2, 3, 4, 5])
np.where(arr > 3, arr * 2, arr)
## 通用函数(ufuncs)
def custom_operation(x):
return x ** 2 + 2 * x
vectorized_func = np.vectorize(custom_operation)
result = vectorized_func(arr)
## 内存视图和引用
a = np.arange(10)
b = a[2:7] ## 创建视图,而非副本
## 内存高效数据类型
small_int_array = np.array([1, 2, 3], dtype=np.int8)
## 线性代数操作
matrix = np.random.rand(3, 3)
## 矩阵分解
U, S, V = np.linalg.svd(matrix)
## 求解线性方程
A = np.array([[1, 2], [3, 4]])
B = np.array([5, 11])
solution = np.linalg.solve(A, B)
## Numba 加速
from numba import jit
@jit(nopython=True)
def fast_computation(arr):
return arr ** 2 + 2 * arr
## 高级随机生成
random_normal = np.random.normal(0, 1, (3, 3))
random_uniform = np.random.uniform(0, 1, (2, 2))
高级数组技术需要实践。LabEx 建议尝试不同方法,以了解它们的细微行为和性能特征。
通过掌握 NumPy 的数组操作技术,Python 程序员可以开启复杂的数据处理能力。本教程为你提供了创建、转换和优化多维数组的基本技能,从而实现更高效、强大的科学计算和数据分析工作流程。