numpy-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNumPy Best Practices
NumPy最佳实践
Expert guidelines for NumPy development, focusing on array programming, numerical computing, and performance optimization.
NumPy开发的专家指南,重点关注数组编程、数值计算和性能优化。
Code Style and Structure
代码风格与结构
- Write concise, technical Python code with accurate NumPy examples
- Prefer vectorized operations over explicit loops for performance
- Use descriptive variable names reflecting data content (e.g., ,
weights,gradients)input_array - Follow PEP 8 style guidelines for Python code
- Use functional programming patterns when appropriate
- 编写简洁、专业的Python代码,并附带准确的NumPy示例
- 为提升性能,优先使用向量化操作而非显式循环
- 使用能反映数据内容的描述性变量名(例如、
weights、gradients)input_array - 遵循Python的PEP 8风格指南
- 酌情使用函数式编程模式
Array Creation and Manipulation
数组创建与操作
- Use appropriate array creation functions: ,
np.array(),np.zeros(),np.ones(),np.empty(),np.arange()np.linspace() - Prefer or
np.zeros()for pre-allocation when array size is knownnp.empty() - Use ,
np.concatenate(),np.vstack()for combining arraysnp.hstack() - Leverage broadcasting for operations on arrays with different shapes
- 使用合适的数组创建函数:、
np.array()、np.zeros()、np.ones()、np.empty()、np.arange()np.linspace() - 当已知数组大小时,优先使用或
np.zeros()进行预分配np.empty() - 使用、
np.concatenate()、np.vstack()来合并数组np.hstack() - 利用广播机制处理不同形状数组间的操作
Indexing and Slicing
索引与切片
- Use advanced indexing with boolean arrays for conditional selection
- Prefer views over copies when possible to save memory
- Use for conditional element selection
np.where() - Understand the difference between fancy indexing (creates copy) and basic slicing (creates view)
- 使用布尔数组进行高级索引以实现条件筛选
- 尽可能优先使用视图而非副本,以节省内存
- 使用进行条件元素筛选
np.where() - 理解花式索引(会创建副本)与基础切片(会创建视图)之间的区别
Data Types
数据类型
- Specify appropriate data types explicitly using parameter
dtype - Use for memory-efficient computations when full precision is not needed
np.float32 - Be aware of integer overflow with fixed-size integer types
- Use for type conversion without unnecessary copies
np.asarray()
- 使用参数显式指定合适的数据类型
dtype - 当不需要全精度时,使用进行内存高效的计算
np.float32 - 注意固定大小整数类型的整数溢出问题
- 使用进行类型转换,避免不必要的副本
np.asarray()
Performance Optimization
性能优化
Vectorization
向量化
- Always prefer vectorized operations over Python loops
- Use NumPy universal functions (ufuncs) for element-wise operations
- Leverage for complex tensor operations
np.einsum() - Use or
np.dot()operator for matrix multiplication@
- 始终优先使用向量化操作而非Python循环
- 使用NumPy通用函数(ufuncs)进行逐元素操作
- 利用处理复杂张量操作
np.einsum() - 使用或
np.dot()运算符进行矩阵乘法@
Memory Management
内存管理
- Use to check memory layout (C-contiguous vs Fortran-contiguous)
np.ndarray.flags - Prefer in-place operations with parameter when possible
out - Use memory-mapped arrays () for large datasets
np.memmap - Be mindful of array copies vs views
- 使用检查内存布局(C连续 vs Fortran连续)
np.ndarray.flags - 尽可能使用带有参数的原地操作
out - 对大型数据集使用内存映射数组()
np.memmap - 注意区分数组副本与视图
Computation Efficiency
计算效率
- Use ,
np.sum(),np.mean()withnp.std()parameter for aggregationsaxis - Leverage ,
np.cumsum()for cumulative operationsnp.cumprod() - Use for efficient sorted array operations
np.searchsorted()
- 使用带参数的
axis、np.sum()、np.mean()进行聚合操作np.std() - 利用、
np.cumsum()进行累积操作np.cumprod() - 使用实现高效的有序数组操作
np.searchsorted()
Error Handling and Validation
错误处理与验证
- Validate input shapes and data types before computations
- Use assertions for dimension checking with informative messages
- Handle NaN and Inf values appropriately with ,
np.isnan()np.isinf() - Use context manager for controlling floating-point error handling
np.errstate()
- 在计算前验证输入的形状和数据类型
- 使用断言进行维度检查,并提供信息丰富的提示消息
- 使用、
np.isnan()妥善处理NaN和Inf值np.isinf() - 使用上下文管理器控制浮点错误处理
np.errstate()
Random Number Generation
随机数生成
- Use for modern random number generation
np.random.default_rng() - Set seeds for reproducibility:
rng = np.random.default_rng(seed=42) - Prefer the new Generator API over legacy functions
np.random - Use appropriate distributions: ,
rng.normal(),rng.uniform()rng.choice()
- 使用进行现代随机数生成
np.random.default_rng() - 设置种子以保证可复现性:
rng = np.random.default_rng(seed=42) - 优先使用新的Generator API而非旧版函数
np.random - 使用合适的分布函数:、
rng.normal()、rng.uniform()rng.choice()
Linear Algebra
线性代数
- Use for linear algebra operations
np.linalg - Leverage instead of computing inverse for linear systems
np.linalg.solve() - Use ,
np.linalg.eig()for decompositionsnp.linalg.svd() - Check matrix condition with before inversion
np.linalg.cond()
- 使用进行线性代数操作
np.linalg - 求解线性系统时,优先使用而非计算逆矩阵
np.linalg.solve() - 使用、
np.linalg.eig()进行矩阵分解np.linalg.svd() - 求逆前使用检查矩阵条件数
np.linalg.cond()
Testing and Documentation
测试与文档
- Write unit tests using with
pytestassertionsnp.testing - Use for exact comparisons
np.testing.assert_array_equal() - Use for floating-point comparisons
np.testing.assert_array_almost_equal() - Include comprehensive docstrings following NumPy docstring format
- 使用结合
pytest断言编写单元测试np.testing - 使用进行精确比较
np.testing.assert_array_equal() - 使用进行浮点数比较
np.testing.assert_array_almost_equal() - 遵循NumPy文档字符串格式,编写全面的文档字符串
Key Conventions
关键约定
- Import as
import numpy as np - Use for variables and functions
snake_case - Document array shapes in docstrings
- Profile code with to identify bottlenecks
%timeit
- 按的方式导入
import numpy as np - 变量和函数使用命名法
snake_case - 在文档字符串中说明数组形状
- 使用对代码进行性能分析,找出瓶颈
%timeit