Skill: AI data analyst
Purpose
Perform comprehensive data analysis, statistical modeling, and data visualization by writing and executing self-contained Python scripts. Generate publication-quality charts, statistical reports, and actionable insights from data files or databases.
When to use this skill
- You need to analyze datasets to understand patterns, trends, or relationships.
- You want to perform statistical tests or build predictive models.
- You need data visualizations (charts, graphs, dashboards) to communicate findings.
- You're doing exploratory data analysis (EDA) to understand data structure and quality.
- You need to clean, transform, or merge datasets for analysis.
- You want reproducible analysis with documented methodology and code.
Key capabilities
Unlike point-solution data analysis tools:
- Full Python ecosystem: Access to pandas, numpy, scikit-learn, statsmodels, matplotlib, seaborn, plotly, and more.
- Runs locally: Your data stays on your machine; no uploads to third-party services.
- Reproducible: All analysis is code-based and version controllable.
- Customizable: Extend with any Python library or custom analysis logic.
- Publication-quality output: Generate professional charts and reports.
- Statistical rigor: Access to comprehensive statistical and ML libraries.
Inputs
- Data sources: CSV files, Excel files, JSON, Parquet, or database connections.
- Analysis goals: Questions to answer or hypotheses to test.
- Variables of interest: Specific columns, metrics, or dimensions to focus on.
- Output preferences: Chart types, report format, statistical tests needed.
- Context: Business domain, data dictionary, or known data quality issues.
Out of scope
- Real-time streaming data analysis (use appropriate streaming tools).
- Extremely large datasets requiring distributed computing (use Spark/Dask instead).
- Production ML model deployment (use ML ops tools and infrastructure).
- Live dashboarding (use BI tools like Tableau/Looker for operational dashboards).
Conventions and best practices
Python environment
- Use virtual environments to isolate dependencies.
- Install only necessary packages for the specific analysis.
- Document all dependencies in
requirements.txt or environment.yml.
Code structure
- Write self-contained scripts that can be re-run by others.
- Use clear variable names and add comments for complex logic.
- Separate concerns: data loading, cleaning, analysis, visualization.
- Save intermediate results to files when analysis is multi-stage.
Data handling
- Never modify source data files – work on copies or in-memory dataframes.
- Document data transformations clearly in code comments.
- Handle missing values explicitly and document approach.
- Validate data quality before analysis (check for nulls, outliers, duplicates).
Visualization best practices
- Choose appropriate chart types for the data and question.
- Use clear labels, titles, and legends on all charts.
- Apply appropriate color schemes (colorblind-friendly when possible).
- Include sample sizes and confidence intervals where relevant.
- Save visualizations in high-resolution formats (PNG 300 DPI, SVG for vector graphics).
Statistical analysis
- State assumptions for statistical tests clearly.
- Check assumptions before applying tests (normality, homoscedasticity, etc.).
- Report effect sizes not just p-values.
- Use appropriate corrections for multiple comparisons.
- Explain practical significance in addition to statistical significance.
Required behavior
- Understand the question: Clarify what insights or decisions the analysis should support.
- Explore the data: Check structure, types, missing values, distributions, outliers.
- Clean and prepare: Handle missing data, outliers, and transformations appropriately.
- Analyze systematically: Apply appropriate statistical methods or ML techniques.
- Visualize effectively: Create clear, informative charts that answer the question.
- Generate insights: Translate statistical findings into actionable business insights.
- Document thoroughly: Explain methodology, assumptions, limitations, and conclusions.
- Make reproducible: Ensure others can re-run the analysis and get the same results.
Required artifacts
- Analysis script(s): Well-documented Python code performing the analysis.
- Visualizations: Charts saved as high-quality image files (PNG/SVG).
- Analysis report: Markdown or text document summarizing:
- Research question and methodology
- Data description and quality assessment
- Key findings with supporting statistics
- Visualizations with interpretations
- Limitations and caveats
- Recommendations or next steps
- Requirements file:
requirements.txt with all dependencies.
- Sample data (if appropriate and non-sensitive): Small sample for reproducibility.
Implementation checklist
1. Data exploration and preparation
2. Data cleaning and transformation
3. Analysis execution
4. Visualization
5. Reporting
6. Reproducibility
Verification
Run the following to verify the analysis:
# Create virtual environment
python3 -m venv venv
source venv/bin/activate # or `venv\Scripts\activate` on Windows
# Install dependencies
pip install -r requirements.txt
# Run analysis script
python analysis.py
# Check outputs generated
ls -lh outputs/
The skill is complete when:
- Analysis script runs without errors from clean environment.
- All required visualizations are generated in high quality.
- Report clearly explains methodology, findings, and limitations.
- Results are interpretable and actionable.
- Code is well-documented and reproducible.
Common analysis patterns
Exploratory Data Analysis (EDA)
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load and inspect data
df = pd.read_csv('data.csv')
print(df.info())
print(df.describe())
# Check for missing values
print(df.isnull().sum())
# Visualize distributions
df.hist(figsize=(12, 10), bins=30)
plt.tight_layout()
plt.savefig('distributions.png', dpi=300)
# Check correlations
corr = df.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.savefig('correlations.png', dpi=300)
Time series analysis
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
# Load time series data
df = pd.read_csv('timeseries.csv', parse_dates=['date'])
df.set_index('date', inplace=True)
# Decompose time series
decomposition = seasonal_decompose(df['value'], model='additive', period=30)
fig = decomposition.plot()
fig.set_size_inches(12, 8)
plt.savefig('decomposition.png', dpi=300)
# Calculate rolling statistics
df['rolling_mean'] = df['value'].rolling(window=7).mean()
df['rolling_std'] = df['value'].rolling(window=7).std()
# Plot with trends
plt.figure(figsize=(12, 6))
plt.plot(df['value'], label='Original')
plt.plot(df['rolling_mean'], label='7-day Moving Avg', linewidth=2)
plt.fill_between(df.index,
df['rolling_mean'] - df['rolling_std'],
df['rolling_mean'] + df['rolling_std'],
alpha=0.3)
plt.legend()
plt.savefig('trends.png', dpi=300)
Statistical hypothesis testing
from scipy import stats
import numpy as np
# Compare two groups
group_a = df[df['group'] == 'A']['metric']
group_b = df[df['group'] == 'B']['metric']
# Check normality
_, p_norm_a = stats.shapiro(group_a)
_, p_norm_b = stats.shapiro(group_b)
# Choose appropriate test
if p_norm_a > 0.05 and p_norm_b > 0.05:
# Parametric test (t-test)
statistic, p_value = stats.ttest_ind(group_a, group_b)
test_used = "Independent t-test"
else:
# Non-parametric test (Mann-Whitney U)
statistic, p_value = stats.mannwhitneyu(group_a, group_b)
test_used = "Mann-Whitney U test"
# Calculate effect size (Cohen's d)
pooled_std = np.sqrt((group_a.std()**2 + group_b.std()**2) / 2)
cohens_d = (group_a.mean() - group_b.mean()) / pooled_std
print(f"Test used: {test_used}")
print(f"Test statistic: {statistic:.4f}")
print(f"P-value: {p_value:.4f}")
print(f"Effect size (Cohen's d): {cohens_d:.4f}")
Predictive modeling
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
# Prepare data
X = df.drop('target', axis=1)
y = df['target']
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Train model
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Evaluate
y_pred = model.predict(X_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
print(f"RMSE: {rmse:.4f}")
print(f"R² Score: {r2:.4f}")
# Feature importance
importance = pd.DataFrame({
'feature': X.columns,
'importance': model.feature_importances_
}).sort_values('importance', ascending=False)
plt.figure(figsize=(10, 6))
plt.barh(importance['feature'][:10], importance['importance'][:10])
plt.xlabel('Feature Importance')
plt.title('Top 10 Most Important Features')
plt.tight_layout()
plt.savefig('feature_importance.png', dpi=300)
Recommended Python libraries
Data manipulation
- pandas: Data manipulation and analysis
- numpy: Numerical computing
- polars: High-performance DataFrame library (alternative to pandas)
Visualization
- matplotlib: Foundational plotting library
- seaborn: Statistical visualizations
- plotly: Interactive charts
- altair: Declarative statistical visualization
Statistical analysis
- scipy.stats: Statistical functions and tests
- statsmodels: Statistical modeling
- pingouin: Statistical tests with clear output
Machine learning
- scikit-learn: ML algorithms and tools
- xgboost: Gradient boosting
- lightgbm: Fast gradient boosting
Time series
- statsmodels.tsa: Time series analysis
- prophet: Forecasting tool
- pmdarima: Auto ARIMA
Specialized
- networkx: Network analysis
- geopandas: Geospatial data analysis
- textblob / spacy: Natural language processing
Safety and escalation
- Data privacy: Never analyze or share data containing PII without proper authorization.
- Statistical validity: If sample sizes are too small for reliable inference, call this out explicitly.
- Causal claims: Avoid implying causation from correlational analysis; be explicit about limitations.
- Model limitations: Document when models may not generalize or when predictions should not be trusted.
- Data quality: If data quality issues could materially affect conclusions, flag this prominently.
Integration with other skills
This skill can be combined with:
- Internal data querying: To fetch data from warehouses or databases for analysis.
- Web app builder: To create interactive dashboards displaying analysis results.
- Internal tools: To build analysis tools for non-technical stakeholders.
1---2name: ai-data-analyst-23description: Perform comprehensive data analysis, statistical modeling, and data visualization by writing and executing self-contained Python scripts. Use when you need to analyze datasets, perform statistical tests, create visualizations, or build predictive models with reproducible, code-based workflows.4---5# Skill: AI data analyst67## Purpose89Perform comprehensive data analysis, statistical modeling, and data visualization by writing and executing self-contained Python scripts. Generate publication-quality charts, statistical reports, and actionable insights from data files or databases.1011## When to use this skill1213- You need to **analyze datasets** to understand patterns, trends, or relationships.14- You want to perform **statistical tests** or build predictive models.15- You need **data visualizations** (charts, graphs, dashboards) to communicate findings.16- You're doing **exploratory data analysis** (EDA) to understand data structure and quality.17- You need to **clean, transform, or merge** datasets for analysis.18- You want **reproducible analysis** with documented methodology and code.1920## Key capabilities2122Unlike point-solution data analysis tools:2324- **Full Python ecosystem**: Access to pandas, numpy, scikit-learn, statsmodels, matplotlib, seaborn, plotly, and more.25- **Runs locally**: Your data stays on your machine; no uploads to third-party services.26- **Reproducible**: All analysis is code-based and version controllable.27- **Customizable**: Extend with any Python library or custom analysis logic.28- **Publication-quality output**: Generate professional charts and reports.29- **Statistical rigor**: Access to comprehensive statistical and ML libraries.3031## Inputs3233- **Data sources**: CSV files, Excel files, JSON, Parquet, or database connections.34- **Analysis goals**: Questions to answer or hypotheses to test.35- **Variables of interest**: Specific columns, metrics, or dimensions to focus on.36- **Output preferences**: Chart types, report format, statistical tests needed.37- **Context**: Business domain, data dictionary, or known data quality issues.3839## Out of scope4041- Real-time streaming data analysis (use appropriate streaming tools).42- Extremely large datasets requiring distributed computing (use Spark/Dask instead).43- Production ML model deployment (use ML ops tools and infrastructure).44- Live dashboarding (use BI tools like Tableau/Looker for operational dashboards).4546## Conventions and best practices4748### Python environment49- Use **virtual environments** to isolate dependencies.50- Install only necessary packages for the specific analysis.51- Document all dependencies in `requirements.txt` or `environment.yml`.5253### Code structure54- Write **self-contained scripts** that can be re-run by others.55- Use **clear variable names** and add comments for complex logic.56- **Separate concerns**: data loading, cleaning, analysis, visualization.57- Save **intermediate results** to files when analysis is multi-stage.5859### Data handling60- **Never modify source data files** – work on copies or in-memory dataframes.61- **Document data transformations** clearly in code comments.62- **Handle missing values** explicitly and document approach.63- **Validate data quality** before analysis (check for nulls, outliers, duplicates).6465### Visualization best practices66- Choose **appropriate chart types** for the data and question.67- Use **clear labels, titles, and legends** on all charts.68- Apply **appropriate color schemes** (colorblind-friendly when possible).69- Include **sample sizes and confidence intervals** where relevant.70- Save visualizations in **high-resolution formats** (PNG 300 DPI, SVG for vector graphics).7172### Statistical analysis73- **State assumptions** for statistical tests clearly.74- **Check assumptions** before applying tests (normality, homoscedasticity, etc.).75- **Report effect sizes** not just p-values.76- **Use appropriate corrections** for multiple comparisons.77- **Explain practical significance** in addition to statistical significance.7879## Required behavior80811. **Understand the question**: Clarify what insights or decisions the analysis should support.822. **Explore the data**: Check structure, types, missing values, distributions, outliers.833. **Clean and prepare**: Handle missing data, outliers, and transformations appropriately.844. **Analyze systematically**: Apply appropriate statistical methods or ML techniques.855. **Visualize effectively**: Create clear, informative charts that answer the question.866. **Generate insights**: Translate statistical findings into actionable business insights.877. **Document thoroughly**: Explain methodology, assumptions, limitations, and conclusions.888. **Make reproducible**: Ensure others can re-run the analysis and get the same results.8990## Required artifacts9192- **Analysis script(s)**: Well-documented Python code performing the analysis.93- **Visualizations**: Charts saved as high-quality image files (PNG/SVG).94- **Analysis report**: Markdown or text document summarizing:95 - Research question and methodology96 - Data description and quality assessment97 - Key findings with supporting statistics98 - Visualizations with interpretations99 - Limitations and caveats100 - Recommendations or next steps101- **Requirements file**: `requirements.txt` with all dependencies.102- **Sample data** (if appropriate and non-sensitive): Small sample for reproducibility.103104## Implementation checklist105106### 1. Data exploration and preparation107- [ ] Load data and inspect structure (shape, columns, types)108- [ ] Check for missing values, duplicates, outliers109- [ ] Generate summary statistics (mean, median, std, min, max)110- [ ] Visualize distributions of key variables111- [ ] Document data quality issues found112113### 2. Data cleaning and transformation114- [ ] Handle missing values (impute, drop, or flag)115- [ ] Address outliers if needed (cap, transform, or document)116- [ ] Create derived variables if needed117- [ ] Normalize or scale variables for modeling118- [ ] Split data if doing train/test analysis119120### 3. Analysis execution121- [ ] Choose appropriate analytical methods122- [ ] Check statistical assumptions123- [ ] Execute analysis with proper parameters124- [ ] Calculate confidence intervals and effect sizes125- [ ] Perform sensitivity analyses if appropriate126127### 4. Visualization128- [ ] Create exploratory visualizations129- [ ] Generate publication-quality final charts130- [ ] Ensure all charts have clear labels and titles131- [ ] Use appropriate color schemes and styling132- [ ] Save in high-resolution formats133134### 5. Reporting135- [ ] Write clear summary of methods used136- [ ] Present key findings with supporting evidence137- [ ] Explain practical significance of results138- [ ] Document limitations and assumptions139- [ ] Provide actionable recommendations140141### 6. Reproducibility142- [ ] Test that script runs from clean environment143- [ ] Document all dependencies144- [ ] Add comments explaining non-obvious code145- [ ] Include instructions for running analysis146147## Verification148149Run the following to verify the analysis:150151```bash152# Create virtual environment153python3 -m venv venv154source venv/bin/activate # or `venv\Scripts\activate` on Windows155156# Install dependencies157pip install -r requirements.txt158159# Run analysis script160python analysis.py161162# Check outputs generated163ls -lh outputs/164```165166The skill is complete when:167168- Analysis script runs without errors from clean environment.169- All required visualizations are generated in high quality.170- Report clearly explains methodology, findings, and limitations.171- Results are interpretable and actionable.172- Code is well-documented and reproducible.173174## Common analysis patterns175176### Exploratory Data Analysis (EDA)177```python178import pandas as pd179import matplotlib.pyplot as plt180import seaborn as sns181182# Load and inspect data183df = pd.read_csv('data.csv')184print(df.info())185print(df.describe())186187# Check for missing values188print(df.isnull().sum())189190# Visualize distributions191df.hist(figsize=(12, 10), bins=30)192plt.tight_layout()193plt.savefig('distributions.png', dpi=300)194195# Check correlations196corr = df.corr()197sns.heatmap(corr, annot=True, cmap='coolwarm')198plt.savefig('correlations.png', dpi=300)199```200201### Time series analysis202```python203import pandas as pd204import matplotlib.pyplot as plt205from statsmodels.tsa.seasonal import seasonal_decompose206207# Load time series data208df = pd.read_csv('timeseries.csv', parse_dates=['date'])209df.set_index('date', inplace=True)210211# Decompose time series212decomposition = seasonal_decompose(df['value'], model='additive', period=30)213fig = decomposition.plot()214fig.set_size_inches(12, 8)215plt.savefig('decomposition.png', dpi=300)216217# Calculate rolling statistics218df['rolling_mean'] = df['value'].rolling(window=7).mean()219df['rolling_std'] = df['value'].rolling(window=7).std()220221# Plot with trends222plt.figure(figsize=(12, 6))223plt.plot(df['value'], label='Original')224plt.plot(df['rolling_mean'], label='7-day Moving Avg', linewidth=2)225plt.fill_between(df.index,226 df['rolling_mean'] - df['rolling_std'],227 df['rolling_mean'] + df['rolling_std'],228 alpha=0.3)229plt.legend()230plt.savefig('trends.png', dpi=300)231```232233### Statistical hypothesis testing234```python235from scipy import stats236import numpy as np237238# Compare two groups239group_a = df[df['group'] == 'A']['metric']240group_b = df[df['group'] == 'B']['metric']241242# Check normality243_, p_norm_a = stats.shapiro(group_a)244_, p_norm_b = stats.shapiro(group_b)245246# Choose appropriate test247if p_norm_a > 0.05 and p_norm_b > 0.05:248 # Parametric test (t-test)249 statistic, p_value = stats.ttest_ind(group_a, group_b)250 test_used = "Independent t-test"251else:252 # Non-parametric test (Mann-Whitney U)253 statistic, p_value = stats.mannwhitneyu(group_a, group_b)254 test_used = "Mann-Whitney U test"255256# Calculate effect size (Cohen's d)257pooled_std = np.sqrt((group_a.std()**2 + group_b.std()**2) / 2)258cohens_d = (group_a.mean() - group_b.mean()) / pooled_std259260print(f"Test used: {test_used}")261print(f"Test statistic: {statistic:.4f}")262print(f"P-value: {p_value:.4f}")263print(f"Effect size (Cohen's d): {cohens_d:.4f}")264```265266### Predictive modeling267```python268from sklearn.model_selection import train_test_split269from sklearn.ensemble import RandomForestRegressor270from sklearn.metrics import mean_squared_error, r2_score271import matplotlib.pyplot as plt272273# Prepare data274X = df.drop('target', axis=1)275y = df['target']276277# Split data278X_train, X_test, y_train, y_test = train_test_split(279 X, y, test_size=0.2, random_state=42280)281282# Train model283model = RandomForestRegressor(n_estimators=100, random_state=42)284model.fit(X_train, y_train)285286# Evaluate287y_pred = model.predict(X_test)288rmse = np.sqrt(mean_squared_error(y_test, y_pred))289r2 = r2_score(y_test, y_pred)290291print(f"RMSE: {rmse:.4f}")292print(f"R² Score: {r2:.4f}")293294# Feature importance295importance = pd.DataFrame({296 'feature': X.columns,297 'importance': model.feature_importances_298}).sort_values('importance', ascending=False)299300plt.figure(figsize=(10, 6))301plt.barh(importance['feature'][:10], importance['importance'][:10])302plt.xlabel('Feature Importance')303plt.title('Top 10 Most Important Features')304plt.tight_layout()305plt.savefig('feature_importance.png', dpi=300)306```307308## Recommended Python libraries309310### Data manipulation311- **pandas**: Data manipulation and analysis312- **numpy**: Numerical computing313- **polars**: High-performance DataFrame library (alternative to pandas)314315### Visualization316- **matplotlib**: Foundational plotting library317- **seaborn**: Statistical visualizations318- **plotly**: Interactive charts319- **altair**: Declarative statistical visualization320321### Statistical analysis322- **scipy.stats**: Statistical functions and tests323- **statsmodels**: Statistical modeling324- **pingouin**: Statistical tests with clear output325326### Machine learning327- **scikit-learn**: ML algorithms and tools328- **xgboost**: Gradient boosting329- **lightgbm**: Fast gradient boosting330331### Time series332- **statsmodels.tsa**: Time series analysis333- **prophet**: Forecasting tool334- **pmdarima**: Auto ARIMA335336### Specialized337- **networkx**: Network analysis338- **geopandas**: Geospatial data analysis339- **textblob** / **spacy**: Natural language processing340341## Safety and escalation342343- **Data privacy**: Never analyze or share data containing PII without proper authorization.344- **Statistical validity**: If sample sizes are too small for reliable inference, call this out explicitly.345- **Causal claims**: Avoid implying causation from correlational analysis; be explicit about limitations.346- **Model limitations**: Document when models may not generalize or when predictions should not be trusted.347- **Data quality**: If data quality issues could materially affect conclusions, flag this prominently.348349## Integration with other skills350351This skill can be combined with:352353- **Internal data querying**: To fetch data from warehouses or databases for analysis.354- **Web app builder**: To create interactive dashboards displaying analysis results.355- **Internal tools**: To build analysis tools for non-technical stakeholders.