pandas-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePandas Best Practices
Pandas最佳实践
Expert guidelines for Pandas development, focusing on data manipulation, analysis, and efficient DataFrame operations.
针对Pandas开发的专家指南,聚焦数据处理、分析以及高效的DataFrame操作。
Code Style and Structure
代码风格与结构
- Write concise, technical responses with accurate Python examples
- Prioritize reproducibility in data analysis workflows
- Use functional programming; avoid unnecessary classes
- Prefer vectorized operations over explicit loops
- Use descriptive variable names reflecting data content
- Follow PEP 8 style guidelines
- 编写简洁、专业的回复,并附带准确的Python示例
- 优先保证数据分析工作流的可复现性
- 使用函数式编程;避免不必要的类
- 优先选择向量化操作,而非显式循环
- 使用能反映数据内容的描述性变量名
- 遵循PEP 8风格指南
DataFrame Creation and I/O
DataFrame创建与输入输出
- Use ,
pd.read_csv(),pd.read_excel()with appropriate parameterspd.read_json() - Specify parameter to ensure correct data types on load
dtype - Use for automatic datetime parsing
parse_dates - Set when the data has a natural index column
index_col - Use for reading large files incrementally
chunksize
- 结合合适的参数使用、
pd.read_csv()、pd.read_excel()pd.read_json() - 指定参数,确保加载时数据类型正确
dtype - 使用自动解析日期时间
parse_dates - 当数据有自然索引列时,设置
index_col - 对于大文件,使用进行增量读取
chunksize
Data Selection
数据选择
- Use for label-based indexing
.loc[] - Use for integer position-based indexing
.iloc[] - Avoid chained indexing (e.g., ) - use
df['col'][0]or.locinstead.iloc - Use boolean indexing for conditional selection:
df[df['col'] > value] - Use method for complex filtering conditions
.query()
- 使用进行基于标签的索引
.loc[] - 使用进行基于整数位置的索引
.iloc[] - 避免链式索引(例如)——改用
df['col'][0]或.loc.iloc - 使用布尔索引进行条件筛选:
df[df['col'] > value] - 复杂筛选条件使用方法
.query()
Method Chaining
方法链式调用
- Prefer method chaining for data transformations when possible
- Use for applying custom functions in a chain
.pipe() - Chain operations like ,
.assign(),.query(),.groupby().agg() - Keep chains readable by breaking across multiple lines
- 尽可能优先使用方法链式调用进行数据转换
- 使用在链式调用中应用自定义函数
.pipe() - 链式调用、
.assign()、.query()、.groupby()等操作.agg() - 通过换行保持链式调用的可读性
Data Cleaning and Validation
数据清洗与验证
Missing Data
缺失数据
- Check for missing data with and
.isna().info() - Handle missing data appropriately: ,
.fillna(), or imputation.dropna() - Use for nullable integer and boolean types
pd.NA - Document decisions about missing data handling
- 使用和
.isna()检查缺失数据.info() - 合理处理缺失数据:使用、
.fillna()或插补法.dropna() - 对于可空整数和布尔类型,使用
pd.NA - 记录缺失数据处理的决策
Data Quality Checks
数据质量检查
- Implement data quality checks at the beginning of analysis
- Validate data types with and convert as needed
.dtypes - Check for duplicates with and handle appropriately
.duplicated() - Use for quick statistical overview
.describe()
- 在分析开始时实施数据质量检查
- 使用验证数据类型,并按需转换
.dtypes - 使用检查重复数据并合理处理
.duplicated() - 使用快速获取统计概览
.describe()
Type Conversion
类型转换
- Use for explicit type conversion
.astype() - Use for date parsing
pd.to_datetime() - Use with
pd.to_numeric()for safe numeric conversionerrors='coerce' - Utilize categorical data types for low-cardinality string columns
- 使用进行显式类型转换
.astype() - 使用解析日期
pd.to_datetime() - 使用并设置
pd.to_numeric()进行安全的数值转换errors='coerce' - 对低基数字符串列使用分类数据类型
Grouping and Aggregation
分组与聚合
GroupBy Operations
GroupBy操作
- Use for efficient aggregation operations
.groupby() - Specify aggregation functions with for multiple operations
.agg() - Use named aggregation for clearer output column names
- Consider for broadcasting results back to original shape
.transform()
- 使用进行高效的聚合操作
.groupby() - 使用指定多个聚合函数
.agg() - 使用命名聚合让输出列名更清晰
- 考虑使用将结果广播回原始形状
.transform()
Pivot Tables and Reshaping
透视表与数据重塑
- Use for multi-dimensional aggregation
.pivot_table() - Use to convert wide to long format
.melt() - Use to convert long to wide format
.pivot() - Use and
.stack()for hierarchical index manipulation.unstack()
- 使用进行多维聚合
.pivot_table() - 使用将宽格式转换为长格式
.melt() - 使用将长格式转换为宽格式
.pivot() - 使用和
.stack()处理层次化索引.unstack()
Performance Optimization
性能优化
Memory Efficiency
内存效率
- Use categorical data types for low-cardinality strings
- Downcast numeric types when appropriate
- Use and
pd.eval()for large expression evaluation.eval()
- 对低基数字符串列使用分类数据类型
- 适时向下转换数值类型
- 使用和
pd.eval()处理大型表达式.eval()
Computation Speed
计算速度
- Use vectorized operations instead of with row-wise functions
.apply() - Prefer built-in aggregation functions over custom ones
- Use or
.valuesfor NumPy operations when faster.to_numpy()
- 使用向量化操作替代带逐行函数的
.apply() - 优先使用内置聚合函数而非自定义函数
- 当速度更快时,使用或
.values进行NumPy操作.to_numpy()
Avoiding Common Pitfalls
避免常见陷阱
- Avoid iterating with - use vectorized operations
.iterrows() - Don't modify DataFrames while iterating
- Be aware of SettingWithCopyWarning - use when needed
.copy() - Avoid growing DataFrames row by row - collect in list and create once
- 避免使用迭代——改用向量化操作
.iterrows() - 迭代时不要修改DataFrame
- 注意SettingWithCopyWarning——必要时使用
.copy() - 避免逐行扩展DataFrame——先收集到列表中再一次性创建
Time Series Operations
时间序列操作
- Use for time series data
DatetimeIndex - Leverage for time-based aggregation
.resample() - Use and
.shift()for lag operations.diff() - Use and
.rolling()for window calculations.expanding()
- 对时间序列数据使用
DatetimeIndex - 利用进行基于时间的聚合
.resample() - 使用和
.shift()进行滞后操作.diff() - 使用和
.rolling()进行窗口计算.expanding()
Merging and Joining
合并与连接
- Use for SQL-style joins
.merge() - Specify parameter: 'inner', 'outer', 'left', 'right'
how - Use parameter to check join cardinality
validate - Use for stacking DataFrames
.concat()
- 使用实现类SQL风格的连接
.merge() - 指定参数:'inner'、'outer'、'left'、'right'
how - 使用参数检查连接的基数
validate - 使用堆叠DataFrame
.concat()
Key Conventions
关键约定
- Import as
import pandas as pd - Use for column names when possible
snake_case - Document data sources and transformations
- Keep notebooks reproducible with clear cell execution order
- 导入时使用
import pandas as pd - 尽可能对列名使用命名法
snake_case - 记录数据源与转换过程
- 保持Notebook的可复现性,确保单元格执行顺序清晰