Data Analysis Agent Skill
Overview
A production-grade agent skill for end-to-end data analysis workflows. Use this
skill when you need to load datasets, inspect structure, clean messy data,
perform statistical analyses, create visualizations, or generate structured
reports from tabular data.
When to Trigger
Activate this skill when the user asks to:
- Analyze data: "Analyze this CSV", "What patterns do you see in sales.csv?",
"Explore this dataset", "Summarize the data in users.json"
- Create charts/graphs: "Make a bar chart of…", "Plot revenue over time",
"Visualize the correlation matrix", "Show me a heatmap of…"
- Find patterns: "Find trends in this data", "Is there a correlation between
X and Y?", "Cluster customers from this data", "Detect anomalies in…"
- Generate reports: "Create a report from survey_results.xlsx",
"Summarize quarterly metrics", "Build a dashboard from sales data"
- Clean data: "Clean this messy dataset", "Fix missing values in…",
"Normalize these columns", "Deduplicate this CSV"
- Statistical testing: "Run a t-test on group A vs B", "Check if this
distribution is normal", "Perform regression analysis", "Calculate
confidence intervals"
Near-Miss Negatives — Do NOT Trigger
- Questions about database schema design without actual data (e.g.,
"What columns should my users table have?")
- Questions about spreadsheet software UI (e.g., "How do I freeze a row in
Google Sheets?")
- General math / statistics theory questions without a dataset context
(e.g., "Explain the central limit theorem")
- Pure SQL query writing without a data-analysis intent (e.g., "Write a
query to join three tables" — use a SQL skill instead)
- Questions about ETL pipeline architecture or data engineering (e.g.,
"Design a data ingestion pipeline")
Step-by-Step Workflow
Follow these phases in order. Skip phases that don't apply (e.g., if data is
already clean) but always state that you're skipping and why.
Phase 1: Load
Determine the data source and load it into a DataFrame.
CSV → pd.read_csv(filepath, ...)
JSON → pd.read_json(filepath, ...)
Excel → pd.read_excel(filepath, sheet_name=...)
SQL → pd.read_sql_query(query, connection)
Checklist:
Phase 2: Inspect
Understand what you're working with before touching anything.
df.shape # rows × columns
df.info() # dtypes, non-null counts, memory
df.head(10) # first rows
df.tail(5) # last rows
df.describe() # numeric summary stats
df.describe(include='object') # categorical summary
df.dtypes # column types
df.columns.tolist() # column names
Checklist:
Phase 3: Clean
Address data quality issues. Never modify the source file without prompting
the user first. Work on a copy.
Common operations:
| Issue |
Approach |
| Missing values |
df.isnull().sum() → decide drop vs impute |
| Wrong dtypes |
pd.to_numeric(), pd.to_datetime(), astype() |
| Outliers |
IQR method, Z-score, domain-specific thresholds |
| Duplicates |
df.duplicated().sum() → df.drop_duplicates() |
| Inconsistent strings |
.str.strip(), .str.lower(), .str.replace() |
| Date parsing |
pd.to_datetime() with format or infer |
| Normalization |
Min-max scaling, Z-score standardization |
| Categorical encoding |
One-hot, label encoding for ML prep |
Rules:
- Always work on
df_clean = df.copy(), never mutate the original in-place
without explicit user consent.
- Report every change: "Dropped 47 duplicate rows (2.3% of data)", "Imputed
missing age values with median (142 cells)".
- Flag suspicious patterns even if you don't fix them: "Column 'salary' has
340 zero values — verify if these are legitimate."
- If a cleaning decision is irreversible, ask first.
Phase 4: Analyze
Apply appropriate analytical methods based on the question.
Exploratory Data Analysis (EDA):
- Univariate: histograms, box plots, value counts per column
- Bivariate: scatter plots, correlation coefficients, grouped means
- Multivariate: pair plots, correlation matrix heatmap, PCA
Statistical Methods (see references/statistical-methods.md):
| Goal |
Method |
| Compare two groups |
Independent t-test, Mann-Whitney U |
| Compare 3+ groups |
One-way ANOVA, Kruskal-Wallis |
| Relationship between two continuous vars |
Pearson/Spearman correlation |
| Predict continuous outcome |
Linear regression, polynomial regression |
| Predict categorical outcome |
Logistic regression |
| Check normality |
Shapiro-Wilk test, Q-Q plot |
| Detect time trends |
Moving averages, decomposition, stationarity tests |
| Find clusters |
K-means, hierarchical clustering, DBSCAN |
| Reduce dimensions |
PCA, t-SNE (visualization only) |
Time Series specifics:
- Set datetime index:
df.set_index('date', inplace=True)
- Resample:
df.resample('M').mean()
- Rolling windows:
df['value'].rolling(7).mean()
- Decomposition: trend, seasonal, residual
Phase 5: Visualize
Choose the right chart for the data and question. See
references/visualization-patterns.md for the full guide.
Library selection:
- Static, publication-quality:
matplotlib + seaborn
- Interactive, exploratory:
plotly
- Statistical plots:
seaborn (box, violin, pair, joint, heatmap)
Quick reference:
| Data Type |
Question |
Chart |
| Categorical × Numeric |
Compare amounts |
Bar chart, box plot |
| Numeric × Numeric |
Relationship |
Scatter plot, line chart |
| Time × Numeric |
Trend over time |
Line chart, area chart |
| Categorical × Categorical |
Cross-tabulation |
Heatmap, stacked bar |
| Distribution |
Shape of data |
Histogram, KDE, violin |
| Part-to-whole |
Proportions |
Pie chart* (≤5 categories), treemap |
| Correlation matrix |
Relationships |
Heatmap |
| Rankings |
Order |
Horizontal bar chart |
*Pie charts: use only when ≤5 categories and values sum to a meaningful whole.
Prefer bar charts otherwise.
Best practices:
- Always label axes and add a title
- Use accessible color palettes (avoid red-green for colorblind users)
- Sort bar charts by value unless categories have a natural order
- Add data source and date to chart footnotes
- For interactive charts, include hover tooltips
Phase 6: Report
Synthesize findings into a structured report.
Report structure:
- Executive Summary — 2–3 sentences with the key finding
- Data Overview — source, shape, date range, columns
- Data Quality — issues found, actions taken
- Key Findings — bullet points with numbers, ranked by importance
- Visualizations — inline charts with captions
- Statistical Results — test statistics, p-values, effect sizes
- Limitations & Caveats — data gaps, assumptions, edge cases
- Recommendations — actionable next steps or further analysis
Output formats:
- Quick answer: plain text summary in chat with key numbers
- Detailed report: Markdown document with embedded charts
- Dashboard: interactive HTML with plotly (offer if >5 charts)
- Export: offer to save cleaned data and charts as files
Tool-Aware Implementation
Python Libraries
This skill assumes Python 3.9+ with the following libraries available.
Check availability before use; install missing packages as needed.
# Core
import pandas as pd
import numpy as np
# Visualization
import matplotlib.pyplot as plt
import seaborn as sns
# Interactive
import plotly.express as px
import plotly.graph_objects as go
# Statistics
from scipy import stats
from scipy.stats import norm, ttest_ind, f_oneway, pearsonr, spearmanr
# Optional: machine learning
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.linear_model import LinearRegression, LogisticRegression
Matplotlib setup for non-interactive environments:
import matplotlib
matplotlib.use('Agg') # headless rendering
Plotly in notebooks vs scripts:
# In Jupyter/notebook environments:
import plotly.io as pio
pio.renderers.default = 'notebook'
# For saving to files:
fig.write_html('chart.html')
fig.write_image('chart.png')
Platform-Specific Notes
| Platform |
Matplotlib backend |
File output |
Notes |
| Claude Code |
Agg |
write to files |
Save charts as PNG/HTML, display from disk |
| Codex |
Agg |
write to files |
Same approach |
| Cursor |
Agg or interactive |
write to files |
Can open HTML in preview |
| Gemini CLI |
Agg |
write to files |
Save charts, display paths |
| OpenClaw |
Agg |
write to files |
Use canvas for HTML output |
| Copilot |
Agg |
write to files |
Standard file-based approach |
Safety & Guardrails
- Never modify source data in-place — always create a copy or backup before
transformations. Offer to save cleaned data as a new file.
- Flag data quality issues — don't silently fix problems. Report missing
values, outliers, and type inconsistencies before and after cleaning.
- Statistical honesty — report p-values and effect sizes, not just
"significant" or "not significant". Don't p-hack by running multiple tests
without correction. Mention when sample sizes are too small for reliable
inference.
- Privacy awareness — if a dataset appears to contain PII (emails, phone
numbers, names), warn the user and suggest anonymization before analysis.
- Large file handling — for files >100MB, use chunked reading
(
chunksize parameter) or sample before full analysis. Warn about memory
constraints.
- SQL safety — use read-only connections. Never run INSERT, UPDATE,
DELETE, DROP, or ALTER. Use transactions or connection strings that enforce
read-only mode.
- Deterministic results — set random seeds for reproducible analysis:
np.random.seed(42).
Scripts
scripts/validate_dataset.py
PEP 723 compliant data quality validation script. Run with:
python scripts/validate_dataset.py path/to/dataset.csv
# or
python scripts/validate_dataset.py path/to/dataset.json
# or
python scripts/validate_dataset.py path/to/dataset.xlsx --sheet "Sheet1"
Produces a structured quality report covering missing values, outliers, type
consistency, duplicates, and basic statistics. See script docstring for details.
References
- data-cleaning-guide.md — Handling
nulls, outliers, type coercion, deduplication, and normalization patterns.
- visualization-patterns.md — Chart
type selection guide, color best practices, accessibility considerations.
- statistical-methods.md — Descriptive
statistics, hypothesis testing, regression, correlation, confidence intervals,
and when to use each method.
1---2name: data-analysis3description: Comprehensive data analysis agent skill for loading, cleaning, exploring, visualizing, and reporting on structured datasets. Supports CSV, JSON, Excel, and SQL data sources. Produces statistical summaries, correlation matrices, time series analysis, regression models, hypothesis tests, and publication-quality visualizations.4---56# Data Analysis Agent Skill78## Overview910A production-grade agent skill for end-to-end data analysis workflows. Use this11skill when you need to load datasets, inspect structure, clean messy data,12perform statistical analyses, create visualizations, or generate structured13reports from tabular data.1415## When to Trigger1617Activate this skill when the user asks to:1819- **Analyze data**: "Analyze this CSV", "What patterns do you see in sales.csv?",20 "Explore this dataset", "Summarize the data in users.json"21- **Create charts/graphs**: "Make a bar chart of…", "Plot revenue over time",22 "Visualize the correlation matrix", "Show me a heatmap of…"23- **Find patterns**: "Find trends in this data", "Is there a correlation between24 X and Y?", "Cluster customers from this data", "Detect anomalies in…"25- **Generate reports**: "Create a report from survey_results.xlsx",26 "Summarize quarterly metrics", "Build a dashboard from sales data"27- **Clean data**: "Clean this messy dataset", "Fix missing values in…",28 "Normalize these columns", "Deduplicate this CSV"29- **Statistical testing**: "Run a t-test on group A vs B", "Check if this30 distribution is normal", "Perform regression analysis", "Calculate31 confidence intervals"3233### Near-Miss Negatives — Do NOT Trigger3435- Questions about **database schema design** without actual data (e.g.,36 "What columns should my users table have?")37- Questions about **spreadsheet software UI** (e.g., "How do I freeze a row in38 Google Sheets?")39- General **math / statistics theory** questions without a dataset context40 (e.g., "Explain the central limit theorem")41- Pure **SQL query writing** without a data-analysis intent (e.g., "Write a42 query to join three tables" — use a SQL skill instead)43- Questions about **ETL pipeline architecture** or data engineering (e.g.,44 "Design a data ingestion pipeline")4546## Step-by-Step Workflow4748Follow these phases in order. Skip phases that don't apply (e.g., if data is49already clean) but always **state that you're skipping** and why.5051### Phase 1: Load5253Determine the data source and load it into a DataFrame.5455```56CSV → pd.read_csv(filepath, ...)57JSON → pd.read_json(filepath, ...)58Excel → pd.read_excel(filepath, sheet_name=...)59SQL → pd.read_sql_query(query, connection)60```6162**Checklist:**63- [ ] Identify encoding (try UTF-8, Latin-1, detect automatically)64- [ ] For CSV: inspect delimiter (comma, tab, semicolon), quote character65- [ ] For Excel: list available sheets, load the right one66- [ ] For JSON: handle nested structures with `pd.json_normalize()` if needed67- [ ] For SQL: confirm read-only access, never run destructive queries68- [ ] Load a sample first if the dataset is large (>100k rows)6970### Phase 2: Inspect7172Understand what you're working with before touching anything.7374```python75df.shape # rows × columns76df.info() # dtypes, non-null counts, memory77df.head(10) # first rows78df.tail(5) # last rows79df.describe() # numeric summary stats80df.describe(include='object') # categorical summary81df.dtypes # column types82df.columns.tolist() # column names83```8485**Checklist:**86- [ ] Report shape: rows × columns87- [ ] List all columns with their dtypes88- [ ] Show summary statistics for numeric columns89- [ ] Show value counts for low-cardinality categorical columns90- [ ] Flag potential issues: wrong dtypes, placeholder values, suspicious zeros9192### Phase 3: Clean9394Address data quality issues. **Never modify the source file** without prompting95the user first. Work on a copy.9697**Common operations:**9899| Issue | Approach |100|-------|----------|101| Missing values | `df.isnull().sum()` → decide drop vs impute |102| Wrong dtypes | `pd.to_numeric()`, `pd.to_datetime()`, `astype()` |103| Outliers | IQR method, Z-score, domain-specific thresholds |104| Duplicates | `df.duplicated().sum()` → `df.drop_duplicates()` |105| Inconsistent strings | `.str.strip()`, `.str.lower()`, `.str.replace()` |106| Date parsing | `pd.to_datetime()` with format or infer |107| Normalization | Min-max scaling, Z-score standardization |108| Categorical encoding | One-hot, label encoding for ML prep |109110**Rules:**1111. Always work on `df_clean = df.copy()`, never mutate the original in-place112 without explicit user consent.1132. Report every change: "Dropped 47 duplicate rows (2.3% of data)", "Imputed114 missing age values with median (142 cells)".1153. Flag suspicious patterns even if you don't fix them: "Column 'salary' has116 340 zero values — verify if these are legitimate."1174. If a cleaning decision is irreversible, ask first.118119### Phase 4: Analyze120121Apply appropriate analytical methods based on the question.122123**Exploratory Data Analysis (EDA):**124- Univariate: histograms, box plots, value counts per column125- Bivariate: scatter plots, correlation coefficients, grouped means126- Multivariate: pair plots, correlation matrix heatmap, PCA127128**Statistical Methods (see `references/statistical-methods.md`):**129130| Goal | Method |131|------|--------|132| Compare two groups | Independent t-test, Mann-Whitney U |133| Compare 3+ groups | One-way ANOVA, Kruskal-Wallis |134| Relationship between two continuous vars | Pearson/Spearman correlation |135| Predict continuous outcome | Linear regression, polynomial regression |136| Predict categorical outcome | Logistic regression |137| Check normality | Shapiro-Wilk test, Q-Q plot |138| Detect time trends | Moving averages, decomposition, stationarity tests |139| Find clusters | K-means, hierarchical clustering, DBSCAN |140| Reduce dimensions | PCA, t-SNE (visualization only) |141142**Time Series specifics:**143- Set datetime index: `df.set_index('date', inplace=True)`144- Resample: `df.resample('M').mean()`145- Rolling windows: `df['value'].rolling(7).mean()`146- Decomposition: trend, seasonal, residual147148### Phase 5: Visualize149150Choose the right chart for the data and question. See151`references/visualization-patterns.md` for the full guide.152153**Library selection:**154- **Static, publication-quality**: `matplotlib` + `seaborn`155- **Interactive, exploratory**: `plotly`156- **Statistical plots**: `seaborn` (box, violin, pair, joint, heatmap)157158**Quick reference:**159160| Data Type | Question | Chart |161|-----------|----------|-------|162| Categorical × Numeric | Compare amounts | Bar chart, box plot |163| Numeric × Numeric | Relationship | Scatter plot, line chart |164| Time × Numeric | Trend over time | Line chart, area chart |165| Categorical × Categorical | Cross-tabulation | Heatmap, stacked bar |166| Distribution | Shape of data | Histogram, KDE, violin |167| Part-to-whole | Proportions | Pie chart* (≤5 categories), treemap |168| Correlation matrix | Relationships | Heatmap |169| Rankings | Order | Horizontal bar chart |170171*Pie charts: use only when ≤5 categories and values sum to a meaningful whole.172Prefer bar charts otherwise.173174**Best practices:**175- Always label axes and add a title176- Use accessible color palettes (avoid red-green for colorblind users)177- Sort bar charts by value unless categories have a natural order178- Add data source and date to chart footnotes179- For interactive charts, include hover tooltips180181### Phase 6: Report182183Synthesize findings into a structured report.184185**Report structure:**1861. **Executive Summary** — 2–3 sentences with the key finding1872. **Data Overview** — source, shape, date range, columns1883. **Data Quality** — issues found, actions taken1894. **Key Findings** — bullet points with numbers, ranked by importance1905. **Visualizations** — inline charts with captions1916. **Statistical Results** — test statistics, p-values, effect sizes1927. **Limitations & Caveats** — data gaps, assumptions, edge cases1938. **Recommendations** — actionable next steps or further analysis194195**Output formats:**196- **Quick answer**: plain text summary in chat with key numbers197- **Detailed report**: Markdown document with embedded charts198- **Dashboard**: interactive HTML with plotly (offer if >5 charts)199- **Export**: offer to save cleaned data and charts as files200201## Tool-Aware Implementation202203### Python Libraries204205This skill assumes Python 3.9+ with the following libraries available.206Check availability before use; install missing packages as needed.207208```python209# Core210import pandas as pd211import numpy as np212213# Visualization214import matplotlib.pyplot as plt215import seaborn as sns216217# Interactive218import plotly.express as px219import plotly.graph_objects as go220221# Statistics222from scipy import stats223from scipy.stats import norm, ttest_ind, f_oneway, pearsonr, spearmanr224225# Optional: machine learning226from sklearn.preprocessing import StandardScaler, LabelEncoder227from sklearn.cluster import KMeans228from sklearn.decomposition import PCA229from sklearn.linear_model import LinearRegression, LogisticRegression230```231232**Matplotlib setup for non-interactive environments:**233```python234import matplotlib235matplotlib.use('Agg') # headless rendering236```237238**Plotly in notebooks vs scripts:**239```python240# In Jupyter/notebook environments:241import plotly.io as pio242pio.renderers.default = 'notebook'243244# For saving to files:245fig.write_html('chart.html')246fig.write_image('chart.png')247```248249### Platform-Specific Notes250251| Platform | Matplotlib backend | File output | Notes |252|----------|-------------------|-------------|-------|253| Claude Code | Agg | write to files | Save charts as PNG/HTML, display from disk |254| Codex | Agg | write to files | Same approach |255| Cursor | Agg or interactive | write to files | Can open HTML in preview |256| Gemini CLI | Agg | write to files | Save charts, display paths |257| OpenClaw | Agg | write to files | Use canvas for HTML output |258| Copilot | Agg | write to files | Standard file-based approach |259260## Safety & Guardrails2612621. **Never modify source data in-place** — always create a copy or backup before263 transformations. Offer to save cleaned data as a new file.2642. **Flag data quality issues** — don't silently fix problems. Report missing265 values, outliers, and type inconsistencies before and after cleaning.2663. **Statistical honesty** — report p-values and effect sizes, not just267 "significant" or "not significant". Don't p-hack by running multiple tests268 without correction. Mention when sample sizes are too small for reliable269 inference.2704. **Privacy awareness** — if a dataset appears to contain PII (emails, phone271 numbers, names), warn the user and suggest anonymization before analysis.2725. **Large file handling** — for files >100MB, use chunked reading273 (`chunksize` parameter) or sample before full analysis. Warn about memory274 constraints.2756. **SQL safety** — use read-only connections. Never run INSERT, UPDATE,276 DELETE, DROP, or ALTER. Use transactions or connection strings that enforce277 read-only mode.2787. **Deterministic results** — set random seeds for reproducible analysis:279 `np.random.seed(42)`.280281## Scripts282283### `scripts/validate_dataset.py`284285PEP 723 compliant data quality validation script. Run with:286287```bash288python scripts/validate_dataset.py path/to/dataset.csv289# or290python scripts/validate_dataset.py path/to/dataset.json291# or292python scripts/validate_dataset.py path/to/dataset.xlsx --sheet "Sheet1"293```294295Produces a structured quality report covering missing values, outliers, type296consistency, duplicates, and basic statistics. See script docstring for details.297298## References299300- **[data-cleaning-guide.md](references/data-cleaning-guide.md)** — Handling301 nulls, outliers, type coercion, deduplication, and normalization patterns.302- **[visualization-patterns.md](references/visualization-patterns.md)** — Chart303 type selection guide, color best practices, accessibility considerations.304- **[statistical-methods.md](references/statistical-methods.md)** — Descriptive305 statistics, hypothesis testing, regression, correlation, confidence intervals,306 and when to use each method.