# Data Preparation

> Skill: data-preparation

- Skill: `kaito41418-ux/data-preparation` (Agent Skill, multi-file: 18 files)
- Install (CLI): `npx skillmds@latest add kaito41418-ux/data-preparation`
- Raw SKILL.md: https://api.skillmd.com/api/skills/kaito41418-ux/data-preparation/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: kaito41418-ux (https://skillmd.com/u/kaito41418-ux)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/kaito41418-ux/data-preparation

---


# Skill: data-preparation

原始數據清洗與整理，輸出 tidy CSV + 清洗報告 (.docx)，並為下游統計分析 skill 提供適配指引。

## Metadata
- **Description**: 對 CSV / Excel / SQL / Hive 導出的原始數據做全流程清洗：列名規範化、類型智能推斷、缺失值填充、寬長表重塑、時間衍生列、數值變換、類別編碼。前後 profile 對比記錄丟棄行數與變更；末尾自動推斷下游統計 skill 並輸出可直接執行的 CLI。
- **Version**: 1.0.0
- **Entrypoint**: 兩種模式並列 —— `orchestrator.py`（一鍵版）或 Claude 逐個調 `tools/` 內函數
- **Related**（下游 skill）:
  - 假設檢驗：`advanced-data-analytics`
  - 迴歸建模：`regression-analytics`
  - 因素分析：`factor-analysis`
  - 多因子 ANOVA：`factorial-anova`
  - 多變量分析：`multivariate-analysis`
  - 生存分析：`survival-analysis`
  - 時間序列：`time-series-analysis`
  - 文獻檢索：`literature-review`

## 觸發時機

- 「這份 CSV 太亂了，幫我整理成能跑 t-test 的格式」
- 「有一堆缺失值，幫我先處理再做迴歸」
- 「數據是寬表，我需要轉成長表跑 ANOVA」
- 「幫我把日期欄拆成年/月/週」
- 「準備一份能餵給 XX skill 的資料」
- 「數據清洗」/「數據整理」/「數據預處理」/「tidy data」

## 使用模式

### 模式 A：一鍵 orchestrator（快速走完全流程）
```bash
python orchestrator.py --source local --file raw.csv --ops all \
    --output-dir ./outcome-temp/prep \
    --target-schema regression-linear   # 可選，會校驗輸出是否適配下游
```

`--ops` 可用值（逗號分隔或關鍵字）：
- `all`     — profile → clean → impute → 最終 profile（**默認且最常用**）
- `minimal` — 僅 clean + listwise dropna
- 自定義：`profile,clean,impute,reshape,time,transform,encode` 任意組合

### 模式 B：Claude 逐步驟細粒度控制
當用戶需求特殊（如僅想做某一步、或參數需依 profile 結果動態決定），Claude 依 SOP 逐個調 tools：

```python
from tools.data_fetcher import DataFetcher
from tools.profiler import summarize, diff_two
from tools.cleaner import clean_all           # 或分別調 strip / normalize / drop_duplicate ...
from tools.imputer import impute
from tools.word_generator import generate_prep_docx

df = DataFetcher().load(source="local", file_path="raw.csv")
profile_before = summarize(df)

df, clean_log = clean_all(df)
df, impute_log = impute(df, strategy="median")

profile_after = summarize(df)
df.to_csv("cleaned.csv", index=False)

generate_prep_docx(
    output_path="Prep_Report.docx",
    profile_before=profile_before,
    profile_after=profile_after,
    step_logs=[*clean_log, *impute_log],
    source_info={"path": "raw.csv", "backend": "local"},
    downstream_hint={"skill": "regression-analytics", "cli": "python .../orchestrator.py --analysis linear ..."},
)
```

## SOP（Claude 自我遵循）

1. **fetch + 初次 profile**
   ```python
   df = DataFetcher().load(source, file_path=...)
   profile_before = summarize(df)   # 展示給用戶：dtype / missing% / n_unique / stats
   ```

2. **決定操作**
   - 若用戶只說「幫我清洗一下」→ 走 orchestrator `--ops all`
   - 若用戶明確要求某些步驟（「只填缺失值、不做編碼」）→ 逐步驟調
   - 若 profile 顯示極端情況（如某列 100% 缺失、全為常數）→ 主動建議刪除

3. **執行**：按順序調 tools。**每步都要記錄 log**（做了什麼、影響了多少行/列）

4. **二次 profile + 對比**
   ```python
   profile_after = summarize(df)
   diff = diff_two(profile_before, profile_after)
   ```

5. **推斷下游並提示**
   - 從對話中識別下游意圖：
     - 「t-test」/「配對檢驗」/「相關性」 → `advanced-data-analytics`
     - 「線性/logistic 迴歸」 → `regression-analytics`
     - 「因素分析」/「量表」 → `factor-analysis`
     - 「兩因子 ANOVA」/「多因子」 → `factorial-anova`
     - 「PCA」/「聚類」/「MANOVA」 → `multivariate-analysis`
     - 「生存分析」/「Kaplan-Meier」/「Cox」 → `survival-analysis`
     - 「時序」/「ARIMA」/「預測」 → `time-series-analysis`
   - 寫入 `downstream_hint` 傳給 `word_generator`，docx 末尾顯示可直接執行的 CLI

## Output Location

**預設輸出目錄**：`./outcome-temp/`

- `cleaned.csv`：清洗後的 tidy data
- `Prep_Report.docx`：清洗報告（章節：源信息、清洗前 profile、步驟日誌、清洗後 profile、前後對比、下游 CLI 建議）

## Tool Reference

| tool | 主要函數 | 職責 |
|---|---|---|
| `data_fetcher.py` | `DataFetcher().load(source, ...)` | 從 local/sql/hadoop 讀入 |
| `profiler.py` | `summarize(df)` / `diff_two(before, after)` | 列級 profile + 前後 diff |
| `cleaner.py` | `clean_all(df)` / `strip_column_names` / `normalize_column_names` / `drop_duplicate_rows` / `drop_constant_columns` / `coerce_types` | 基礎清洗 |
| `imputer.py` | `impute(df, strategy="median", cols=None)` | 缺失值填充 |
| `reshaper.py` | `wide_to_long` / `long_to_wide` / `split_column` / `merge_columns` / `rename_columns` | 表結構重塑 |
| `time_deriver.py` | `derive_duration` / `derive_event_status` / `expand_date_parts` | 時間衍生列 |
| `transformer.py` | `apply_transform(df, cols, method="zscore")` | 數值變換 |
| `encoder.py` | `one_hot` / `label_encode` | 類別編碼 |
| `word_generator.py` | `generate_prep_docx(...)` | Word 報告匯出 |

## Constraints

- **Tidy data 定義**：每行一個觀測、每列一個變量、每個 cell 一個值
- 列名 normalize 為 snake_case：`"Age Group"` → `"age_group"`
- 類型推斷順序：datetime → numeric（含 "1,234" / "50%" / "$100"）→ bool（true/false/是/否）→ category（低基數 object）
- 缺失值默認策略：數值列 median，object 列 mode
- one-hot 編碼上限：15 個 unique 值；超過拒絕並建議 label encoding 或分箱
- 數值變換 `log` 自動處理零負值（`log(x + 1)`）
- **CSV 輸出會丟失部分 dtype**（datetime / bool 序列化為字串）—— 這是 CSV 格式固有限制。清洗過程 pandas 內部正確 coerce，下游 skill 從 CSV 讀回時會依 `read_csv` 重新推斷；若下游 skill 需要嚴格類型，可傳 `parse_dates=[...]` 或在 Claude 端手動做 `pd.to_datetime`

## Dependencies
- Python 3.10+: `pandas>=2.0 numpy python-docx openpyxl sqlalchemy pyhive`
- 無 R 依賴

## Failure Modes（Claude 遇到時的應對）
- **全列缺失** → 建議直接 drop，不要嘗試 impute
- **類型推斷失敗**（如日期格式極不規則）→ 保留為 object 並在報告中警告；用戶可手動指定 dtype
- **寬長表重塑後仍不是 tidy**（如某個 cell 含 list）→ 建議用戶檢查原始數據，該 skill 不做嵌套結構展開
- **`--target-schema` 校驗失敗** → docx 中列出缺少的欄位契約，並給出補救建議（如「請重塑為長表」）

