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."4metadata:5 maintainer: Mindrally6 source: https://skillmd.com/skills/mindrally/analytics-data-analysis7 upstream: https://github.com/Mindrally/skills8---910# Analytics and Data Analysis1112Guidelines for data analysis, visualization, and Jupyter-based workflows using pandas, matplotlib, seaborn, and numpy. Prioritize readability, reproducibility, and vectorized operations.1314## Workflow: Exploratory Data Analysis Pipeline15161. **Load and inspect** — Read data with `pd.read_csv()` or appropriate loader, check `.shape`, `.dtypes`, `.describe()`, and `.isnull().sum()`172. **Clean and transform** — Handle missing values, fix dtypes, rename columns, filter outliers using vectorized pandas operations183. **Explore relationships** — Use `.groupby()`, `.corr()`, and cross-tabulations to identify patterns194. **Visualize findings** — Create targeted plots with matplotlib/seaborn; label axes, add titles, use colorblind-friendly palettes205. **Validate results** — Run statistical tests, report confidence intervals, verify assumptions216. **Document and share** — Structure notebook with markdown sections, clear outputs before sharing, pin dependencies2223## Key Principles2425- Write concise, technical code with accurate Python examples26- Emphasize readability and reproducibility in data analysis workflows27- Use functional programming patterns; minimize class usage28- Leverage vectorized operations over explicit loops for performance29- Use descriptive variable naming conventions (e.g., `is_valid`, `has_data`, `total_count`)30- Adhere to PEP 8 style guidelines3132## Quick Start Example3334```python35import pandas as pd36import matplotlib.pyplot as plt37import seaborn as sns3839# Load and inspect40df = pd.read_csv("data.csv", parse_dates=["timestamp"])41print(f"Shape: {df.shape}, Missing: {df.isnull().sum().sum()}")4243# Clean: drop rows missing target, fill numeric gaps with median44df = (45 df.dropna(subset=["revenue"])46 .assign(category=lambda x: x["category"].astype("category"))47 .fillna(df.select_dtypes("number").median())48)4950# Analyze: revenue by category51summary = df.groupby("category")["revenue"].agg(["mean", "median", "std"])5253# Visualize54fig, ax = plt.subplots(figsize=(10, 6))55sns.boxplot(data=df, x="category", y="revenue", palette="colorblind", ax=ax)56ax.set_title("Revenue Distribution by Category")57ax.set_ylabel("Revenue ($)")58plt.tight_layout()59plt.savefig("revenue_by_category.png", dpi=150)60plt.show()61```6263## Data Analysis with Pandas6465### Data Manipulation Best Practices66- Use pandas for all data manipulation and analysis tasks67- Apply method chaining for clean, readable transformations68- Utilize `loc` and `iloc` for explicit data selection69- Employ `groupby` for efficient data aggregation70- Use `merge` and `join` appropriately for combining datasets7172### Performance Optimization73- Use vectorized operations instead of loops74- Utilize efficient data structures like categorical data types for low-cardinality string columns75- Consider dask for larger-than-memory datasets76- Profile code to identify and optimize bottlenecks77- Use appropriate dtypes to minimize memory usage7879### Data Validation80- Validate data types and ranges to ensure data integrity81- Use try-except blocks for error-prone operations when reading external data82- Check for missing values and handle appropriately83- Verify data shape and structure after transformations8485## Visualization Standards8687### Matplotlib Guidelines88- Use matplotlib for fine-grained customization control89- Create clear, informative plots with proper labeling90- Always include axis labels and titles91- Use consistent color schemes across related visualizations92- Save figures with appropriate resolution for the intended use9394### Seaborn for Statistical Visualizations95- Apply seaborn for statistical visualizations and attractive defaults96- Leverage built-in themes for consistent styling97- Use appropriate plot types for the data (scatter, line, bar, heatmap, etc.)98- Consider color-blindness accessibility in color palette choices99100### Accessibility in Visualizations101- Use colorblind-friendly palettes102- Include alternative text descriptions103- Ensure sufficient contrast in visual elements104- Provide data tables as alternatives to complex charts105106## Jupyter Notebook Best Practices107108### Notebook Structure109- Structure notebooks with clear markdown sections110- Begin with an overview/introduction cell111- Document analysis steps thoroughly112- Keep code cells focused and modular113- End with conclusions and key findings114115### Execution and Reproducibility116- Maintain meaningful cell execution order117- Clear outputs before sharing notebooks118- Use environment files (requirements.txt) for dependencies119- Document data sources and access methods120- Include date/version information121122### Code Organization123- Import all libraries at the notebook beginning124- Define helper functions in dedicated cells125- Use magic commands appropriately (%matplotlib inline, etc.)126- Keep individual cells concise and single-purpose127128## Technical Requirements129130### Core Dependencies131- pandas: Data manipulation and analysis132- numpy: Numerical computing133- matplotlib: Base plotting library134- seaborn: Statistical data visualization135- jupyter: Interactive computing environment136137### Extended Libraries138- scikit-learn: Machine learning tasks139- scipy: Scientific computing140- plotly: Interactive visualizations141- statsmodels: Statistical modeling142143## Analytics Implementation144145### Tracking and Measurement146- Define clear metrics and KPIs before analysis147- Document data collection methodology148- Implement proper data pipelines for reproducibility149- Create automated reporting where appropriate150- Version control notebooks and analysis scripts151152### Statistical Analysis153- Use appropriate statistical tests for the data type154- Report confidence intervals alongside point estimates155- Be cautious about p-value interpretation156- Consider effect sizes, not just statistical significance157- Document assumptions and limitations158159## Error Handling and Logging160161- Implement proper error handling in data pipelines162- Log data quality issues and anomalies163- Create validation checkpoints in analysis workflows164- Document known data quality issues165- Build in data sanity checks at key stages