Analytics and Data Analysis
Guidelines for data analysis, visualization, and Jupyter-based workflows using pandas, matplotlib, seaborn, and numpy. Prioritize readability, reproducibility, and vectorized operations.
Workflow: Exploratory Data Analysis Pipeline
- Load and inspect — Read data with
pd.read_csv() or appropriate loader, check .shape, .dtypes, .describe(), and .isnull().sum()
- Clean and transform — Handle missing values, fix dtypes, rename columns, filter outliers using vectorized pandas operations
- Explore relationships — Use
.groupby(), .corr(), and cross-tabulations to identify patterns
- Visualize findings — Create targeted plots with matplotlib/seaborn; label axes, add titles, use colorblind-friendly palettes
- Validate results — Run statistical tests, report confidence intervals, verify assumptions
- Document and share — Structure notebook with markdown sections, clear outputs before sharing, pin dependencies
Key Principles
- Write concise, technical code with accurate Python examples
- Emphasize readability and reproducibility in data analysis workflows
- Use functional programming patterns; minimize class usage
- Leverage vectorized operations over explicit loops for performance
- Use descriptive variable naming conventions (e.g.,
is_valid, has_data, total_count)
- Adhere to PEP 8 style guidelines
Quick Start Example
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load and inspect
df = pd.read_csv("data.csv", parse_dates=["timestamp"])
print(f"Shape: {df.shape}, Missing: {df.isnull().sum().sum()}")
# Clean: drop rows missing target, fill numeric gaps with median
df = (
df.dropna(subset=["revenue"])
.assign(category=lambda x: x["category"].astype("category"))
.fillna(df.select_dtypes("number").median())
)
# Analyze: revenue by category
summary = df.groupby("category")["revenue"].agg(["mean", "median", "std"])
# Visualize
fig, ax = plt.subplots(figsize=(10, 6))
sns.boxplot(data=df, x="category", y="revenue", palette="colorblind", ax=ax)
ax.set_title("Revenue Distribution by Category")
ax.set_ylabel("Revenue ($)")
plt.tight_layout()
plt.savefig("revenue_by_category.png", dpi=150)
plt.show()
Data Analysis with Pandas
Data Manipulation Best Practices
- Use pandas for all data manipulation and analysis tasks
- Apply method chaining for clean, readable transformations
- Utilize
loc and iloc for explicit data selection
- Employ
groupby for efficient data aggregation
- Use
merge and join appropriately for combining datasets
Performance Optimization
- Use vectorized operations instead of loops
- Utilize efficient data structures like categorical data types for low-cardinality string columns
- Consider dask for larger-than-memory datasets
- Profile code to identify and optimize bottlenecks
- Use appropriate dtypes to minimize memory usage
Data Validation
- Validate data types and ranges to ensure data integrity
- Use try-except blocks for error-prone operations when reading external data
- Check for missing values and handle appropriately
- Verify data shape and structure after transformations
Visualization Standards
Matplotlib Guidelines
- Use matplotlib for fine-grained customization control
- Create clear, informative plots with proper labeling
- Always include axis labels and titles
- Use consistent color schemes across related visualizations
- Save figures with appropriate resolution for the intended use
Seaborn for Statistical Visualizations
- Apply seaborn for statistical visualizations and attractive defaults
- Leverage built-in themes for consistent styling
- Use appropriate plot types for the data (scatter, line, bar, heatmap, etc.)
- Consider color-blindness accessibility in color palette choices
Accessibility in Visualizations
- Use colorblind-friendly palettes
- Include alternative text descriptions
- Ensure sufficient contrast in visual elements
- Provide data tables as alternatives to complex charts
Jupyter Notebook Best Practices
Notebook Structure
- Structure notebooks with clear markdown sections
- Begin with an overview/introduction cell
- Document analysis steps thoroughly
- Keep code cells focused and modular
- End with conclusions and key findings
Execution and Reproducibility
- Maintain meaningful cell execution order
- Clear outputs before sharing notebooks
- Use environment files (requirements.txt) for dependencies
- Document data sources and access methods
- Include date/version information
Code Organization
- Import all libraries at the notebook beginning
- Define helper functions in dedicated cells
- Use magic commands appropriately (%matplotlib inline, etc.)
- Keep individual cells concise and single-purpose
Technical Requirements
Core Dependencies
- pandas: Data manipulation and analysis
- numpy: Numerical computing
- matplotlib: Base plotting library
- seaborn: Statistical data visualization
- jupyter: Interactive computing environment
Extended Libraries
- scikit-learn: Machine learning tasks
- scipy: Scientific computing
- plotly: Interactive visualizations
- statsmodels: Statistical modeling
Analytics Implementation
Tracking and Measurement
- Define clear metrics and KPIs before analysis
- Document data collection methodology
- Implement proper data pipelines for reproducibility
- Create automated reporting where appropriate
- Version control notebooks and analysis scripts
Statistical Analysis
- Use appropriate statistical tests for the data type
- Report confidence intervals alongside point estimates
- Be cautious about p-value interpretation
- Consider effect sizes, not just statistical significance
- Document assumptions and limitations
Error Handling and Logging
- Implement proper error handling in data pipelines
- Log data quality issues and anomalies
- Create validation checkpoints in analysis workflows
- Document known data quality issues
- Build in data sanity checks at key stages
1---2name: analytics-data-analysis3description: Best practices for analytics, data analysis, and visualization using Python, pandas, matplotlib, seaborn, and Jupyter notebooks. Use when performing exploratory data analysis, building data pipelines, creating statistical visualizations, writing Jupyter notebooks, cleaning and transforming datasets, or implementing analytics dashboards.4---56# Analytics and Data Analysis78Guidelines for data analysis, visualization, and Jupyter-based workflows using pandas, matplotlib, seaborn, and numpy. Prioritize readability, reproducibility, and vectorized operations.910## Workflow: Exploratory Data Analysis Pipeline11121. **Load and inspect** — Read data with `pd.read_csv()` or appropriate loader, check `.shape`, `.dtypes`, `.describe()`, and `.isnull().sum()`132. **Clean and transform** — Handle missing values, fix dtypes, rename columns, filter outliers using vectorized pandas operations143. **Explore relationships** — Use `.groupby()`, `.corr()`, and cross-tabulations to identify patterns154. **Visualize findings** — Create targeted plots with matplotlib/seaborn; label axes, add titles, use colorblind-friendly palettes165. **Validate results** — Run statistical tests, report confidence intervals, verify assumptions176. **Document and share** — Structure notebook with markdown sections, clear outputs before sharing, pin dependencies1819## Key Principles2021- Write concise, technical code with accurate Python examples22- Emphasize readability and reproducibility in data analysis workflows23- Use functional programming patterns; minimize class usage24- Leverage vectorized operations over explicit loops for performance25- Use descriptive variable naming conventions (e.g., `is_valid`, `has_data`, `total_count`)26- Adhere to PEP 8 style guidelines2728## Quick Start Example2930```python31import pandas as pd32import matplotlib.pyplot as plt33import seaborn as sns3435# Load and inspect36df = pd.read_csv("data.csv", parse_dates=["timestamp"])37print(f"Shape: {df.shape}, Missing: {df.isnull().sum().sum()}")3839# Clean: drop rows missing target, fill numeric gaps with median40df = (41 df.dropna(subset=["revenue"])42 .assign(category=lambda x: x["category"].astype("category"))43 .fillna(df.select_dtypes("number").median())44)4546# Analyze: revenue by category47summary = df.groupby("category")["revenue"].agg(["mean", "median", "std"])4849# Visualize50fig, ax = plt.subplots(figsize=(10, 6))51sns.boxplot(data=df, x="category", y="revenue", palette="colorblind", ax=ax)52ax.set_title("Revenue Distribution by Category")53ax.set_ylabel("Revenue ($)")54plt.tight_layout()55plt.savefig("revenue_by_category.png", dpi=150)56plt.show()57```5859## Data Analysis with Pandas6061### Data Manipulation Best Practices62- Use pandas for all data manipulation and analysis tasks63- Apply method chaining for clean, readable transformations64- Utilize `loc` and `iloc` for explicit data selection65- Employ `groupby` for efficient data aggregation66- Use `merge` and `join` appropriately for combining datasets6768### Performance Optimization69- Use vectorized operations instead of loops70- Utilize efficient data structures like categorical data types for low-cardinality string columns71- Consider dask for larger-than-memory datasets72- Profile code to identify and optimize bottlenecks73- Use appropriate dtypes to minimize memory usage7475### Data Validation76- Validate data types and ranges to ensure data integrity77- Use try-except blocks for error-prone operations when reading external data78- Check for missing values and handle appropriately79- Verify data shape and structure after transformations8081## Visualization Standards8283### Matplotlib Guidelines84- Use matplotlib for fine-grained customization control85- Create clear, informative plots with proper labeling86- Always include axis labels and titles87- Use consistent color schemes across related visualizations88- Save figures with appropriate resolution for the intended use8990### Seaborn for Statistical Visualizations91- Apply seaborn for statistical visualizations and attractive defaults92- Leverage built-in themes for consistent styling93- Use appropriate plot types for the data (scatter, line, bar, heatmap, etc.)94- Consider color-blindness accessibility in color palette choices9596### Accessibility in Visualizations97- Use colorblind-friendly palettes98- Include alternative text descriptions99- Ensure sufficient contrast in visual elements100- Provide data tables as alternatives to complex charts101102## Jupyter Notebook Best Practices103104### Notebook Structure105- Structure notebooks with clear markdown sections106- Begin with an overview/introduction cell107- Document analysis steps thoroughly108- Keep code cells focused and modular109- End with conclusions and key findings110111### Execution and Reproducibility112- Maintain meaningful cell execution order113- Clear outputs before sharing notebooks114- Use environment files (requirements.txt) for dependencies115- Document data sources and access methods116- Include date/version information117118### Code Organization119- Import all libraries at the notebook beginning120- Define helper functions in dedicated cells121- Use magic commands appropriately (%matplotlib inline, etc.)122- Keep individual cells concise and single-purpose123124## Technical Requirements125126### Core Dependencies127- pandas: Data manipulation and analysis128- numpy: Numerical computing129- matplotlib: Base plotting library130- seaborn: Statistical data visualization131- jupyter: Interactive computing environment132133### Extended Libraries134- scikit-learn: Machine learning tasks135- scipy: Scientific computing136- plotly: Interactive visualizations137- statsmodels: Statistical modeling138139## Analytics Implementation140141### Tracking and Measurement142- Define clear metrics and KPIs before analysis143- Document data collection methodology144- Implement proper data pipelines for reproducibility145- Create automated reporting where appropriate146- Version control notebooks and analysis scripts147148### Statistical Analysis149- Use appropriate statistical tests for the data type150- Report confidence intervals alongside point estimates151- Be cautious about p-value interpretation152- Consider effect sizes, not just statistical significance153- Document assumptions and limitations154155## Error Handling and Logging156157- Implement proper error handling in data pipelines158- Log data quality issues and anomalies159- Create validation checkpoints in analysis workflows160- Document known data quality issues161- Build in data sanity checks at key stages