[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76XNFNVP22PE37WQYH7FTDB":3,"skill-same:01M76XNFNVP22PE37WQYH7FTDB":50},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":27,"commitSha":28,"skillDirectory":29,"forksCount":30,"repositoryHtmlUrl":31,"repositoryHomepageUrl":32,"ownerHtmlUrl":33,"ownerBlogUrl":6,"ownerDescription":34,"updatedAt":35,"install":36,"resources":49},"01M76XNFNVP22PE37WQYH7FTDB","Spreadsheet & Data Wrangling Master",null,"Complete spreadsheet methodology — data cleanup, transformation, analysis, dashboards, automation, and reporting. Works with CSV, Excel, Google Sheets, or any tabular data. Use when the user needs to clean messy data, build reports, create dashboards, automate recurring spreadsheet tasks, or transform data between formats.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fa\u002Fafrexai-spreadsheet-master\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: Spreadsheet & Data Wrangling Master\nslug: afrexai-spreadsheet-master\nversion: 1.0.0\ndescription: \"Complete spreadsheet methodology — data cleanup, transformation, analysis, dashboards, automation, and reporting. Works with CSV, Excel, Google Sheets, or any tabular data. Use when the user needs to clean messy data, build reports, create dashboards, automate recurring spreadsheet tasks, or transform data between formats.\"\ntags: spreadsheet, excel, csv, data, cleanup, reporting, dashboard, analytics, automation, google-sheets\n---\n\n# Spreadsheet & Data Wrangling Master\n\n> Turn messy data into clean insights, automated reports, and decision-ready dashboards. Platform-agnostic — works with CSV, Excel, Google Sheets, or any tabular format.\n\n---\n\n## Phase 1: Data Intake & Assessment\n\nBefore touching any data, assess what you have.\n\n### Quick Health Check (score \u002F20)\n\n```yaml\ndata_intake:\n  source: \"\"           # file path, URL, API, database, manual entry\n  format: \"\"           # CSV, XLSX, TSV, JSON, clipboard paste\n  rows: 0\n  columns: 0\n  file_size: \"\"\n  encoding: \"\"         # UTF-8, Latin-1, Windows-1252, etc.\n  delimiter: \"\"        # comma, tab, pipe, semicolon\n\n  health_score:        # rate each 0-4, total \u002F20\n    completeness: 0    # 4=\u003C1% missing, 3=\u003C5%, 2=\u003C15%, 1=\u003C30%, 0=>30%\n    consistency: 0     # 4=uniform types, 3=minor mixed, 2=significant mixed, 1=chaotic, 0=unusable\n    accuracy: 0        # 4=verified, 3=plausible, 2=some outliers, 1=many errors, 0=untrustworthy\n    freshness: 0       # 4=real-time, 3=\u003C24h, 2=\u003C7d, 1=\u003C30d, 0=stale\u002Funknown\n    structure: 0       # 4=tidy (1 row=1 obs), 3=minor reshaping, 2=pivot needed, 1=multi-header, 0=freeform\n\n  issues_found: []     # list every problem before fixing anything\n```\n\n### First 10 Questions to Ask\n\n1. How many rows and columns?\n2. What does each row represent? (one customer? one transaction? one day?)\n3. Are there header rows? Multiple header rows? Merged cells?\n4. What are the data types? (dates, currencies, percentages, IDs, free text)\n5. How much is missing? Which columns?\n6. Are there duplicates? By which key?\n7. Is there a unique identifier column?\n8. What date format? (MM\u002FDD\u002FYYYY vs DD\u002FMM\u002FYYYY vs YYYY-MM-DD vs mixed)\n9. What currency\u002Fnumber format? (1,000.00 vs 1.000,00 vs 1000)\n10. Where did this data come from and how often is it updated?\n\n---\n\n## Phase 2: Data Cleaning Decision Tree\n\n### Step-by-Step Cleaning Protocol\n\n```\nSTART\n  │\n  ├─ Headers → Normalize (lowercase, snake_case, no spaces\u002Fspecial chars)\n  │\n  ├─ Duplicates?\n  │   ├─ Exact duplicates → Remove, keep first\n  │   ├─ Near-duplicates → Flag for review (fuzzy match on name + address)\n  │   └─ Intentional duplicates → Leave (e.g., multiple orders same customer)\n  │\n  ├─ Missing Values?\n  │   ├─ \u003C5% of column → Fill (mean for numeric, mode for categorical, forward-fill for time series)\n  │   ├─ 5-30% → Flag + fill with \"UNKNOWN\" or interpolate with justification\n  │   ├─ >30% → Consider dropping column or flagging as unreliable\n  │   └─ Entire row missing key fields → Remove with log\n  │\n  ├─ Data Types?\n  │   ├─ Dates as text → Parse to date (try multiple formats, log failures)\n  │   ├─ Numbers as text → Strip currency symbols, commas, whitespace, convert\n  │   ├─ IDs\u002Fzips with leading zeros → Keep as text (NEVER convert to number)\n  │   ├─ Phone numbers → Text, standardize format\n  │   ├─ Mixed types in column → Split or coerce with error log\n  │   └─ Boolean variants → Map (Yes\u002FNo\u002FTrue\u002FFalse\u002F1\u002F0\u002FY\u002FN → consistent)\n  │\n  ├─ Outliers?\n  │   ├─ Calculate IQR: Q1 - 1.5×IQR to Q3 + 1.5×IQR\n  │   ├─ Business logic check (negative revenue? age 200? date in 2099?)\n  │   ├─ Decide: fix (typo), cap (winsorize), remove, or keep with flag\n  │   └─ ALWAYS log which outliers were modified and why\n  │\n  ├─ Standardization?\n  │   ├─ Text case → Consistent (Title Case for names, UPPER for codes)\n  │   ├─ Whitespace → Trim leading\u002Ftrailing, collapse internal\n  │   ├─ Categories → Map variants (\"US\"\u002F\"USA\"\u002F\"United States\" → \"US\")\n  │   ├─ Dates → ISO 8601 (YYYY-MM-DD) internally\n  │   ├─ Currency → Consistent symbol placement, decimal precision\n  │   └─ Phone\u002Femail → Validate format\n  │\n  └─ Structural Issues?\n      ├─ Multi-header rows → Flatten to single header\n      ├─ Merged cells → Unmerge + fill down\n      ├─ Pivot\u002Fcrosstab → Unpivot to tidy format (1 row = 1 observation)\n      ├─ Multiple tables in one sheet → Split to separate sheets\u002Ffiles\n      └─ Metadata rows (totals, notes) → Separate from data rows\n```\n\n### Cleaning Log Template\n\n```yaml\ncleaning_log:\n  date: \"YYYY-MM-DD\"\n  source_file: \"\"\n  rows_before: 0\n  rows_after: 0\n  actions:\n    - action: \"removed exact duplicates\"\n      rows_affected: 0\n      key_columns: [\"email\"]\n    - action: \"filled missing values\"\n      column: \"state\"\n      method: \"mode\"\n      values_filled: 0\n    - action: \"removed outliers\"\n      column: \"revenue\"\n      criteria: \"negative values\"\n      rows_removed: 0\n    - action: \"standardized dates\"\n      column: \"order_date\"\n      from_format: \"MM\u002FDD\u002FYYYY\"\n      to_format: \"YYYY-MM-DD\"\n      parse_failures: 0\n  notes: \"\"\n```\n\n---\n\n## Phase 3: Transformation Patterns\n\n### 12 Essential Transform Operations\n\n| # | Operation | When to Use | Example |\n|---|-----------|-------------|---------|\n| 1 | **Filter** | Subset rows by condition | Orders > $1000, Date after 2024-01-01 |\n| 2 | **Sort** | Order by column(s) | Revenue descending, then date ascending |\n| 3 | **Group + Aggregate** | Summarize by category | Total revenue by region, avg order by customer |\n| 4 | **Pivot** | Rows → columns | Monthly columns from date rows |\n| 5 | **Unpivot\u002FMelt** | Columns → rows | Month columns back to date rows |\n| 6 | **Join\u002FMerge** | Combine datasets | Customer data + order data on customer_id |\n| 7 | **Deduplicate** | Remove redundancy | Keep latest record per customer |\n| 8 | **Derive** | Calculate new columns | profit = revenue - cost, age = today - birthdate |\n| 9 | **Split** | One column → many | \"John Smith\" → first_name, last_name |\n| 10 | **Concatenate** | Many columns → one | city + state + zip → full_address |\n| 11 | **Lookup\u002FMap** | Enrich with reference data | state_code → state_name, product_id → category |\n| 12 | **Window** | Running calculations | 7-day moving average, rank within group, running total |\n\n### Join Strategy Decision Guide\n\n```\nWhich join do you need?\n│\n├─ Need ALL rows from left table → LEFT JOIN\n│   (customers who may or may not have orders)\n│\n├─ Need ONLY matching rows → INNER JOIN\n│   (only customers WITH orders)\n│\n├─ Need ALL rows from both → FULL OUTER JOIN\n│   (reconciliation: find mismatches)\n│\n├─ Need everything NOT in other table → LEFT JOIN + WHERE right IS NULL\n│   (customers who NEVER ordered)\n│\n└─ Need every combination → CROSS JOIN (rare, use carefully)\n    (all products × all stores for pricing matrix)\n\n⚠️ ALWAYS check join results:\n- Row count: did it explode? (many-to-many join)\n- Row count: did it shrink? (keys not matching)\n- NULL columns: expected from outer join, unexpected = key mismatch\n```\n\n### Formula Reference (Cross-Platform)\n\n| Task | Excel | Google Sheets | Python (pandas) |\n|------|-------|---------------|-----------------|\n| Lookup | `VLOOKUP`, `XLOOKUP` | `VLOOKUP`, `XLOOKUP` | `df.merge()`, `df.map()` |\n| Conditional sum | `SUMIFS` | `SUMIFS` | `df.groupby().sum()` |\n| Conditional count | `COUNTIFS` | `COUNTIFS` | `df.groupby().count()` |\n| Text split | `TEXTSPLIT`, `LEFT\u002FMID\u002FRIGHT` | `SPLIT` | `df.str.split()` |\n| Date diff | `DATEDIF`, math | `DATEDIF` | `(df.col2 - df.col1).dt.days` |\n| Running total | `SUM($A$1:A1)` | `SUM($A$1:A1)` | `df.cumsum()` |\n| Rank | `RANK.EQ` | `RANK` | `df.rank()` |\n| Percent of total | `=A1\u002FSUM($A:$A)` | `=A1\u002FSUM($A:$A)` | `df.col \u002F df.col.sum()` |\n| Remove duplicates | Data → Remove Duplicates | Data → Remove Duplicates | `df.drop_duplicates()` |\n| Pivot | Pivot Table | Pivot Table | `df.pivot_table()` |\n\n---\n\n## Phase 4: Analysis Frameworks\n\n### Quick Analysis Menu\n\nPick the analysis that matches the question:\n\n**Descriptive (What happened?)**\n- Summary statistics: count, mean, median, min, max, std dev, percentiles\n- Frequency distributions: how many of each category?\n- Time trends: daily\u002Fweekly\u002Fmonthly aggregates over time\n- Cross-tabs: category A × category B breakdown\n\n**Diagnostic (Why did it happen?)**\n- Drill-down: which segment drove the change?\n- Cohort analysis: behavior by signup month\n- Correlation: which variables move together?\n- Variance analysis: actual vs budget\u002Fforecast, by category\n\n**Predictive (What might happen?)**\n- Trend projection: linear\u002Fexponential fit + confidence\n- Moving averages: 7\u002F30\u002F90 day smoothing\n- Seasonality: same-period prior year comparison\n- Growth rate: MoM, QoQ, YoY percentage changes\n\n**Prescriptive (What should we do?)**\n- Pareto (80\u002F20): which 20% of X drives 80% of Y?\n- Scenario analysis: best\u002Fbase\u002Fworst case with different assumptions\n- Sensitivity: which input variable has biggest impact?\n- Break-even: at what point does X cover Y?\n\n### Insight Formula\n\nEvery finding MUST follow this structure:\n```\nINSIGHT: [What you found — one sentence]\nEVIDENCE: [The specific numbers]\nSO WHAT: [Why it matters to the business]\nACTION: [What to do about it]\nCONFIDENCE: [High\u002FMedium\u002FLow + why]\n```\n\nExample:\n```\nINSIGHT: Customer acquisition cost increased 43% in Q3 vs Q2\nEVIDENCE: CAC went from $47 to $67, driven by paid search CPC increase (+62%)\nSO WHAT: At current LTV of $180, payback period extended from 3.1 to 4.5 months\nACTION: Shift 30% of paid search budget to email\u002Freferral channels (CAC $12 and $23 respectively)\nCONFIDENCE: High — based on complete Stripe + Google Ads data for full quarter\n```\n\n---\n\n## Phase 5: Dashboard & Report Templates\n\n### Executive Summary Dashboard (1-page)\n\n```\n┌──────────────────────────────────────────────────┐\n│  EXECUTIVE DASHBOARD — [Period]                   │\n│                                                    │\n│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐│\n│  │ Revenue  │ │ Customers│ │ Margin  │ │  Growth ││\n│  │ $XXX,XXX │ │  X,XXX  │ │  XX.X%  │ │ +XX.X%  ││\n│  │ ▲ +X.X%  │ │ ▲ +XXX  │ │ ▼ -X.X% │ │ vs LY   ││\n│  └─────────┘ └─────────┘ └─────────┘ └─────────┘│\n│                                                    │\n│  [Trend chart — key metric over 12 months]        │\n│                                                    │\n│  TOP 3 INSIGHTS:                                  │\n│  1. [Insight + action]                            │\n│  2. [Insight + action]                            │\n│  3. [Insight + action]                            │\n│                                                    │\n│  ┌──────────────────┐ ┌──────────────────┐        │\n│  │ By Segment       │ │ By Channel       │        │\n│  │ (table or chart) │ │ (table or chart) │        │\n│  └──────────────────┘ └──────────────────┘        │\n└──────────────────────────────────────────────────┘\n```\n\n### KPI Formatting Rules\n\n| Element | Rule | Example |\n|---------|------|---------|\n| Big numbers | Abbreviate with 1 decimal | $1.2M, 14.3K |\n| Percentages | 1 decimal, always show direction | ▲ +12.3%, ▼ -4.1% |\n| Currency | 2 decimals for \u003C$1000, 0 for larger | $47.50, $12,000 |\n| Dates | Consistent format throughout | Jan 2025, not 01\u002F2025 |\n| Comparison | Always include baseline | $120K (+15% vs LY) |\n| RAG status | Use color + text | 🟢 On Track, 🟡 At Risk, 🔴 Behind |\n| Sparklines | Show direction at a glance | ▁▂▃▅▇ (trending up) |\n\n### Chart Selection Guide\n\n```\nWhat are you showing?\n│\n├─ Change over time → LINE chart (≤5 series) or AREA (stacked composition)\n│\n├─ Comparison across categories → BAR chart (horizontal for long labels)\n│\n├─ Part of whole → PIE (≤5 slices) or STACKED BAR (>5 or over time)\n│\n├─ Distribution → HISTOGRAM or BOX PLOT\n│\n├─ Relationship between 2 variables → SCATTER PLOT\n│\n├─ Geographic → MAP (if location data exists)\n│\n├─ Ranked list → HORIZONTAL BAR sorted descending\n│\n└─ Single KPI → BIG NUMBER with trend indicator\n\n⚠️ NEVER use:\n- 3D charts (distorts perception)\n- Dual Y-axes (misleads readers)\n- Pie with >7 slices (use bar instead)\n- Rainbow colors (use 2-3 colors max + grey)\n```\n\n---\n\n## Phase 6: Recurring Report Automation\n\n### Automation Checklist\n\n```yaml\nrecurring_report:\n  name: \"\"\n  frequency: \"\"          # daily, weekly, monthly, quarterly\n  owner: \"\"\n  recipients: []\n  \n  data_sources:\n    - source: \"\"         # file path, API, database\n      refresh: \"\"        # how data gets updated\n      format: \"\"\n  \n  processing_steps:\n    - step: \"load data\"\n      tool: \"\"           # Python, Excel macro, Google Apps Script\n    - step: \"clean\"\n      rules: []          # reference cleaning protocol\n    - step: \"transform\"\n      operations: []\n    - step: \"analyze\"\n      calculations: []\n    - step: \"format\"\n      template: \"\"       # dashboard template to populate\n    - step: \"deliver\"\n      method: \"\"         # email, Slack, shared drive, API push\n  \n  quality_checks:\n    - \"Row count within expected range (±20%)\"\n    - \"No NULL values in required columns\"\n    - \"Totals reconcile with source system\"\n    - \"Date range matches expected period\"\n    - \"Key metrics pass sanity check (no 10x jumps without explanation)\"\n  \n  error_handling:\n    - trigger: \"data source unavailable\"\n      action: \"use cached last-good version + alert\"\n    - trigger: \"row count outside range\"\n      action: \"pause + flag for human review\"\n    - trigger: \"metric exceeds 3× historical std dev\"\n      action: \"include anomaly callout in report\"\n```\n\n### Python Automation Template\n\n```python\n\"\"\"\nRecurring report: [NAME]\nSchedule: [FREQUENCY]\n\"\"\"\nimport pandas as pd\nfrom pathlib import Path\nfrom datetime import datetime\n\n# --- Config ---\nINPUT_PATH = Path(\"data\u002Fraw\u002F\")\nOUTPUT_PATH = Path(\"data\u002Freports\u002F\")\nREPORT_DATE = datetime.now().strftime(\"%Y-%m-%d\")\n\n# --- Load ---\ndf = pd.read_csv(INPUT_PATH \u002F \"source.csv\", parse_dates=[\"date\"])\n\n# --- Clean ---\ndf = df.drop_duplicates()\ndf = df.dropna(subset=[\"required_column\"])\ndf[\"amount\"] = pd.to_numeric(df[\"amount\"], errors=\"coerce\")\n\n# --- Transform ---\nsummary = (\n    df.groupby(\"category\")\n    .agg(\n        total=(\"amount\", \"sum\"),\n        count=(\"id\", \"count\"),\n        avg=(\"amount\", \"mean\"),\n    )\n    .sort_values(\"total\", ascending=False)\n    .reset_index()\n)\n\n# --- Quality Check ---\nassert len(df) > 0, \"Empty dataset!\"\nassert df[\"amount\"].isna().sum() \u002F len(df) \u003C 0.05, \"Too many missing amounts\"\n\n# --- Output ---\noutput_file = OUTPUT_PATH \u002F f\"report-{REPORT_DATE}.csv\"\nsummary.to_csv(output_file, index=False)\nprint(f\"✅ Report saved: {output_file} | {len(summary)} rows\")\n```\n\n---\n\n## Phase 7: Common Spreadsheet Patterns\n\n### Pattern 1: Financial Model\n\n```\nSheet structure:\n├── Assumptions    → All editable inputs in ONE place (highlighted cells)\n├── Revenue        → Formulas reference Assumptions\n├── Costs          → Formulas reference Assumptions  \n├── P&L            → Pulls from Revenue + Costs\n├── Cash Flow      → Derived from P&L + working capital\n├── Balance Sheet  → Derived from Cash Flow\n├── Scenarios      → Best\u002FBase\u002FWorst toggle that feeds Assumptions\n└── Dashboard      → Charts + KPIs pulling from P&L\u002FCash Flow\n\nRules:\n- Inputs = blue font or yellow background (pick one, be consistent)\n- Formulas = black font, never hardcode numbers in formula cells\n- Every formula traces back to Assumptions or raw data\n- No circular references\n- Include version number + last-updated date\n```\n\n### Pattern 2: CRM \u002F Contact Tracker\n\n```\nRequired columns:\n- id (auto-increment or UUID)\n- name, email, phone, company\n- source (how they found us)\n- status (lead → contacted → qualified → proposal → won\u002Flost)\n- last_contact_date\n- next_action + next_action_date\n- deal_value\n- notes\n\nDerived columns:\n- days_since_last_contact = TODAY() - last_contact_date\n- pipeline_stage_days = TODAY() - stage_entry_date\n- is_stale = days_since_last_contact > 14\n\nDashboard metrics:\n- Pipeline value by stage\n- Conversion rate stage-to-stage\n- Average days in each stage\n- Stale leads count (action needed)\n```\n\n### Pattern 3: Inventory \u002F Stock Tracker\n\n```\nRequired columns:\n- sku, name, category\n- quantity_on_hand, reorder_point, reorder_quantity\n- unit_cost, unit_price\n- last_received_date, last_sold_date\n- supplier\n\nDerived columns:\n- stock_value = quantity_on_hand × unit_cost\n- margin = (unit_price - unit_cost) \u002F unit_price\n- days_of_supply = quantity_on_hand \u002F avg_daily_sales\n- needs_reorder = quantity_on_hand \u003C= reorder_point\n\nAlerts:\n- 🔴 Below reorder point\n- 🟡 Within 7 days of stockout (based on velocity)\n- ⚪ Dead stock (no sales in 90 days)\n```\n\n### Pattern 4: Project \u002F Task Tracker\n\n```\nRequired columns:\n- task_id, task_name, description\n- assignee, priority (P0-P3)\n- status (backlog → in_progress → review → done)\n- start_date, due_date, completed_date\n- estimated_hours, actual_hours\n\nDerived columns:\n- days_remaining = due_date - TODAY()\n- is_overdue = due_date \u003C TODAY() AND status != \"done\"\n- effort_variance = actual_hours - estimated_hours\n- completion_rate = done_tasks \u002F total_tasks\n\nDashboard:\n- Burndown chart (remaining vs time)\n- Status distribution pie\n- Overdue tasks list\n- Team workload (tasks per assignee)\n```\n\n### Pattern 5: Budget vs Actual\n\n```\nStructure:\n- Rows: expense categories + revenue lines\n- Columns: Budget | Actual | Variance | Variance %\n- Group by: month or quarter\n\nKey formulas:\n- variance = actual - budget\n- variance_pct = (actual - budget) \u002F budget\n- YTD_budget = SUM of months through current\n- Run_rate = (YTD_actual \u002F months_elapsed) × 12\n\nConditional formatting:\n- Green: favorable variance (revenue over, cost under)\n- Red: unfavorable variance (revenue under, cost over)\n- Threshold: flag if |variance| > 10%\n```\n\n---\n\n## Phase 8: Data Quality Rules\n\n### Validation Checklist (run before any analysis)\n\n```yaml\nvalidation:\n  structural:\n    - \"No duplicate column names\"\n    - \"No completely empty columns\"\n    - \"No completely empty rows (except intentional separators)\"\n    - \"Consistent column count across all rows\"\n    - \"Headers in row 1 (no multi-row headers without handling)\"\n  \n  type_integrity:\n    - \"Date columns parse as valid dates\"\n    - \"Numeric columns contain no text (except headers)\"\n    - \"ID columns are unique where expected\"\n    - \"Email columns match basic email pattern\"\n    - \"Phone columns are consistent format\"\n  \n  business_rules:\n    - \"Revenue >= 0 (or explain negative = refund)\"\n    - \"Dates within expected range (not in future for historical data)\"\n    - \"Percentages between 0-100 (or 0-1, consistently)\"\n    - \"Status values match allowed list\"\n    - \"Foreign keys exist in reference table\"\n  \n  completeness:\n    - \"Required columns have \u003C5% missing\"\n    - \"No orphan records (child without parent)\"\n    - \"Date ranges are continuous (no gaps in daily data)\"\n```\n\n### Data Quality Score (0-100)\n\n| Dimension | Weight | Score 0-4 | Criteria |\n|-----------|--------|-----------|----------|\n| Completeness | 25% | | % of non-null values in required fields |\n| Uniqueness | 15% | | % of rows with valid unique keys |\n| Consistency | 20% | | % of values matching expected format\u002Ftype |\n| Accuracy | 20% | | % passing business rule validation |\n| Timeliness | 10% | | Data freshness vs expected refresh |\n| Conformity | 10% | | % matching standard formats (dates, phones, emails) |\n\n**Score = Σ(weight × score\u002F4 × 100)**\n\n- 90-100: Production-ready\n- 75-89: Minor fixes needed\n- 50-74: Significant cleanup required\n- \u003C50: Re-collect or restructure before use\n\n---\n\n## Phase 9: Format Conversion & Interop\n\n### Conversion Decision Matrix\n\n| From → To | Best Method | Watch Out For |\n|-----------|-------------|---------------|\n| CSV → Excel | pandas + openpyxl | Encoding, date parsing, leading zeros |\n| Excel → CSV | pandas or openpyxl | Multiple sheets, formulas lost, merged cells |\n| JSON → CSV | pandas json_normalize | Nested objects need flattening |\n| CSV → JSON | pandas to_json | Choose records vs columns orientation |\n| Excel → Google Sheets | Upload directly | Macros stripped, some formulas differ |\n| Google Sheets → Excel | Download as .xlsx | IMPORTRANGE breaks, custom functions lost |\n| PDF table → CSV | Tabula, pdfplumber | Layout detection, merged cells, multi-page |\n| HTML table → CSV | pandas read_html | Multiple tables, nested tables, encoding |\n\n### Encoding Survival Guide\n\n```\nGarbled text? Try these encodings in order:\n1. UTF-8 (default, handles all languages)\n2. UTF-8-BOM (Windows exports often add BOM)\n3. Latin-1 \u002F ISO-8859-1 (Western European)\n4. Windows-1252 (Windows \"ANSI\")\n5. Shift-JIS (Japanese)\n6. GB2312 \u002F GBK (Chinese)\n\nPython: pd.read_csv(\"file.csv\", encoding=\"utf-8-sig\")\nDetection: chardet or charset-normalizer library\n```\n\n---\n\n## Phase 10: Performance & Scale\n\n### Size Thresholds\n\n| Rows | Tool Recommendation |\n|------|-------------------|\n| \u003C10K | Any tool (Excel, Sheets, pandas) |\n| 10K-100K | Excel (careful) or pandas |\n| 100K-1M | pandas with chunking, or DuckDB |\n| 1M-10M | DuckDB, Polars, or database |\n| >10M | Database (PostgreSQL, BigQuery) |\n\n### Performance Tips\n\n- **Read only needed columns**: `pd.read_csv(file, usecols=[\"col1\",\"col2\"])`\n- **Specify dtypes upfront**: Prevents inference overhead\n- **Use chunking for large files**: `pd.read_csv(file, chunksize=50000)`\n- **Categoricals for low-cardinality**: `df[\"status\"] = df[\"status\"].astype(\"category\")`\n- **Avoid iterrows**: Use vectorized operations or `.apply()`\n- **DuckDB for SQL on files**: `duckdb.sql(\"SELECT * FROM 'file.csv' WHERE x > 100\")`\n\n---\n\n## Phase 11: Edge Cases & Gotchas\n\n### The Dirty Dozen (most common data problems)\n\n1. **Mixed date formats** — US (MM\u002FDD) vs EU (DD\u002FMM) vs ISO (YYYY-MM-DD) in same column\n2. **Excel date serial numbers** — 44927 instead of 2023-01-01\n3. **Leading zeros stripped** — ZIP code 01234 becomes 1234\n4. **Scientific notation** — ID 1234567890123 becomes 1.23457E+12\n5. **Hidden characters** — Non-breaking spaces, zero-width chars, BOM markers\n6. **Merged cells** — Only top-left has value, rest are empty\n7. **Number-as-text** — \"100\" (text) vs 100 (number), looks identical\n8. **Locale-dependent decimals** — 1,234.56 vs 1.234,56\n9. **Empty string vs NULL** — \"\" and NaN behave differently\n10. **Trailing whitespace** — \"New York \" ≠ \"New York\"\n11. **Excel 1904 date system** — Mac-origin files, dates off by 4 years\n12. **Formula results vs formulas** — Copy-paste values loses formulas silently\n\n### Multi-Currency Handling\n\n```yaml\ncurrency_rules:\n  - Store amount AND currency code in separate columns\n  - Never mix currencies in a single column without code\n  - Use ISO 4217 codes (USD, GBP, EUR, BTC)\n  - Store exchange rate and rate date used for conversion\n  - Keep original amount + converted amount as separate columns\n  - Specify: is this the rate at transaction time or current rate?\n```\n\n### Time Zone Handling\n\n```yaml\ntimezone_rules:\n  - Store timestamps in UTC internally\n  - Record the source timezone\n  - Convert to local time only for display\n  - \"End of day\" = 23:59:59 in the business timezone, not UTC\n  - Daylight saving transitions can cause 23h or 25h days\n  - Aggregate daily data in business timezone, not UTC\n```\n\n---\n\n## Phase 12: Quality Scoring Rubric (0-100)\n\n| Dimension | Weight | 0 (Fail) | 1 (Poor) | 2 (Fair) | 3 (Good) | 4 (Excellent) |\n|-----------|--------|----------|----------|----------|----------|----------------|\n| **Data Cleanliness** | 20% | Raw dump, untouched | Some cleaning, inconsistent | Most issues addressed | Clean with documented process | Spotless + automated validation |\n| **Structure** | 15% | Unstructured mess | Basic tabular, issues | Proper structure, minor gaps | Tidy data, good schema | Perfect normalization + relationships |\n| **Analysis Depth** | 20% | No analysis | Basic counts\u002Fsums | Segmented analysis | Multi-dimensional + insights | Predictive + prescriptive + actions |\n| **Visualization** | 15% | No charts | Wrong chart types | Adequate charts | Clear, well-labeled charts | Publication-quality dashboards |\n| **Documentation** | 10% | None | Minimal notes | Column descriptions | Full data dictionary + methodology | Reproducible + versioned |\n| **Automation** | 10% | Manual everything | Some formulas | Template-based | Scripted pipeline | Fully automated + monitored |\n| **Accuracy** | 10% | Unverified | Spot-checked | Sample-validated | Cross-referenced with source | Reconciled + audit trail |\n\n**Grading: 90+** = Production analytics, **75-89** = Solid work, **60-74** = Needs improvement, **\u003C60** = Redo\n\n---\n\n## Natural Language Commands\n\n```\n\"Clean this CSV\"           → Run Phase 2 cleaning protocol, output clean file + log\n\"Analyze this data\"        → Phase 1 assessment → Phase 4 analysis → insights\n\"Build a dashboard\"        → Phase 5 template → populate with data\n\"Convert this to Excel\"    → Phase 9 conversion with quality preservation\n\"Find duplicates\"          → Dedup analysis with exact + fuzzy matching\n\"What's wrong with this data?\" → Phase 1 health check + Phase 8 validation\n\"Create a monthly report\"  → Phase 6 automation template\n\"Compare these two files\"  → Join + variance analysis\n\"Summarize by category\"    → Group + aggregate + Pareto analysis\n\"Make this data tidy\"      → Unpivot\u002Freshape to 1-row-per-observation\n\"Set up a budget tracker\"  → Phase 7 Pattern 5 template\n\"Profile this dataset\"     → Full Phase 1 + Phase 8 quality score\n```\n\n---\n\n## Related AfrexAI Skills\n\n- `afrexai-data-analyst` — Advanced analytical methodology (DICE framework, statistical analysis)\n- `afrexai-fpa-engine` — Financial planning & analysis with spreadsheet models\n- `afrexai-budget-tracker` — Personal\u002Fbusiness budget management\n- `afrexai-business-automation` — Automate recurring spreadsheet workflows\n\n---\n\n⚡ **Level up your data game** → [AfrexAI Context Packs ($47)](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F) — industry-specific data templates, KPI frameworks, and reporting automations for SaaS, Fintech, Manufacturing, Ecommerce, and more.\n\n🔗 **More free skills by AfrexAI:**\n- `afrexai-data-analyst` — Complete data analysis methodology\n- `afrexai-business-automation` — Workflow automation frameworks\n- `afrexai-seo-content-engine` — SEO-optimized content creation\n- `afrexai-customer-success` — Customer retention & health scoring\n- `afrexai-devops-engine` — DevOps & platform engineering\n\n📦 Browse all: [AfrexAI Storefront](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n","# Spreadsheet & Data Wrangling Master\n\n> Turn messy data into clean insights, automated reports, and decision-ready dashboards. Platform-agnostic — works with CSV, Excel, Google Sheets, or any tabular format.\n\n---\n\n## Phase 1: Data Intake & Assessment\n\nBefore touching any data, assess what you have.\n\n### Quick Health Check (score \u002F20)\n\n```yaml\ndata_intake:\n  source: \"\"           # file path, URL, API, database, manual entry\n  format: \"\"           # CSV, XLSX, TSV, JSON, clipboard paste\n  rows: 0\n  columns: 0\n  file_size: \"\"\n  encoding: \"\"         # UTF-8, Latin-1, Windows-1252, etc.\n  delimiter: \"\"        # comma, tab, pipe, semicolon\n\n  health_score:        # rate each 0-4, total \u002F20\n    completeness: 0    # 4=\u003C1% missing, 3=\u003C5%, 2=\u003C15%, 1=\u003C30%, 0=>30%\n    consistency: 0     # 4=uniform types, 3=minor mixed, 2=significant mixed, 1=chaotic, 0=unusable\n    accuracy: 0        # 4=verified, 3=plausible, 2=some outliers, 1=many errors, 0=untrustworthy\n    freshness: 0       # 4=real-time, 3=\u003C24h, 2=\u003C7d, 1=\u003C30d, 0=stale\u002Funknown\n    structure: 0       # 4=tidy (1 row=1 obs), 3=minor reshaping, 2=pivot needed, 1=multi-header, 0=freeform\n\n  issues_found: []     # list every problem before fixing anything\n```\n\n### First 10 Questions to Ask\n\n1. How many rows and columns?\n2. What does each row represent? (one customer? one transaction? one day?)\n3. Are there header rows? Multiple header rows? Merged cells?\n4. What are the data types? (dates, currencies, percentages, IDs, free text)\n5. How much is missing? Which columns?\n6. Are there duplicates? By which key?\n7. Is there a unique identifier column?\n8. What date format? (MM\u002FDD\u002FYYYY vs DD\u002FMM\u002FYYYY vs YYYY-MM-DD vs mixed)\n9. What currency\u002Fnumber format? (1,000.00 vs 1.000,00 vs 1000)\n10. Where did this data come from and how often is it updated?\n\n---\n\n## Phase 2: Data Cleaning Decision Tree\n\n### Step-by-Step Cleaning Protocol\n\n```\nSTART\n  │\n  ├─ Headers → Normalize (lowercase, snake_case, no spaces\u002Fspecial chars)\n  │\n  ├─ Duplicates?\n  │   ├─ Exact duplicates → Remove, keep first\n  │   ├─ Near-duplicates → Flag for review (fuzzy match on name + address)\n  │   └─ Intentional duplicates → Leave (e.g., multiple orders same customer)\n  │\n  ├─ Missing Values?\n  │   ├─ \u003C5% of column → Fill (mean for numeric, mode for categorical, forward-fill for time series)\n  │   ├─ 5-30% → Flag + fill with \"UNKNOWN\" or interpolate with justification\n  │   ├─ >30% → Consider dropping column or flagging as unreliable\n  │   └─ Entire row missing key fields → Remove with log\n  │\n  ├─ Data Types?\n  │   ├─ Dates as text → Parse to date (try multiple formats, log failures)\n  │   ├─ Numbers as text → Strip currency symbols, commas, whitespace, convert\n  │   ├─ IDs\u002Fzips with leading zeros → Keep as text (NEVER convert to number)\n  │   ├─ Phone numbers → Text, standardize format\n  │   ├─ Mixed types in column → Split or coerce with error log\n  │   └─ Boolean variants → Map (Yes\u002FNo\u002FTrue\u002FFalse\u002F1\u002F0\u002FY\u002FN → consistent)\n  │\n  ├─ Outliers?\n  │   ├─ Calculate IQR: Q1 - 1.5×IQR to Q3 + 1.5×IQR\n  │   ├─ Business logic check (negative revenue? age 200? date in 2099?)\n  │   ├─ Decide: fix (typo), cap (winsorize), remove, or keep with flag\n  │   └─ ALWAYS log which outliers were modified and why\n  │\n  ├─ Standardization?\n  │   ├─ Text case → Consistent (Title Case for names, UPPER for codes)\n  │   ├─ Whitespace → Trim leading\u002Ftrailing, collapse internal\n  │   ├─ Categories → Map variants (\"US\"\u002F\"USA\"\u002F\"United States\" → \"US\")\n  │   ├─ Dates → ISO 8601 (YYYY-MM-DD) internally\n  │   ├─ Currency → Consistent symbol placement, decimal precision\n  │   └─ Phone\u002Femail → Validate format\n  │\n  └─ Structural Issues?\n      ├─ Multi-header rows → Flatten to single header\n      ├─ Merged cells → Unmerge + fill down\n      ├─ Pivot\u002Fcrosstab → Unpivot to tidy format (1 row = 1 observation)\n      ├─ Multiple tables in one sheet → Split to separate sheets\u002Ffiles\n      └─ Metadata rows (totals, notes) → Separate from data rows\n```\n\n### Cleaning Log Template\n\n```yaml\ncleaning_log:\n  date: \"YYYY-MM-DD\"\n  source_file: \"\"\n  rows_before: 0\n  rows_after: 0\n  actions:\n    - action: \"removed exact duplicates\"\n      rows_affected: 0\n      key_columns: [\"email\"]\n    - action: \"filled missing values\"\n      column: \"state\"\n      method: \"mode\"\n      values_filled: 0\n    - action: \"removed outliers\"\n      column: \"revenue\"\n      criteria: \"negative values\"\n      rows_removed: 0\n    - action: \"standardized dates\"\n      column: \"order_date\"\n      from_format: \"MM\u002FDD\u002FYYYY\"\n      to_format: \"YYYY-MM-DD\"\n      parse_failures: 0\n  notes: \"\"\n```\n\n---\n\n## Phase 3: Transformation Patterns\n\n### 12 Essential Transform Operations\n\n| # | Operation | When to Use | Example |\n|---|-----------|-------------|---------|\n| 1 | **Filter** | Subset rows by condition | Orders > $1000, Date after 2024-01-01 |\n| 2 | **Sort** | Order by column(s) | Revenue descending, then date ascending |\n| 3 | **Group + Aggregate** | Summarize by category | Total revenue by region, avg order by customer |\n| 4 | **Pivot** | Rows → columns | Monthly columns from date rows |\n| 5 | **Unpivot\u002FMelt** | Columns → rows | Month columns back to date rows |\n| 6 | **Join\u002FMerge** | Combine datasets | Customer data + order data on customer_id |\n| 7 | **Deduplicate** | Remove redundancy | Keep latest record per customer |\n| 8 | **Derive** | Calculate new columns | profit = revenue - cost, age = today - birthdate |\n| 9 | **Split** | One column → many | \"John Smith\" → first_name, last_name |\n| 10 | **Concatenate** | Many columns → one | city + state + zip → full_address |\n| 11 | **Lookup\u002FMap** | Enrich with reference data | state_code → state_name, product_id → category |\n| 12 | **Window** | Running calculations | 7-day moving average, rank within group, running total |\n\n### Join Strategy Decision Guide\n\n```\nWhich join do you need?\n│\n├─ Need ALL rows from left table → LEFT JOIN\n│   (customers who may or may not have orders)\n│\n├─ Need ONLY matching rows → INNER JOIN\n│   (only customers WITH orders)\n│\n├─ Need ALL rows from both → FULL OUTER JOIN\n│   (reconciliation: find mismatches)\n│\n├─ Need everything NOT in other table → LEFT JOIN + WHERE right IS NULL\n│   (customers who NEVER ordered)\n│\n└─ Need every combination → CROSS JOIN (rare, use carefully)\n    (all products × all stores for pricing matrix)\n\n⚠️ ALWAYS check join results:\n- Row count: did it explode? (many-to-many join)\n- Row count: did it shrink? (keys not matching)\n- NULL columns: expected from outer join, unexpected = key mismatch\n```\n\n### Formula Reference (Cross-Platform)\n\n| Task | Excel | Google Sheets | Python (pandas) |\n|------|-------|---------------|-----------------|\n| Lookup | `VLOOKUP`, `XLOOKUP` | `VLOOKUP`, `XLOOKUP` | `df.merge()`, `df.map()` |\n| Conditional sum | `SUMIFS` | `SUMIFS` | `df.groupby().sum()` |\n| Conditional count | `COUNTIFS` | `COUNTIFS` | `df.groupby().count()` |\n| Text split | `TEXTSPLIT`, `LEFT\u002FMID\u002FRIGHT` | `SPLIT` | `df.str.split()` |\n| Date diff | `DATEDIF`, math | `DATEDIF` | `(df.col2 - df.col1).dt.days` |\n| Running total | `SUM($A$1:A1)` | `SUM($A$1:A1)` | `df.cumsum()` |\n| Rank | `RANK.EQ` | `RANK` | `df.rank()` |\n| Percent of total | `=A1\u002FSUM($A:$A)` | `=A1\u002FSUM($A:$A)` | `df.col \u002F df.col.sum()` |\n| Remove duplicates | Data → Remove Duplicates | Data → Remove Duplicates | `df.drop_duplicates()` |\n| Pivot | Pivot Table | Pivot Table | `df.pivot_table()` |\n\n---\n\n## Phase 4: Analysis Frameworks\n\n### Quick Analysis Menu\n\nPick the analysis that matches the question:\n\n**Descriptive (What happened?)**\n- Summary statistics: count, mean, median, min, max, std dev, percentiles\n- Frequency distributions: how many of each category?\n- Time trends: daily\u002Fweekly\u002Fmonthly aggregates over time\n- Cross-tabs: category A × category B breakdown\n\n**Diagnostic (Why did it happen?)**\n- Drill-down: which segment drove the change?\n- Cohort analysis: behavior by signup month\n- Correlation: which variables move together?\n- Variance analysis: actual vs budget\u002Fforecast, by category\n\n**Predictive (What might happen?)**\n- Trend projection: linear\u002Fexponential fit + confidence\n- Moving averages: 7\u002F30\u002F90 day smoothing\n- Seasonality: same-period prior year comparison\n- Growth rate: MoM, QoQ, YoY percentage changes\n\n**Prescriptive (What should we do?)**\n- Pareto (80\u002F20): which 20% of X drives 80% of Y?\n- Scenario analysis: best\u002Fbase\u002Fworst case with different assumptions\n- Sensitivity: which input variable has biggest impact?\n- Break-even: at what point does X cover Y?\n\n### Insight Formula\n\nEvery finding MUST follow this structure:\n```\nINSIGHT: [What you found — one sentence]\nEVIDENCE: [The specific numbers]\nSO WHAT: [Why it matters to the business]\nACTION: [What to do about it]\nCONFIDENCE: [High\u002FMedium\u002FLow + why]\n```\n\nExample:\n```\nINSIGHT: Customer acquisition cost increased 43% in Q3 vs Q2\nEVIDENCE: CAC went from $47 to $67, driven by paid search CPC increase (+62%)\nSO WHAT: At current LTV of $180, payback period extended from 3.1 to 4.5 months\nACTION: Shift 30% of paid search budget to email\u002Freferral channels (CAC $12 and $23 respectively)\nCONFIDENCE: High — based on complete Stripe + Google Ads data for full quarter\n```\n\n---\n\n## Phase 5: Dashboard & Report Templates\n\n### Executive Summary Dashboard (1-page)\n\n```\n┌──────────────────────────────────────────────────┐\n│  EXECUTIVE DASHBOARD — [Period]                   │\n│                                                    │\n│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐│\n│  │ Revenue  │ │ Customers│ │ Margin  │ │  Growth ││\n│  │ $XXX,XXX │ │  X,XXX  │ │  XX.X%  │ │ +XX.X%  ││\n│  │ ▲ +X.X%  │ │ ▲ +XXX  │ │ ▼ -X.X% │ │ vs LY   ││\n│  └─────────┘ └─────────┘ └─────────┘ └─────────┘│\n│                                                    │\n│  [Trend chart — key metric over 12 months]        │\n│                                                    │\n│  TOP 3 INSIGHTS:                                  │\n│  1. [Insight + action]                            │\n│  2. [Insight + action]                            │\n│  3. [Insight + action]                            │\n│                                                    │\n│  ┌──────────────────┐ ┌──────────────────┐        │\n│  │ By Segment       │ │ By Channel       │        │\n│  │ (table or chart) │ │ (table or chart) │        │\n│  └──────────────────┘ └──────────────────┘        │\n└──────────────────────────────────────────────────┘\n```\n\n### KPI Formatting Rules\n\n| Element | Rule | Example |\n|---------|------|---------|\n| Big numbers | Abbreviate with 1 decimal | $1.2M, 14.3K |\n| Percentages | 1 decimal, always show direction | ▲ +12.3%, ▼ -4.1% |\n| Currency | 2 decimals for \u003C$1000, 0 for larger | $47.50, $12,000 |\n| Dates | Consistent format throughout | Jan 2025, not 01\u002F2025 |\n| Comparison | Always include baseline | $120K (+15% vs LY) |\n| RAG status | Use color + text | 🟢 On Track, 🟡 At Risk, 🔴 Behind |\n| Sparklines | Show direction at a glance | ▁▂▃▅▇ (trending up) |\n\n### Chart Selection Guide\n\n```\nWhat are you showing?\n│\n├─ Change over time → LINE chart (≤5 series) or AREA (stacked composition)\n│\n├─ Comparison across categories → BAR chart (horizontal for long labels)\n│\n├─ Part of whole → PIE (≤5 slices) or STACKED BAR (>5 or over time)\n│\n├─ Distribution → HISTOGRAM or BOX PLOT\n│\n├─ Relationship between 2 variables → SCATTER PLOT\n│\n├─ Geographic → MAP (if location data exists)\n│\n├─ Ranked list → HORIZONTAL BAR sorted descending\n│\n└─ Single KPI → BIG NUMBER with trend indicator\n\n⚠️ NEVER use:\n- 3D charts (distorts perception)\n- Dual Y-axes (misleads readers)\n- Pie with >7 slices (use bar instead)\n- Rainbow colors (use 2-3 colors max + grey)\n```\n\n---\n\n## Phase 6: Recurring Report Automation\n\n### Automation Checklist\n\n```yaml\nrecurring_report:\n  name: \"\"\n  frequency: \"\"          # daily, weekly, monthly, quarterly\n  owner: \"\"\n  recipients: []\n  \n  data_sources:\n    - source: \"\"         # file path, API, database\n      refresh: \"\"        # how data gets updated\n      format: \"\"\n  \n  processing_steps:\n    - step: \"load data\"\n      tool: \"\"           # Python, Excel macro, Google Apps Script\n    - step: \"clean\"\n      rules: []          # reference cleaning protocol\n    - step: \"transform\"\n      operations: []\n    - step: \"analyze\"\n      calculations: []\n    - step: \"format\"\n      template: \"\"       # dashboard template to populate\n    - step: \"deliver\"\n      method: \"\"         # email, Slack, shared drive, API push\n  \n  quality_checks:\n    - \"Row count within expected range (±20%)\"\n    - \"No NULL values in required columns\"\n    - \"Totals reconcile with source system\"\n    - \"Date range matches expected period\"\n    - \"Key metrics pass sanity check (no 10x jumps without explanation)\"\n  \n  error_handling:\n    - trigger: \"data source unavailable\"\n      action: \"use cached last-good version + alert\"\n    - trigger: \"row count outside range\"\n      action: \"pause + flag for human review\"\n    - trigger: \"metric exceeds 3× historical std dev\"\n      action: \"include anomaly callout in report\"\n```\n\n### Python Automation Template\n\n```python\n\"\"\"\nRecurring report: [NAME]\nSchedule: [FREQUENCY]\n\"\"\"\nimport pandas as pd\nfrom pathlib import Path\nfrom datetime import datetime\n\n# --- Config ---\nINPUT_PATH = Path(\"data\u002Fraw\u002F\")\nOUTPUT_PATH = Path(\"data\u002Freports\u002F\")\nREPORT_DATE = datetime.now().strftime(\"%Y-%m-%d\")\n\n# --- Load ---\ndf = pd.read_csv(INPUT_PATH \u002F \"source.csv\", parse_dates=[\"date\"])\n\n# --- Clean ---\ndf = df.drop_duplicates()\ndf = df.dropna(subset=[\"required_column\"])\ndf[\"amount\"] = pd.to_numeric(df[\"amount\"], errors=\"coerce\")\n\n# --- Transform ---\nsummary = (\n    df.groupby(\"category\")\n    .agg(\n        total=(\"amount\", \"sum\"),\n        count=(\"id\", \"count\"),\n        avg=(\"amount\", \"mean\"),\n    )\n    .sort_values(\"total\", ascending=False)\n    .reset_index()\n)\n\n# --- Quality Check ---\nassert len(df) > 0, \"Empty dataset!\"\nassert df[\"amount\"].isna().sum() \u002F len(df) \u003C 0.05, \"Too many missing amounts\"\n\n# --- Output ---\noutput_file = OUTPUT_PATH \u002F f\"report-{REPORT_DATE}.csv\"\nsummary.to_csv(output_file, index=False)\nprint(f\"✅ Report saved: {output_file} | {len(summary)} rows\")\n```\n\n---\n\n## Phase 7: Common Spreadsheet Patterns\n\n### Pattern 1: Financial Model\n\n```\nSheet structure:\n├── Assumptions    → All editable inputs in ONE place (highlighted cells)\n├── Revenue        → Formulas reference Assumptions\n├── Costs          → Formulas reference Assumptions  \n├── P&L            → Pulls from Revenue + Costs\n├── Cash Flow      → Derived from P&L + working capital\n├── Balance Sheet  → Derived from Cash Flow\n├── Scenarios      → Best\u002FBase\u002FWorst toggle that feeds Assumptions\n└── Dashboard      → Charts + KPIs pulling from P&L\u002FCash Flow\n\nRules:\n- Inputs = blue font or yellow background (pick one, be consistent)\n- Formulas = black font, never hardcode numbers in formula cells\n- Every formula traces back to Assumptions or raw data\n- No circular references\n- Include version number + last-updated date\n```\n\n### Pattern 2: CRM \u002F Contact Tracker\n\n```\nRequired columns:\n- id (auto-increment or UUID)\n- name, email, phone, company\n- source (how they found us)\n- status (lead → contacted → qualified → proposal → won\u002Flost)\n- last_contact_date\n- next_action + next_action_date\n- deal_value\n- notes\n\nDerived columns:\n- days_since_last_contact = TODAY() - last_contact_date\n- pipeline_stage_days = TODAY() - stage_entry_date\n- is_stale = days_since_last_contact > 14\n\nDashboard metrics:\n- Pipeline value by stage\n- Conversion rate stage-to-stage\n- Average days in each stage\n- Stale leads count (action needed)\n```\n\n### Pattern 3: Inventory \u002F Stock Tracker\n\n```\nRequired columns:\n- sku, name, category\n- quantity_on_hand, reorder_point, reorder_quantity\n- unit_cost, unit_price\n- last_received_date, last_sold_date\n- supplier\n\nDerived columns:\n- stock_value = quantity_on_hand × unit_cost\n- margin = (unit_price - unit_cost) \u002F unit_price\n- days_of_supply = quantity_on_hand \u002F avg_daily_sales\n- needs_reorder = quantity_on_hand \u003C= reorder_point\n\nAlerts:\n- 🔴 Below reorder point\n- 🟡 Within 7 days of stockout (based on velocity)\n- ⚪ Dead stock (no sales in 90 days)\n```\n\n### Pattern 4: Project \u002F Task Tracker\n\n```\nRequired columns:\n- task_id, task_name, description\n- assignee, priority (P0-P3)\n- status (backlog → in_progress → review → done)\n- start_date, due_date, completed_date\n- estimated_hours, actual_hours\n\nDerived columns:\n- days_remaining = due_date - TODAY()\n- is_overdue = due_date \u003C TODAY() AND status != \"done\"\n- effort_variance = actual_hours - estimated_hours\n- completion_rate = done_tasks \u002F total_tasks\n\nDashboard:\n- Burndown chart (remaining vs time)\n- Status distribution pie\n- Overdue tasks list\n- Team workload (tasks per assignee)\n```\n\n### Pattern 5: Budget vs Actual\n\n```\nStructure:\n- Rows: expense categories + revenue lines\n- Columns: Budget | Actual | Variance | Variance %\n- Group by: month or quarter\n\nKey formulas:\n- variance = actual - budget\n- variance_pct = (actual - budget) \u002F budget\n- YTD_budget = SUM of months through current\n- Run_rate = (YTD_actual \u002F months_elapsed) × 12\n\nConditional formatting:\n- Green: favorable variance (revenue over, cost under)\n- Red: unfavorable variance (revenue under, cost over)\n- Threshold: flag if |variance| > 10%\n```\n\n---\n\n## Phase 8: Data Quality Rules\n\n### Validation Checklist (run before any analysis)\n\n```yaml\nvalidation:\n  structural:\n    - \"No duplicate column names\"\n    - \"No completely empty columns\"\n    - \"No completely empty rows (except intentional separators)\"\n    - \"Consistent column count across all rows\"\n    - \"Headers in row 1 (no multi-row headers without handling)\"\n  \n  type_integrity:\n    - \"Date columns parse as valid dates\"\n    - \"Numeric columns contain no text (except headers)\"\n    - \"ID columns are unique where expected\"\n    - \"Email columns match basic email pattern\"\n    - \"Phone columns are consistent format\"\n  \n  business_rules:\n    - \"Revenue >= 0 (or explain negative = refund)\"\n    - \"Dates within expected range (not in future for historical data)\"\n    - \"Percentages between 0-100 (or 0-1, consistently)\"\n    - \"Status values match allowed list\"\n    - \"Foreign keys exist in reference table\"\n  \n  completeness:\n    - \"Required columns have \u003C5% missing\"\n    - \"No orphan records (child without parent)\"\n    - \"Date ranges are continuous (no gaps in daily data)\"\n```\n\n### Data Quality Score (0-100)\n\n| Dimension | Weight | Score 0-4 | Criteria |\n|-----------|--------|-----------|----------|\n| Completeness | 25% | | % of non-null values in required fields |\n| Uniqueness | 15% | | % of rows with valid unique keys |\n| Consistency | 20% | | % of values matching expected format\u002Ftype |\n| Accuracy | 20% | | % passing business rule validation |\n| Timeliness | 10% | | Data freshness vs expected refresh |\n| Conformity | 10% | | % matching standard formats (dates, phones, emails) |\n\n**Score = Σ(weight × score\u002F4 × 100)**\n\n- 90-100: Production-ready\n- 75-89: Minor fixes needed\n- 50-74: Significant cleanup required\n- \u003C50: Re-collect or restructure before use\n\n---\n\n## Phase 9: Format Conversion & Interop\n\n### Conversion Decision Matrix\n\n| From → To | Best Method | Watch Out For |\n|-----------|-------------|---------------|\n| CSV → Excel | pandas + openpyxl | Encoding, date parsing, leading zeros |\n| Excel → CSV | pandas or openpyxl | Multiple sheets, formulas lost, merged cells |\n| JSON → CSV | pandas json_normalize | Nested objects need flattening |\n| CSV → JSON | pandas to_json | Choose records vs columns orientation |\n| Excel → Google Sheets | Upload directly | Macros stripped, some formulas differ |\n| Google Sheets → Excel | Download as .xlsx | IMPORTRANGE breaks, custom functions lost |\n| PDF table → CSV | Tabula, pdfplumber | Layout detection, merged cells, multi-page |\n| HTML table → CSV | pandas read_html | Multiple tables, nested tables, encoding |\n\n### Encoding Survival Guide\n\n```\nGarbled text? Try these encodings in order:\n1. UTF-8 (default, handles all languages)\n2. UTF-8-BOM (Windows exports often add BOM)\n3. Latin-1 \u002F ISO-8859-1 (Western European)\n4. Windows-1252 (Windows \"ANSI\")\n5. Shift-JIS (Japanese)\n6. GB2312 \u002F GBK (Chinese)\n\nPython: pd.read_csv(\"file.csv\", encoding=\"utf-8-sig\")\nDetection: chardet or charset-normalizer library\n```\n\n---\n\n## Phase 10: Performance & Scale\n\n### Size Thresholds\n\n| Rows | Tool Recommendation |\n|------|-------------------|\n| \u003C10K | Any tool (Excel, Sheets, pandas) |\n| 10K-100K | Excel (careful) or pandas |\n| 100K-1M | pandas with chunking, or DuckDB |\n| 1M-10M | DuckDB, Polars, or database |\n| >10M | Database (PostgreSQL, BigQuery) |\n\n### Performance Tips\n\n- **Read only needed columns**: `pd.read_csv(file, usecols=[\"col1\",\"col2\"])`\n- **Specify dtypes upfront**: Prevents inference overhead\n- **Use chunking for large files**: `pd.read_csv(file, chunksize=50000)`\n- **Categoricals for low-cardinality**: `df[\"status\"] = df[\"status\"].astype(\"category\")`\n- **Avoid iterrows**: Use vectorized operations or `.apply()`\n- **DuckDB for SQL on files**: `duckdb.sql(\"SELECT * FROM 'file.csv' WHERE x > 100\")`\n\n---\n\n## Phase 11: Edge Cases & Gotchas\n\n### The Dirty Dozen (most common data problems)\n\n1. **Mixed date formats** — US (MM\u002FDD) vs EU (DD\u002FMM) vs ISO (YYYY-MM-DD) in same column\n2. **Excel date serial numbers** — 44927 instead of 2023-01-01\n3. **Leading zeros stripped** — ZIP code 01234 becomes 1234\n4. **Scientific notation** — ID 1234567890123 becomes 1.23457E+12\n5. **Hidden characters** — Non-breaking spaces, zero-width chars, BOM markers\n6. **Merged cells** — Only top-left has value, rest are empty\n7. **Number-as-text** — \"100\" (text) vs 100 (number), looks identical\n8. **Locale-dependent decimals** — 1,234.56 vs 1.234,56\n9. **Empty string vs NULL** — \"\" and NaN behave differently\n10. **Trailing whitespace** — \"New York \" ≠ \"New York\"\n11. **Excel 1904 date system** — Mac-origin files, dates off by 4 years\n12. **Formula results vs formulas** — Copy-paste values loses formulas silently\n\n### Multi-Currency Handling\n\n```yaml\ncurrency_rules:\n  - Store amount AND currency code in separate columns\n  - Never mix currencies in a single column without code\n  - Use ISO 4217 codes (USD, GBP, EUR, BTC)\n  - Store exchange rate and rate date used for conversion\n  - Keep original amount + converted amount as separate columns\n  - Specify: is this the rate at transaction time or current rate?\n```\n\n### Time Zone Handling\n\n```yaml\ntimezone_rules:\n  - Store timestamps in UTC internally\n  - Record the source timezone\n  - Convert to local time only for display\n  - \"End of day\" = 23:59:59 in the business timezone, not UTC\n  - Daylight saving transitions can cause 23h or 25h days\n  - Aggregate daily data in business timezone, not UTC\n```\n\n---\n\n## Phase 12: Quality Scoring Rubric (0-100)\n\n| Dimension | Weight | 0 (Fail) | 1 (Poor) | 2 (Fair) | 3 (Good) | 4 (Excellent) |\n|-----------|--------|----------|----------|----------|----------|----------------|\n| **Data Cleanliness** | 20% | Raw dump, untouched | Some cleaning, inconsistent | Most issues addressed | Clean with documented process | Spotless + automated validation |\n| **Structure** | 15% | Unstructured mess | Basic tabular, issues | Proper structure, minor gaps | Tidy data, good schema | Perfect normalization + relationships |\n| **Analysis Depth** | 20% | No analysis | Basic counts\u002Fsums | Segmented analysis | Multi-dimensional + insights | Predictive + prescriptive + actions |\n| **Visualization** | 15% | No charts | Wrong chart types | Adequate charts | Clear, well-labeled charts | Publication-quality dashboards |\n| **Documentation** | 10% | None | Minimal notes | Column descriptions | Full data dictionary + methodology | Reproducible + versioned |\n| **Automation** | 10% | Manual everything | Some formulas | Template-based | Scripted pipeline | Fully automated + monitored |\n| **Accuracy** | 10% | Unverified | Spot-checked | Sample-validated | Cross-referenced with source | Reconciled + audit trail |\n\n**Grading: 90+** = Production analytics, **75-89** = Solid work, **60-74** = Needs improvement, **\u003C60** = Redo\n\n---\n\n## Natural Language Commands\n\n```\n\"Clean this CSV\"           → Run Phase 2 cleaning protocol, output clean file + log\n\"Analyze this data\"        → Phase 1 assessment → Phase 4 analysis → insights\n\"Build a dashboard\"        → Phase 5 template → populate with data\n\"Convert this to Excel\"    → Phase 9 conversion with quality preservation\n\"Find duplicates\"          → Dedup analysis with exact + fuzzy matching\n\"What's wrong with this data?\" → Phase 1 health check + Phase 8 validation\n\"Create a monthly report\"  → Phase 6 automation template\n\"Compare these two files\"  → Join + variance analysis\n\"Summarize by category\"    → Group + aggregate + Pareto analysis\n\"Make this data tidy\"      → Unpivot\u002Freshape to 1-row-per-observation\n\"Set up a budget tracker\"  → Phase 7 Pattern 5 template\n\"Profile this dataset\"     → Full Phase 1 + Phase 8 quality score\n```\n\n---\n\n## Related AfrexAI Skills\n\n- `afrexai-data-analyst` — Advanced analytical methodology (DICE framework, statistical analysis)\n- `afrexai-fpa-engine` — Financial planning & analysis with spreadsheet models\n- `afrexai-budget-tracker` — Personal\u002Fbusiness budget management\n- `afrexai-business-automation` — Automate recurring spreadsheet workflows\n\n---\n\n⚡ **Level up your data game** → [AfrexAI Context Packs ($47)](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F) — industry-specific data templates, KPI frameworks, and reporting automations for SaaS, Fintech, Manufacturing, Ecommerce, and more.\n\n🔗 **More free skills by AfrexAI:**\n- `afrexai-data-analyst` — Complete data analysis methodology\n- `afrexai-business-automation` — Workflow automation frameworks\n- `afrexai-seo-content-engine` — SEO-optimized content creation\n- `afrexai-customer-success` — Customer retention & health scoring\n- `afrexai-devops-engine` — DevOps & platform engineering\n\n📦 Browse all: [AfrexAI Storefront](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n",{"name":5,"slug":24,"tags":25,"version":26,"description":7},"afrexai-spreadsheet-master","spreadsheet, excel, csv, data, cleanup, reporting, dashboard, analytics, automation, google-sheets","1.0.0","master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fa\u002Fafrexai-spreadsheet-master",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Spreadsheet & Data Wrangling Master\"",{"tool":42,"command":43},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Spreadsheet & Data Wrangling Master\"",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Spreadsheet & Data Wrangling Master\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fa\u002Fafrexai-spreadsheet-master\u002FSKILL.md",true,[],[51,59,66,73,80,87],{"skillNo":52,"name":53,"nameZh":6,"description":54,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":58},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":58},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":58},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":58},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":58},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":58},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]