# Praktik Mandiri 1 — Data Readiness Check & Cleaning Validation
## Participant Starter Notebook — Guided Technical Version
Notebook ini membantu kamu menjalankan workflow PM1 dengan **technical guardrails** agar tidak salah folder, salah source, atau salah export.
**Alur PM1:**
**Setup → Technical Check → Load → Intake → Grain & Key → Profiling → Findings → Verification → Rulebook → Cleaning → Validation → Raw Integrity → Export → Final Gate**
### Sebelum RUN
1. Buka **folder `Bootcamp_Data_Analyst` sebagai workspace** di Antigravity.
2. Simpan notebook ini di folder `notebooks/`.
3. Extract package `SB-Pxx`, lalu letakkan **5 raw files langsung** di `data/raw/pm1_swiftbite/`.
4. Buka `PM1_Data_Readiness_Working_Paper.xlsx` sebagai tempat mencatat decision & evidence.
5. Jalankan notebook **dari atas ke bawah**.
> Jika `TECHNICAL GATE: PASS`, **jangan mengubah path** di notebook.
### Guardrails
- Raw/source **tidak boleh diubah atau ditimpa**.
- Jangan menghapus row hanya karena terlihat aneh.
- Repeated `order_id` belum tentu duplicate.
- Finding belum otomatis menjadi cleaning action.
- Material change harus dapat ditelusuri: **Finding ID → Rule ID → Cleaning Log → Validation Evidence**.
- Notebook membantu sisi teknis. **Judgment, cleaning rule, dan interpretation tetap pekerjaan peserta.**
Ubah hanya **Nama** dan **Variant ID** sesuai package yang kamu terima.
Contoh Variant ID: `SB-P01`, `SB-P12`, `SB-P28`.
# ============================================================
# EDIT AREA 1 — IDENTITAS PESERTA
# ============================================================
PARTICIPANT_NAME = "Talitha"
VARIANT_ID = "SB-P13" # contoh: SB-P01
name_ok = PARTICIPANT_NAME.strip() not in {"", "Isi Nama Kamu"}
variant_ok = (
VARIANT_ID.startswith("SB-P")
and len(VARIANT_ID) == 6
and VARIANT_ID[4:].isdigit()
)
IDENTITY_GATE_PASS = bool(name_ok and variant_ok)
if IDENTITY_GATE_PASS:
print("IDENTITY GATE: PASS")
print("Participant :", PARTICIPANT_NAME)
print("Variant ID :", VARIANT_ID)
else:
print("IDENTITY GATE: FAIL")
print("→ Isi PARTICIPANT_NAME dan VARIANT_ID pada cell ini.")
print("→ Format Variant ID harus seperti SB-P01 atau SB-P28.")
IDENTITY GATE: PASS Participant : Talitha Variant ID : SB-P13
Notebook akan mencari **Workspace Starter yang sama dari Sesi 1** berdasarkan keberadaan folder `data/` dan `notebooks/`.
**Jangan membuat workspace baru. Jangan copy-paste absolute path.**
Jika output menunjukkan `TECHNICAL GATE: PASS`, lanjut ke cell berikutnya tanpa mengubah path.
from pathlib import Path
import json
import hashlib
import pandas as pd
import numpy as np
try:
import duckdb
DUCKDB_AVAILABLE = True
except ImportError:
duckdb = None
DUCKDB_AVAILABLE = False
pd.set_option("display.max_columns", 100)
pd.set_option("display.max_rows", 100)
pd.set_option("display.width", 180)
def find_workspace_root(start=None):
start = Path(start or Path.cwd()).resolve()
for p in [start, *start.parents]:
if (p / "data").is_dir() and (p / "notebooks").is_dir():
return p
return None
WORKSPACE_ROOT = find_workspace_root()
if WORKSPACE_ROOT is None:
TECHNICAL_GATE_PASS = False
RAW_DIR = Path("__WORKSPACE_NOT_FOUND__")
PROCESSED_DIR = Path("__WORKSPACE_NOT_FOUND__")
OUTPUT_DIR = Path("__WORKSPACE_NOT_FOUND__")
DOCS_DIR = Path("__WORKSPACE_NOT_FOUND__")
print("TECHNICAL GATE: FAIL")
print("→ Workspace Starter tidak ditemukan.")
print("→ Di Antigravity, buka folder Bootcamp_Data_Analyst sebagai workspace.")
print("→ Pastikan folder data/ dan notebooks/ terlihat di Explorer.")
print("→ Setelah itu RUN ulang cell ini. Jangan edit path secara manual.")
else:
TECHNICAL_GATE_PASS = True
RAW_DIR = WORKSPACE_ROOT / "data" / "raw" / "pm1_swiftbite"
PROCESSED_DIR = WORKSPACE_ROOT / "data" / "processed" / "pm1_swiftbite"
OUTPUT_DIR = WORKSPACE_ROOT / "outputs" / "pm1_swiftbite"
DOCS_DIR = WORKSPACE_ROOT / "docs" / "pm1_swiftbite"
for folder in [PROCESSED_DIR, OUTPUT_DIR, DOCS_DIR]:
folder.mkdir(parents=True, exist_ok=True)
print("TECHNICAL GATE: PASS")
print("WORKSPACE_ROOT :", WORKSPACE_ROOT)
print("RAW_DIR :", RAW_DIR)
print("PROCESSED_DIR :", PROCESSED_DIR)
print("OUTPUT_DIR :", OUTPUT_DIR)
print("DOCS_DIR :", DOCS_DIR)
TECHNICAL GATE: PASS WORKSPACE_ROOT : C:\Users\talit\Downloads\Bootcamp_Data_Analyst_Workspace_Starter\Bootcamp_Data_Analyst RAW_DIR : C:\Users\talit\Downloads\Bootcamp_Data_Analyst_Workspace_Starter\Bootcamp_Data_Analyst\data\raw\pm1_swiftbite PROCESSED_DIR : C:\Users\talit\Downloads\Bootcamp_Data_Analyst_Workspace_Starter\Bootcamp_Data_Analyst\data\processed\pm1_swiftbite OUTPUT_DIR : C:\Users\talit\Downloads\Bootcamp_Data_Analyst_Workspace_Starter\Bootcamp_Data_Analyst\outputs\pm1_swiftbite DOCS_DIR : C:\Users\talit\Downloads\Bootcamp_Data_Analyst_Workspace_Starter\Bootcamp_Data_Analyst\docs\pm1_swiftbite
Tujuan cell ini hanya memastikan library utama tersedia. Jika DuckDB belum aktif, workflow utama starter tetap dapat berjalan dengan pandas.
print("pandas :", pd.__version__)
try:
import openpyxl
EXCEL_ENGINE_AVAILABLE = True
print("openpyxl:", openpyxl.__version__)
except ImportError:
EXCEL_ENGINE_AVAILABLE = False
print("openpyxl: NOT AVAILABLE")
if DUCKDB_AVAILABLE:
print("DuckDB :", duckdb.__version__)
try:
con = duckdb.connect()
print("DuckDB connection: OK")
except Exception as e:
print("DuckDB connection: WARNING —", type(e).__name__, str(e))
else:
print("DuckDB : NOT AVAILABLE")
print("INFO: workflow utama notebook tetap dapat dijalankan dengan pandas.")
if not EXCEL_ENGINE_AVAILABLE:
print("ENVIRONMENT CHECK: NEEDS FIX")
print("→ File XLSX membutuhkan openpyxl. Aktifkan environment sesuai setup Sesi 1.")
else:
print("ENVIRONMENT CHECK: PASS")
pandas : 3.0.6 openpyxl: 3.1.5 DuckDB : 1.5.6 DuckDB connection: OK ENVIRONMENT CHECK: PASS
Letakkan **5 file berikut langsung** di:
`data/raw/pm1_swiftbite/`
- `swiftbite_customers.json`
- `swiftbite_orders.xlsx`
- `swiftbite_order_items.csv`
- `swiftbite_payments.txt`
- `swiftbite_restaurants.csv`
**Jangan** meletakkan ZIP di folder tersebut dan **jangan** membuat folder `SB-Pxx` lagi di dalam `pm1_swiftbite/`.
EXPECTED_FILES = {
"customers": "swiftbite_customers.json",
"orders": "swiftbite_orders.xlsx",
"order_items": "swiftbite_order_items.csv",
"payments": "swiftbite_payments.txt",
"restaurants": "swiftbite_restaurants.csv",
}
source_status = []
if not TECHNICAL_GATE_PASS:
missing_files = list(EXPECTED_FILES.values())
SOURCE_ACCESS_PASS = False
print("SOURCE ACCESS CHECK: SKIPPED")
print("→ Perbaiki TECHNICAL GATE terlebih dahulu.")
else:
for logical_name, filename in EXPECTED_FILES.items():
path = RAW_DIR / filename
source_status.append({
"logical_name": logical_name,
"filename": filename,
"exists": path.is_file(),
"path": str(path),
})
source_status_df = pd.DataFrame(source_status)
display(source_status_df)
missing_files = source_status_df.loc[
~source_status_df["exists"], "filename"
].tolist()
SOURCE_ACCESS_PASS = len(missing_files) == 0
if SOURCE_ACCESS_PASS:
print("SOURCE ACCESS CHECK: PASS")
print("→ Semua 5 raw files ditemukan. Jangan ubah path.")
else:
print("SOURCE ACCESS CHECK: FAIL")
print("File belum ditemukan:", missing_files)
print("→ Extract package peserta.")
print("→ Copy hanya 5 raw files langsung ke:", RAW_DIR)
print("→ Jangan menaruh file di subfolder tambahan.")
| logical_name | filename | exists | path | |
|---|---|---|---|---|
| 0 | customers | swiftbite_customers.json | True | C:\Users\talit\Downloads\Bootcamp_Data_Analyst... |
| 1 | orders | swiftbite_orders.xlsx | True | C:\Users\talit\Downloads\Bootcamp_Data_Analyst... |
| 2 | order_items | swiftbite_order_items.csv | True | C:\Users\talit\Downloads\Bootcamp_Data_Analyst... |
| 3 | payments | swiftbite_payments.txt | True | C:\Users\talit\Downloads\Bootcamp_Data_Analyst... |
| 4 | restaurants | swiftbite_restaurants.csv | True | C:\Users\talit\Downloads\Bootcamp_Data_Analyst... |
SOURCE ACCESS CHECK: PASS → Semua 5 raw files ditemukan. Jangan ubah path.
Cell ini:
1. membaca kelima source secara aman,
2. menampilkan error per file jika ada,
3. memeriksa kolom minimum yang diperlukan Starter,
4. menyimpan **raw hash baseline** untuk pemeriksaan integritas di akhir.
Jika `RAW LOAD GATE: PASS` dan `SCHEMA GATE: PASS`, lanjutkan.
REQUIRED_COLUMNS = {
"Customers": {
"customer_id", "full_name", "email", "phone_number",
"signup_date", "customer_zone", "customer_segment"
},
"Orders": {
"order_id", "customer_id", "restaurant_id", "order_timestamp",
"order_status", "subtotal_amount", "delivery_fee",
"discount_amount", "total_amount"
},
"Order Items": {
"order_item_id", "order_id", "line_number", "item_name",
"item_category", "quantity", "unit_price",
"line_discount", "line_amount"
},
"Payments": {
"payment_id", "order_id", "payment_timestamp",
"payment_method", "payment_status", "payment_amount"
},
"Restaurants": {
"restaurant_id", "restaurant_name", "cuisine_type",
"restaurant_zone", "price_tier", "active_status"
},
}
def sha256_file(path: Path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def safe_read_source(label, path, reader):
try:
return reader(path), None
except Exception as e:
return None, f"{type(e).__name__}: {e}"
raw_tables = {}
load_errors = {}
RAW_HASH_BASELINE = {}
if not SOURCE_ACCESS_PASS:
RAW_LOAD_GATE_PASS = False
SCHEMA_GATE_PASS = False
DATA_READY = False
print("RAW LOAD GATE: SKIPPED")
print("→ Perbaiki SOURCE ACCESS CHECK terlebih dahulu.")
else:
readers = {
"Customers": lambda p: pd.read_json(p),
"Orders": lambda p: pd.read_excel(p),
"Order Items": lambda p: pd.read_csv(p),
"Payments": lambda p: pd.read_csv(p, sep="|"),
"Restaurants": lambda p: pd.read_csv(p),
}
file_map = {
"Customers": RAW_DIR / EXPECTED_FILES["customers"],
"Orders": RAW_DIR / EXPECTED_FILES["orders"],
"Order Items": RAW_DIR / EXPECTED_FILES["order_items"],
"Payments": RAW_DIR / EXPECTED_FILES["payments"],
"Restaurants": RAW_DIR / EXPECTED_FILES["restaurants"],
}
for label, path in file_map.items():
df, err = safe_read_source(label, path, readers[label])
if err:
load_errors[label] = err
else:
raw_tables[label] = df
RAW_HASH_BASELINE[label] = sha256_file(path)
RAW_LOAD_GATE_PASS = len(load_errors) == 0 and len(raw_tables) == 5
if RAW_LOAD_GATE_PASS:
customers_raw = raw_tables["Customers"]
orders_raw = raw_tables["Orders"]
order_items_raw = raw_tables["Order Items"]
payments_raw = raw_tables["Payments"]
restaurants_raw = raw_tables["Restaurants"]
print("RAW LOAD GATE: PASS")
else:
print("RAW LOAD GATE: FAIL")
for label, err in load_errors.items():
print(f"→ {label}: {err}")
schema_rows = []
if RAW_LOAD_GATE_PASS:
for label, required in REQUIRED_COLUMNS.items():
actual = set(raw_tables[label].columns)
missing_cols = sorted(required - actual)
schema_rows.append({
"dataset": label,
"required_columns": len(required),
"actual_columns": len(actual),
"missing_required_columns": ", ".join(missing_cols) if missing_cols else "",
"status": "PASS" if not missing_cols else "FAIL",
})
schema_check_df = pd.DataFrame(schema_rows)
display(schema_check_df)
SCHEMA_GATE_PASS = (schema_check_df["status"] == "PASS").all()
if SCHEMA_GATE_PASS:
print("SCHEMA GATE: PASS")
else:
print("SCHEMA GATE: FAIL")
print("→ Jangan lanjut cleaning. Periksa apakah package/variant yang digunakan sudah benar.")
else:
SCHEMA_GATE_PASS = False
DATA_READY = bool(
TECHNICAL_GATE_PASS
and SOURCE_ACCESS_PASS
and RAW_LOAD_GATE_PASS
and SCHEMA_GATE_PASS
)
if DATA_READY:
print("DATA READY GATE: PASS")
else:
print("DATA READY GATE: FAIL")
RAW LOAD GATE: PASS
| dataset | required_columns | actual_columns | missing_required_columns | status | |
|---|---|---|---|---|---|
| 0 | Customers | 7 | 7 | PASS | |
| 1 | Orders | 9 | 10 | PASS | |
| 2 | Order Items | 9 | 9 | PASS | |
| 3 | Payments | 6 | 7 | PASS | |
| 4 | Restaurants | 6 | 7 | PASS |
SCHEMA GATE: PASS DATA READY GATE: PASS
Pastikan nama kolom dan contoh record masuk akal. Ini **belum** berarti data sudah bersih.
if DATA_READY:
for name, df in raw_tables.items():
print(f"\n=== {name} | shape={df.shape} ===")
display(df.head(3))
else:
print("PREVIEW SKIPPED — DATA READY GATE belum PASS.")
=== Customers | shape=(157, 7) ===
| customer_id | full_name | phone_number | signup_date | customer_zone | customer_segment | ||
|---|---|---|---|---|---|---|---|
| 0 | C0001 | Hana Hidayat | hanahidayat1@example.com | 085478276914 | 2025-06-11 | West | New |
| 1 | C0002 | Galih Utami | galihutami2@example.com | 088659124317 | 2025-06-23 | West | Loyal |
| 2 | C0003 | Maya Sari | mayasari3@example.com | 081934897883 | 2025-06-25 | North | Regular |
=== Orders | shape=(315, 10) ===
| order_id | customer_id | restaurant_id | order_timestamp | order_status | promo_code | subtotal_amount | delivery_fee | discount_amount | total_amount | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | O00001 | C0129 | R0023 | 2026-01-30 09:06:00 | completed | NaN | 77000 | 8000 | 0 | 85000 |
| 1 | O00002 | C0136 | R0002 | 2026-03-18 06:41:00 | completed | NaN | 119000 | 8000 | 10000 | 117000 |
| 2 | O00003 | C0143 | R0007 | 2026-02-01 00:19:00 | completed | NaN | 104000 | 10000 | 5000 | 109000 |
=== Order Items | shape=(812, 9) ===
| order_item_id | order_id | line_number | item_name | item_category | quantity | unit_price | line_discount | line_amount | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | OI00001 | O00001 | 1 | Fries | Snack | 2 | 18000 | 5000 | 31000 |
| 1 | OI00002 | O00001 | 2 | Pudding | Dessert | 3 | 16000 | 2000 | 46000 |
| 2 | OI00003 | O00002 | 1 | Cake Slice | Dessert | 1 | 24000 | 0 | 24000 |
=== Payments | shape=(354, 7) ===
| payment_id | order_id | payment_method | payment_status | payment_amount | payment_timestamp | attempt_number | |
|---|---|---|---|---|---|---|---|
| 0 | P00001 | O00001 | e_wallet | successful | 85000 | 2026-01-30 09:09:00 | 1 |
| 1 | P00002 | O00002 | bank_transfer | successful | 117000 | 2026-03-18 06:44:00 | 1 |
| 2 | P00003 | O00003 | credit_card | successful | 109000 | 2026-02-01 00:22:00 | 1 |
=== Restaurants | shape=(26, 7) ===
| restaurant_id | restaurant_name | cuisine_type | restaurant_zone | price_tier | onboarding_date | active_status | |
|---|---|---|---|---|---|---|---|
| 0 | R0001 | SwiftBite Partner 01 | Western | East | Budget | 2024-09-12 | active |
| 1 | R0002 | SwiftBite Partner 02 | Fast Food | South | Mid | 2024-07-18 | active |
| 2 | R0003 | SwiftBite Partner 03 | Cafe & Beverage | East | Mid | 2024-03-20 | active |
Catat business meaning, expected grain, candidate key, row/record count, access status, dan key test result.
def intake_summary(df, dataset_name):
return {
"dataset": dataset_name,
"rows": len(df),
"columns": len(df.columns),
"column_names": list(df.columns),
}
if DATA_READY:
intake_df = pd.DataFrame([
intake_summary(customers_raw, "Customers"),
intake_summary(orders_raw, "Orders"),
intake_summary(order_items_raw, "Order Items"),
intake_summary(payments_raw, "Payments"),
intake_summary(restaurants_raw, "Restaurants"),
])
display(intake_df)
| dataset | rows | columns | column_names | |
|---|---|---|---|---|
| 0 | Customers | 157 | 7 | [customer_id, full_name, email, phone_number, ... |
| 1 | Orders | 315 | 10 | [order_id, customer_id, restaurant_id, order_t... |
| 2 | Order Items | 812 | 9 | [order_item_id, order_id, line_number, item_na... |
| 3 | Payments | 354 | 7 | [payment_id, order_id, payment_method, payment... |
| 4 | Restaurants | 26 | 7 | [restaurant_id, restaurant_name, cuisine_type,... |
Repeated `order_id` pada **Order Items** atau **Payments** belum tentu duplicate karena grain-nya berbeda dari Orders.
Gunakan hasil check sebagai **evidence awal**, bukan cleaning action otomatis.
def key_check(df, key_cols, dataset_name):
if isinstance(key_cols, str):
key_cols = [key_cols]
missing_key_rows = int(df[key_cols].isna().any(axis=1).sum())
unique_key_count = int(df[key_cols].drop_duplicates().shape[0])
duplicate_key_rows = int(df.duplicated(subset=key_cols, keep=False).sum())
return pd.DataFrame([{
"dataset": dataset_name,
"key_cols": ", ".join(key_cols),
"rows": len(df),
"unique_key_count": unique_key_count,
"missing_key_rows": missing_key_rows,
"duplicate_key_rows": duplicate_key_rows,
"candidate_key_unique": unique_key_count == len(df) and missing_key_rows == 0,
}])
if DATA_READY:
key_results = pd.concat([
key_check(customers_raw, "customer_id", "Customers"),
key_check(orders_raw, "order_id", "Orders"),
key_check(order_items_raw, "order_item_id", "Order Items"),
key_check(order_items_raw, ["order_id", "line_number"], "Order Items — candidate business key"),
key_check(payments_raw, "payment_id", "Payments"),
key_check(restaurants_raw, "restaurant_id", "Restaurants"),
], ignore_index=True)
display(key_results)
| dataset | key_cols | rows | unique_key_count | missing_key_rows | duplicate_key_rows | candidate_key_unique | |
|---|---|---|---|---|---|---|---|
| 0 | Customers | customer_id | 157 | 156 | 0 | 2 | False |
| 1 | Orders | order_id | 315 | 315 | 0 | 0 | True |
| 2 | Order Items | order_item_id | 812 | 812 | 0 | 0 | True |
| 3 | Order Items — candidate business key | order_id, line_number | 812 | 812 | 0 | 0 | True |
| 4 | Payments | payment_id | 354 | 354 | 0 | 0 | True |
| 5 | Restaurants | restaurant_id | 26 | 26 | 0 | 0 | True |
if DATA_READY:
order_item_cardinality = (
order_items_raw.groupby("order_id")
.size()
.rename("item_rows")
.reset_index()
.sort_values("item_rows", ascending=False)
)
payment_cardinality = (
payments_raw.groupby("order_id")
.size()
.rename("payment_rows")
.reset_index()
.sort_values("payment_rows", ascending=False)
)
print("Order Items cardinality")
display(order_item_cardinality.head(10))
print("Payments cardinality")
display(payment_cardinality.head(10))
Order Items cardinality
| order_id | item_rows | |
|---|---|---|
| 107 | O00108 | 4 |
| 42 | O00043 | 4 |
| 181 | O00182 | 4 |
| 178 | O00179 | 4 |
| 297 | O00298 | 4 |
| 65 | O00066 | 4 |
| 221 | O00222 | 4 |
| 222 | O00223 | 4 |
| 294 | O00295 | 4 |
| 37 | O00038 | 4 |
Payments cardinality
| order_id | payment_rows | |
|---|---|---|
| 314 | O00315 | 2 |
| 34 | O00035 | 2 |
| 47 | O00048 | 2 |
| 48 | O00049 | 2 |
| 275 | O00276 | 2 |
| 51 | O00052 | 2 |
| 270 | O00271 | 2 |
| 62 | O00063 | 2 |
| 260 | O00261 | 2 |
| 71 | O00072 | 2 |
Profiling minimal:
- missing / placeholder,
- data type / format,
- category consistency,
- duplicate / key,
- suspicious numeric / formula,
- potential outlier,
- cross-table concern.
Helper berikut menghasilkan evidence awal, bukan automatic judgment.
def basic_profile(df, dataset_name):
return pd.DataFrame([{
"dataset": dataset_name,
"rows": len(df),
"columns": len(df.columns),
"rows_in_exact_duplicate_groups": int(df.duplicated(keep=False).sum()),
"exact_duplicate_extras": int(df.duplicated(keep="first").sum()),
"null_cells": int(df.isna().sum().sum()),
}])
def column_profile(df):
rows = []
for col in df.columns:
s = df[col]
rows.append({
"column": col,
"dtype": str(s.dtype),
"null_count": int(s.isna().sum()),
"null_pct": round(float(s.isna().mean()), 4),
"unique_count": int(s.nunique(dropna=True)),
"sample_values": list(s.dropna().astype(str).unique()[:5]),
})
return pd.DataFrame(rows)
if DATA_READY:
overall_profile = pd.concat(
[basic_profile(df, name) for name, df in raw_tables.items()],
ignore_index=True
)
display(overall_profile)
| dataset | rows | columns | rows_in_exact_duplicate_groups | exact_duplicate_extras | null_cells | |
|---|---|---|---|---|---|---|
| 0 | Customers | 157 | 7 | 2 | 1 | 0 |
| 1 | Orders | 315 | 10 | 0 | 0 | 160 |
| 2 | Order Items | 812 | 9 | 0 | 0 | 0 |
| 3 | Payments | 354 | 7 | 0 | 0 | 0 |
| 4 | Restaurants | 26 | 7 | 0 | 0 | 0 |
print([k for k, v in globals().items() if isinstance(v, pd.DataFrame) and not k.startswith("_")])
['source_status_df', 'df', 'customers_raw', 'orders_raw', 'order_items_raw', 'payments_raw', 'restaurants_raw', 'schema_check_df', 'intake_df', 'key_results', 'order_item_cardinality', 'payment_cardinality', 'overall_profile', 'findings']
orders_raw.isna().sum()[lambda s: s > 0]
promo_code 160 dtype: int64
checks = {
"Orders → Customers": ("customer_id", orders_raw, customers_raw),
"Orders → Restaurants": ("restaurant_id", orders_raw, restaurants_raw),
"Order Items → Orders": ("order_id", order_items_raw, orders_raw),
"Payments → Orders": ("order_id", payments_raw, orders_raw),
}
for name, (key, child, parent) in checks.items():
unmatched = (~child[key].isin(parent[key])).sum()
print(name, "| unmatched:", unmatched)
Orders → Customers | unmatched: 0 Orders → Restaurants | unmatched: 0 Order Items → Orders | unmatched: 0 Payments → Orders | unmatched: 0
# Ganti object untuk memeriksa dataset lain.
if DATA_READY:
display(category_review(customers_raw, "customer_segment"))
| customer_segment | count | pct | |
|---|---|---|---|
| 0 | Regular | 75 | 0.4777 |
| 1 | Loyal | 45 | 0.2866 |
| 2 | New | 35 | 0.2229 |
| 3 | LOYAL | 1 | 0.0064 |
| 4 | REGULAR | 1 | 0.0064 |
# Ganti object untuk memeriksa dataset lain.
if DATA_READY:
display(category_review(payments_raw, "payment_method"))
| payment_method | count | pct | |
|---|---|---|---|
| 0 | bank_transfer | 90 | 0.2542 |
| 1 | cash | 88 | 0.2486 |
| 2 | e_wallet | 87 | 0.2458 |
| 3 | credit_card | 87 | 0.2458 |
| 4 | E WALLET | 1 | 0.0028 |
| 5 | BANK TRANSFER | 1 | 0.0028 |
if DATA_READY:
display(category_review(restaurants_raw, "price_tier"))
| price_tier | count | pct | |
|---|---|---|---|
| 0 | Budget | 11 | 0.4231 |
| 1 | Mid | 10 | 0.3846 |
| 2 | Premium | 5 | 0.1923 |
def category_review(df, column, top_n=30):
out = (
df[column]
.value_counts(dropna=False)
.rename_axis(column)
.reset_index(name="count")
)
out["pct"] = (out["count"] / len(df)).round(4)
return out.head(top_n)
# Contoh:
# display(category_review(customers_raw, "customer_segment"))
# display(category_review(orders_raw, "order_status"))
# display(category_review(payments_raw, "payment_method"))
# display(category_review(restaurants_raw, "price_tier"))
display(category_review(customers_raw, "customer_segment")) display(category_review(orders_raw, "order_status")) display(category_review(payments_raw, "payment_method")) display(category_review(restaurants_raw, "price_tier"))
| customer_segment | count | pct | |
|---|---|---|---|
| 0 | Regular | 75 | 0.4777 |
| 1 | Loyal | 45 | 0.2866 |
| 2 | New | 35 | 0.2229 |
| 3 | LOYAL | 1 | 0.0064 |
| 4 | REGULAR | 1 | 0.0064 |
| order_status | count | pct | |
|---|---|---|---|
| 0 | completed | 288 | 0.9143 |
| 1 | cancelled | 25 | 0.0794 |
| 2 | COMPLETED | 2 | 0.0063 |
| payment_method | count | pct | |
|---|---|---|---|
| 0 | bank_transfer | 90 | 0.2542 |
| 1 | cash | 88 | 0.2486 |
| 2 | e_wallet | 87 | 0.2458 |
| 3 | credit_card | 87 | 0.2458 |
| 4 | E WALLET | 1 | 0.0028 |
| 5 | BANK TRANSFER | 1 | 0.0028 |
| price_tier | count | pct | |
|---|---|---|---|
| 0 | Budget | 11 | 0.4231 |
| 1 | Mid | 10 | 0.3846 |
| 2 | Premium | 5 | 0.1923 |
def numeric_profile(df):
numeric_cols = df.select_dtypes(include="number").columns.tolist()
if not numeric_cols:
return pd.DataFrame()
return df[numeric_cols].describe().T
# Contoh:
# display(numeric_profile(orders_raw))
# display(numeric_profile(order_items_raw))
display(numeric_profile(orders_raw)) display(numeric_profile(order_items_raw))
| count | mean | std | min | 25% | 50% | 75% | max | |
|---|---|---|---|---|---|---|---|---|
| subtotal_amount | 315.0 | 122196.825397 | 106909.119641 | 3000.0 | 74000.0 | 112000.0 | 147500.0 | 1708000.0 |
| delivery_fee | 315.0 | 12733.333333 | 3701.265062 | 8000.0 | 10000.0 | 12000.0 | 15000.0 | 18000.0 |
| discount_amount | 315.0 | 5730.158730 | 5694.466946 | 0.0 | 0.0 | 5000.0 | 10000.0 | 15000.0 |
| total_amount | 315.0 | 129200.000000 | 106944.422735 | 6000.0 | 82000.0 | 118000.0 | 151500.0 | 1713000.0 |
| count | mean | std | min | 25% | 50% | 75% | max | |
|---|---|---|---|---|---|---|---|---|
| line_number | 812.0 | 1.913793 | 0.885536 | 1.0 | 1.0 | 2.0 | 3.0 | 4.0 |
| unit_price | 812.0 | 24395.320197 | 20343.599114 | 8000.0 | 18000.0 | 22000.0 | 28000.0 | 545000.0 |
| line_discount | 812.0 | 1325.123153 | 1876.641899 | 0.0 | 0.0 | 0.0 | 2000.0 | 5000.0 |
| line_amount | 812.0 | 47394.088670 | 62031.711905 | 3000.0 | 23750.0 | 40000.0 | 60000.0 | 1635000.0 |
Gunakan judgment:
- `FIX`
- `STANDARDIZE`
- `KEEP`
- `INVESTIGATE`
Jangan isi judgment sebelum verification evidence cukup.
FINDING_COLUMNS = [
"finding_id",
"dataset",
"field_key",
"finding_evidence",
"why_it_matters",
"verification_method",
"verification_evidence_result",
"judgment",
"reason_for_judgment",
"cleaning_rule_id",
]
findings = pd.DataFrame(columns=FINDING_COLUMNS)
display(findings)
| finding_id | dataset | field_key | finding_evidence | why_it_matters | verification_method | verification_evidence_result | judgment | reason_for_judgment | cleaning_rule_id |
|---|
```python
new_finding = {
"finding_id": "F-01",
"dataset": "...",
"field_key": "...",
"finding_evidence": "...",
"why_it_matters": "...",
"verification_method": "...",
"verification_evidence_result": "...",
"judgment": "FIX / STANDARDIZE / KEEP / INVESTIGATE",
"reason_for_judgment": "...",
"cleaning_rule_id": "CR-01 atau kosong",
}
findings.loc[len(findings)] = new_finding
```
def fk_check(child_df, parent_df, child_key, parent_key, relationship_name):
child_keys = child_df[[child_key]].drop_duplicates()
parent_keys = parent_df[[parent_key]].drop_duplicates()
merged = child_keys.merge(
parent_keys,
left_on=child_key,
right_on=parent_key,
how="left",
indicator=True,
)
unmatched = merged.loc[merged["_merge"] == "left_only", child_key]
return {
"relationship": relationship_name,
"child_distinct_keys": len(child_keys),
"unmatched_count": len(unmatched),
"unmatched_sample": unmatched.head(10).tolist(),
}
if DATA_READY:
relationship_checks = pd.DataFrame([
fk_check(orders_raw, customers_raw, "customer_id", "customer_id", "Orders → Customers"),
fk_check(orders_raw, restaurants_raw, "restaurant_id", "restaurant_id", "Orders → Restaurants"),
fk_check(order_items_raw, orders_raw, "order_id", "order_id", "Order Items → Orders"),
fk_check(payments_raw, orders_raw, "order_id", "order_id", "Payments → Orders"),
])
display(relationship_checks)
| relationship | child_distinct_keys | unmatched_count | unmatched_sample | |
|---|---|---|---|---|
| 0 | Orders → Customers | 156 | 0 | [] |
| 1 | Orders → Restaurants | 26 | 0 | [] |
| 2 | Order Items → Orders | 315 | 0 | [] |
| 3 | Payments → Orders | 315 | 0 | [] |
# 1. Order dengan subtotal terbesar dan itemnya
top = orders_raw.nlargest(3, "subtotal_amount")
display(top)
display(order_items_raw[order_items_raw["order_id"].isin(top["order_id"])])
# 2. Rumus total = subtotal + fee - discount
calc = orders_raw["subtotal_amount"] + orders_raw["delivery_fee"] - orders_raw["discount_amount"]
mismatch = (calc != orders_raw["total_amount"]).sum()
print("total_amount tidak sesuai rumus:", mismatch)
# 3. Rumus line_amount = quantity * unit_price - line_discount (kalau ada kolom quantity)
print(list(order_items_raw.columns))
| order_id | customer_id | restaurant_id | order_timestamp | order_status | promo_code | subtotal_amount | delivery_fee | discount_amount | total_amount | |
|---|---|---|---|---|---|---|---|---|---|---|
| 83 | O00084 | C0086 | R0022 | 2026-02-18 02:23:00 | completed | NEWUSER | 1708000 | 10000 | 5000 | 1713000 |
| 283 | O00284 | C0082 | R0008 | 2026-01-09 11:56:00 | completed | HEMAT15 | 276000 | 18000 | 0 | 294000 |
| 100 | O00101 | C0049 | R0003 | 2026-01-04 07:56:00 | completed | NaN | 274000 | 18000 | 0 | 292000 |
| order_item_id | order_id | line_number | item_name | item_category | quantity | unit_price | line_discount | line_amount | |
|---|---|---|---|---|---|---|---|---|---|
| 204 | OI00205 | O00084 | 1 | Fries | Snack | 2 | 18000 | 0 | 36000 |
| 205 | OI00206 | O00084 | 2 | Chicken Set | Main | 1 | 42000 | 5000 | 37000 |
| 206 | OI00207 | O00084 | 3 | Iced Tea | Drink | 3 | 545000 | 0 | 1635000 |
| 251 | OI00252 | O00101 | 1 | Iced Tea | Drink | 2 | 9000 | 0 | 18000 |
| 252 | OI00253 | O00101 | 2 | Rice Bowl | Main | 3 | 32000 | 0 | 96000 |
| 253 | OI00254 | O00101 | 3 | Mie Special | Main | 3 | 26000 | 0 | 78000 |
| 254 | OI00255 | O00101 | 4 | Chicken Set | Main | 2 | 42000 | 2000 | 82000 |
| 729 | OI00730 | O00284 | 1 | Nasi Ayam | Main | 3 | 28000 | 0 | 84000 |
| 730 | OI00731 | O00284 | 2 | Rice Bowl | Main | 3 | 32000 | 0 | 96000 |
| 731 | OI00732 | O00284 | 3 | Rice Bowl | Main | 3 | 32000 | 0 | 96000 |
total_amount tidak sesuai rumus: 0 ['order_item_id', 'order_id', 'line_number', 'item_name', 'item_category', 'quantity', 'unit_price', 'line_discount', 'line_amount']
for name, df in {"Customers": customers_raw, "Orders": orders_raw, "Order Items": order_items_raw,
"Payments": payments_raw, "Restaurants": restaurants_raw}.items():
print(name)
print(df.dtypes, "\n")
Customers customer_id str full_name str email str phone_number str signup_date str customer_zone str customer_segment str dtype: object Orders order_id str customer_id str restaurant_id str order_timestamp str order_status str promo_code str subtotal_amount int64 delivery_fee int64 discount_amount int64 total_amount int64 dtype: object Order Items order_item_id str order_id str line_number int64 item_name str item_category str quantity str unit_price int64 line_discount int64 line_amount int64 dtype: object Payments payment_id str order_id str payment_method str payment_status str payment_amount int64 payment_timestamp str attempt_number int64 dtype: object Restaurants restaurant_id str restaurant_name str cuisine_type str restaurant_zone str price_tier str onboarding_date str active_status str dtype: object
print(orders_raw.isna().sum()[lambda s: s > 0])
promo_code 160 dtype: int64
for name, df in {"Order Items": order_items_raw, "Payments": payments_raw, "Restaurants": restaurants_raw}.items():
print(name)
print(df.dtypes, "\n")
Order Items order_item_id str order_id str line_number int64 item_name str item_category str quantity str unit_price int64 line_discount int64 line_amount int64 dtype: object Payments payment_id str order_id str payment_method str payment_status str payment_amount int64 payment_timestamp str attempt_number int64 dtype: object Restaurants restaurant_id str restaurant_name str cuisine_type str restaurant_zone str price_tier str onboarding_date str active_status str dtype: object
# 1. Isi kolom quantity
print(order_items_raw["quantity"].value_counts(dropna=False))
# 2. Null promo vs diskon
print(orders_raw.groupby(orders_raw["promo_code"].isna())["discount_amount"].describe())
# 3. Payments: status dan percobaan
print(payments_raw["payment_status"].value_counts(dropna=False))
print(payments_raw["attempt_number"].value_counts())
print(payments_raw["payment_amount"].describe())
# 4. Isi active_status dan kolom Restaurants lengkap
print(restaurants_raw["active_status"].value_counts(dropna=False))
print(list(restaurants_raw.columns))
# 5. Unmatched untuk Bagian D
checks = {
"Orders → Customers": ("customer_id", orders_raw, customers_raw),
"Orders → Restaurants": ("restaurant_id", orders_raw, restaurants_raw),
"Order Items → Orders": ("order_id", order_items_raw, orders_raw),
"Payments → Orders": ("order_id", payments_raw, orders_raw),
}
for name, (key, child, parent) in checks.items():
print(name, "| unmatched:", (~child[key].isin(parent[key])).sum())
quantity
1 279
2 278
3 253
1 pcs 1
3 pcs 1
Name: count, dtype: int64
count mean std min 25% 50% 75% max
promo_code
False 155.0 5806.451613 5852.179940 0.0 0.0 5000.0 10000.0 15000.0
True 160.0 5656.250000 5554.811926 0.0 0.0 5000.0 10000.0 15000.0
payment_status
successful 298
failed 48
refunded 8
Name: count, dtype: int64
attempt_number
1 315
2 39
Name: count, dtype: int64
count 3.540000e+02
mean 1.285169e+05
std 1.026817e+05
min 6.000000e+03
25% 8.100000e+04
50% 1.200000e+05
75% 1.517500e+05
max 1.713000e+06
Name: payment_amount, dtype: float64
active_status
active 24
inactive 2
Name: count, dtype: int64
['restaurant_id', 'restaurant_name', 'cuisine_type', 'restaurant_zone', 'price_tier', 'onboarding_date', 'active_status']
Orders → Customers | unmatched: 0
Orders → Restaurants | unmatched: 0
Order Items → Orders | unmatched: 0
Payments → Orders | unmatched: 0
### Order Items
`line_amount = quantity × unit_price − line_discount`
### Orders
`total_amount = subtotal_amount + delivery_fee − discount_amount`
Cell ini hanya membuat verification view. Tidak melakukan cleaning.
if DATA_READY:
item_verify = order_items_raw.copy()
item_verify["expected_line_amount"] = (
pd.to_numeric(item_verify["quantity"], errors="coerce")
* pd.to_numeric(item_verify["unit_price"], errors="coerce")
- pd.to_numeric(item_verify["line_discount"], errors="coerce")
)
item_verify["line_formula_match"] = (
pd.to_numeric(item_verify["line_amount"], errors="coerce")
== item_verify["expected_line_amount"]
)
display(
item_verify[
["order_item_id", "order_id", "quantity", "unit_price",
"line_discount", "line_amount", "expected_line_amount", "line_formula_match"]
].head()
)
order_verify = orders_raw.copy()
order_verify["expected_total_amount"] = (
pd.to_numeric(order_verify["subtotal_amount"], errors="coerce")
+ pd.to_numeric(order_verify["delivery_fee"], errors="coerce")
- pd.to_numeric(order_verify["discount_amount"], errors="coerce")
)
order_verify["order_formula_match"] = (
pd.to_numeric(order_verify["total_amount"], errors="coerce")
== order_verify["expected_total_amount"]
)
display(
order_verify[
["order_id", "subtotal_amount", "delivery_fee", "discount_amount",
"total_amount", "expected_total_amount", "order_formula_match"]
].head()
)
| order_item_id | order_id | quantity | unit_price | line_discount | line_amount | expected_line_amount | line_formula_match | |
|---|---|---|---|---|---|---|---|---|
| 0 | OI00001 | O00001 | 2 | 18000 | 5000 | 31000 | 31000.0 | True |
| 1 | OI00002 | O00001 | 3 | 16000 | 2000 | 46000 | 46000.0 | True |
| 2 | OI00003 | O00002 | 1 | 24000 | 0 | 24000 | 24000.0 | True |
| 3 | OI00004 | O00002 | 3 | 20000 | 5000 | 55000 | 55000.0 | True |
| 4 | OI00005 | O00002 | 2 | 20000 | 0 | 40000 | 40000.0 | True |
| order_id | subtotal_amount | delivery_fee | discount_amount | total_amount | expected_total_amount | order_formula_match | |
|---|---|---|---|---|---|---|---|
| 0 | O00001 | 77000 | 8000 | 0 | 85000 | 85000 | True |
| 1 | O00002 | 119000 | 8000 | 10000 | 117000 | 117000 | True |
| 2 | O00003 | 104000 | 10000 | 5000 | 109000 | 109000 | True |
| 3 | O00004 | 58000 | 10000 | 5000 | 63000 | 63000 | True |
| 4 | O00005 | 192000 | 8000 | 5000 | 195000 | 195000 | True |
Lakukan reconciliation setelah memahami item-level validity. Jangan langsung mengoreksi Orders jika item detail sendiri belum diverifikasi.
if DATA_READY:
item_amount_numeric = pd.to_numeric(order_items_raw["line_amount"], errors="coerce")
item_agg_raw = (
order_items_raw.assign(_line_amount_numeric=item_amount_numeric)
.groupby("order_id", as_index=False)["_line_amount_numeric"]
.sum(min_count=1)
.rename(columns={"_line_amount_numeric": "sum_line_amount"})
)
order_item_recon_raw = orders_raw[
["order_id", "subtotal_amount"]
].merge(item_agg_raw, on="order_id", how="left")
order_item_recon_raw["subtotal_numeric"] = pd.to_numeric(
order_item_recon_raw["subtotal_amount"], errors="coerce"
)
order_item_recon_raw["reconcile_match"] = (
order_item_recon_raw["subtotal_numeric"]
== order_item_recon_raw["sum_line_amount"]
)
display(order_item_recon_raw.head())
print(
"Raw reconciliation mismatch count:",
int((~order_item_recon_raw["reconcile_match"]).sum())
)
| order_id | subtotal_amount | sum_line_amount | subtotal_numeric | reconcile_match | |
|---|---|---|---|---|---|
| 0 | O00001 | 77000 | 77000 | 77000 | True |
| 1 | O00002 | 119000 | 119000 | 119000 | True |
| 2 | O00003 | 104000 | 104000 | 104000 | True |
| 3 | O00004 | 58000 | 58000 | 58000 | True |
| 4 | O00005 | 192000 | 192000 | 192000 | True |
Raw reconciliation mismatch count: 3
Rulebook dibuat setelah verification dan sebelum coding.
Gunakan hanya `FIX` atau `STANDARDIZE` sebagai cleaning decision. Finding `KEEP` tidak boleh diubah hanya agar data terlihat lebih rapi.
RULE_COLUMNS = [
"rule_id",
"source_finding_id",
"dataset",
"trigger_condition",
"decision",
"cleaning_action",
"reason_evidence",
"implementation_note",
"validation_criteria",
"rule_status",
]
cleaning_rules = pd.DataFrame(columns=RULE_COLUMNS)
display(cleaning_rules)
| rule_id | source_finding_id | dataset | trigger_condition | decision | cleaning_action | reason_evidence | implementation_note | validation_criteria | rule_status |
|---|
```python
new_rule = {
"rule_id": "CR-01",
"source_finding_id": "F-01",
"dataset": "...",
"trigger_condition": "...",
"decision": "FIX / STANDARDIZE",
"cleaning_action": "...",
"reason_evidence": "...",
"implementation_note": "...",
"validation_criteria": "...",
"rule_status": "Approved",
}
cleaning_rules.loc[len(cleaning_rules)] = new_rule
```
if DATA_READY:
customers_clean = customers_raw.copy(deep=True)
orders_clean = orders_raw.copy(deep=True)
order_items_clean = order_items_raw.copy(deep=True)
payments_clean = payments_raw.copy(deep=True)
restaurants_clean = restaurants_raw.copy(deep=True)
print("Working copies created.")
**Edit hanya cell Cleaning Code di bawah ini.**
Aturan:
- implementasikan hanya rule yang sudah kamu setujui di Working Paper;
- gunakan `customers_clean`, `orders_clean`, `order_items_clean`, `payments_clean`, atau `restaurants_clean`;
- jangan pernah overwrite object dengan suffix `_raw`;
- beri komentar `CR-xx` untuk setiap rule;
- setelah implementasi, catat before/after pada Cleaning Log.
Starter sengaja **tidak memberikan affected record ID atau jawaban** agar evidence tetap berasal dari variant kamu.
# ============================================================ # EDIT AREA 2 — APPROVED CLEANING CODE # ============================================================ # Tambahkan code per Rule ID di bawah ini. # # Contoh struktur komentar: # # CR-01 — [judul rule] # # Source Finding: F-xx # # Evidence basis: ... # # Validation criteria: ... # # Gunakan hanya dataframe *_clean. # JANGAN ubah dataframe *_raw. # TODO: implement approved rules here. pass
CLEANING_LOG_COLUMNS = [
"log_id",
"rule_id",
"dataset",
"affected_records_scope",
"action_performed",
"before_evidence",
"after_evidence",
"rows_records_affected",
"result",
"notes",
]
cleaning_log = pd.DataFrame(columns=CLEANING_LOG_COLUMNS)
display(cleaning_log)
| log_id | rule_id | dataset | affected_records_scope | action_performed | before_evidence | after_evidence | rows_records_affected | result | notes |
|---|
Validation harus membuktikan hasil cleaning memenuhi **15 check pada Working Paper**:
`V-01` sampai `V-15`
Starter menyediakan fungsi `record_check()`. Kamu tetap harus menentukan evidence dan hasil check berdasarkan variant kamu.
> `FINAL_GATE` tidak akan PASS jika check wajib belum lengkap.
validation_results = []
REQUIRED_VALIDATION_IDS = [f"V-{i:02d}" for i in range(1, 16)]
def record_check(check_id, level, dataset_relationship, question,
expected_criteria, actual_result, passed,
related_rule_id="", notes=""):
if check_id not in REQUIRED_VALIDATION_IDS:
print(f"WARNING — {check_id} bukan ID validation V-01 s.d. V-15.")
# Jika cell di-run ulang, replace check dengan ID yang sama agar tidak double.
validation_results[:] = [
row for row in validation_results if row["check_id"] != check_id
]
validation_results.append({
"check_id": check_id,
"validation_level": level,
"dataset_relationship": dataset_relationship,
"validation_question": question,
"expected_criteria": expected_criteria,
"actual_result_metric": actual_result,
"status": "PASS" if bool(passed) else "FAIL",
"related_rule_id": related_rule_id,
"notes": notes,
})
print("VALIDATION HARNESS READY")
print("Required IDs:", ", ".join(REQUIRED_VALIDATION_IDS))
Gunakan area ini untuk mencatat check seperti `V-01` sampai `V-05` sesuai Working Paper.
Kamu boleh memakai kembali helper `key_check()` dari bagian sebelumnya. Jangan mengganti nilai menjadi PASS tanpa evidence.
if DATA_READY:
clean_tables = {
"Customers": customers_clean,
"Orders": orders_clean,
"Order Items": order_items_clean,
"Payments": payments_clean,
"Restaurants": restaurants_clean,
}
print("Clean dataset shapes:")
for name, df in clean_tables.items():
print(name, df.shape)
# ========================================================
# EDIT AREA 3A — V-01 s.d. V-05
# ========================================================
# Contoh pola (BUKAN jawaban):
#
# result = key_check(customers_clean, "customer_id", "Customers")
# passed = bool(result.loc[0, "candidate_key_unique"])
# record_check(
# "V-02", "Key", "Customers",
# "Apakah customer_id valid sesuai grain customer?",
# "No null key; uniqueness sesuai grain",
# result.to_dict("records")[0],
# passed,
# )
#
# Tambahkan validation kamu di bawah ini.
pass
else:
print("VALIDATION SKIPPED — DATA READY GATE belum PASS.")
Gunakan area ini untuk `V-06` sampai `V-14` sesuai Working Paper.
Manfaatkan helper yang sudah tersedia seperti `category_review()`, `fk_check()`, dan perhitungan formula. **Hitung ulang dari clean data**, bukan hanya melihat output raw.
if DATA_READY:
# ========================================================
# EDIT AREA 3B — V-06 s.d. V-14
# ========================================================
# TODO:
# - category/value validation
# - Order Items formula validation
# - Orders total formula validation
# - Orders ↔ Order Items reconciliation
# - FK checks pada clean data
#
# Tambahkan record_check(...) untuk setiap validation ID.
pass
else:
print("VALIDATION SKIPPED — DATA READY GATE belum PASS.")
Gunakan `V-15` untuk membuktikan bahwa finding yang kamu putuskan **KEEP** tidak ikut berubah akibat over-cleaning.
Jika kamu memiliki lebih dari satu KEEP finding, gunakan evidence yang cukup di Working Paper lalu rangkum hasilnya ke `V-15`.
# ============================================================ # EDIT AREA 3C — V-15 KEEP PRESERVATION # ============================================================ # TODO: tambahkan evidence V-15 menggunakan record_check(...). pass
validation_df = pd.DataFrame(validation_results)
if validation_df.empty:
print("VALIDATION GATE: PENDING")
print("→ Belum ada validation evidence yang dicatat.")
else:
validation_df = validation_df.sort_values("check_id").reset_index(drop=True)
display(validation_df)
present_ids = set(validation_df["check_id"])
missing_validation_ids = [
x for x in REQUIRED_VALIDATION_IDS if x not in present_ids
]
print(validation_df["status"].value_counts(dropna=False))
if missing_validation_ids:
print("VALIDATION GATE: PENDING")
print("Missing required checks:", ", ".join(missing_validation_ids))
elif (validation_df["status"] == "FAIL").any():
print("VALIDATION GATE: FAIL")
print("→ Review FAIL sebelum finalisasi.")
else:
print("VALIDATION GATE: PASS")
Cell ini membandingkan SHA-256 raw source saat pertama kali di-load dengan file raw saat ini.
Target: **tidak ada raw/source yang berubah**.
RAW_INTEGRITY_PASS = False
raw_integrity_rows = []
if not DATA_READY:
print("RAW INTEGRITY CHECK: SKIPPED")
print("→ DATA READY GATE belum PASS.")
else:
file_map_integrity = {
"Customers": RAW_DIR / EXPECTED_FILES["customers"],
"Orders": RAW_DIR / EXPECTED_FILES["orders"],
"Order Items": RAW_DIR / EXPECTED_FILES["order_items"],
"Payments": RAW_DIR / EXPECTED_FILES["payments"],
"Restaurants": RAW_DIR / EXPECTED_FILES["restaurants"],
}
for label, path in file_map_integrity.items():
current_hash = sha256_file(path)
baseline_hash = RAW_HASH_BASELINE.get(label)
raw_integrity_rows.append({
"dataset": label,
"unchanged": current_hash == baseline_hash,
})
raw_integrity_df = pd.DataFrame(raw_integrity_rows)
display(raw_integrity_df)
RAW_INTEGRITY_PASS = bool(raw_integrity_df["unchanged"].all())
if RAW_INTEGRITY_PASS:
print("RAW INTEGRITY CHECK: PASS")
else:
print("RAW INTEGRITY CHECK: FAIL")
print("→ Raw/source berubah. Kembalikan source asli sebelum finalisasi.")
| dataset | unchanged | |
|---|---|---|
| 0 | Customers | True |
| 1 | Orders | True |
| 2 | Order Items | True |
| 3 | Payments | True |
| 4 | Restaurants | True |
RAW INTEGRITY CHECK: PASS
Final Gate hanya boleh:
- `PASS` jika **IDENTITY PASS + semua V-01 s.d. V-15 PASS + RAW INTEGRITY PASS**;
- `NOT READY` jika ada critical FAIL atau raw source berubah;
- `PENDING` jika validation belum lengkap.
Jangan mengubah nilai `FINAL_GATE` secara manual.
def derive_final_gate(validation_df, raw_integrity_pass, identity_gate_pass):
if not identity_gate_pass:
return "PENDING", ["Identity belum lengkap."]
if validation_df.empty:
return "PENDING", ["Validation evidence masih kosong."]
present_ids = set(validation_df["check_id"])
missing_ids = [x for x in REQUIRED_VALIDATION_IDS if x not in present_ids]
required_rows = validation_df[
validation_df["check_id"].isin(REQUIRED_VALIDATION_IDS)
].copy()
if (required_rows["status"] == "FAIL").any():
failed_ids = required_rows.loc[
required_rows["status"] == "FAIL", "check_id"
].tolist()
return "NOT READY", [f"Validation FAIL: {', '.join(failed_ids)}"]
if not raw_integrity_pass:
return "NOT READY", ["Raw Integrity Check FAIL."]
if missing_ids:
return "PENDING", [f"Validation belum lengkap: {', '.join(missing_ids)}"]
all_pass = (
len(required_rows) == len(REQUIRED_VALIDATION_IDS)
and (required_rows["status"] == "PASS").all()
)
if all_pass:
return "PASS", []
return "PENDING", ["Review validation evidence."]
FINAL_GATE, FINAL_GATE_REASONS = derive_final_gate(
validation_df,
RAW_INTEGRITY_PASS,
IDENTITY_GATE_PASS,
)
print("PM1 DATA READINESS GATE:", FINAL_GATE)
if FINAL_GATE_REASONS:
for reason in FINAL_GATE_REASONS:
print("→", reason)
FINAL_JUDGMENT_RATIONALE = "PASS"
print(FINAL_JUDGMENT_RATIONALE)
Output:
- `customers_clean.csv`
- `orders_clean.csv`
- `order_items_clean.csv`
- `payments_clean.csv`
- `restaurants_clean.csv`
Jika Final Gate belum PASS, export akan **diblok otomatis**.
def export_clean_data():
if FINAL_GATE != "PASS":
print("CLEAN EXPORT BLOCKED")
print("→ FINAL_GATE belum PASS. Selesaikan validation terlebih dahulu.")
return False
customers_clean.to_csv(PROCESSED_DIR / "customers_clean.csv", index=False)
orders_clean.to_csv(PROCESSED_DIR / "orders_clean.csv", index=False)
order_items_clean.to_csv(PROCESSED_DIR / "order_items_clean.csv", index=False)
payments_clean.to_csv(PROCESSED_DIR / "payments_clean.csv", index=False)
restaurants_clean.to_csv(PROCESSED_DIR / "restaurants_clean.csv", index=False)
print("CLEAN PACKAGE SAVE: PASS")
print("Saved to:", PROCESSED_DIR)
return True
# Hapus tanda # pada baris berikut HANYA setelah FINAL_GATE: PASS
# export_clean_data()
Evidence boleh diekspor untuk review, tetapi **clean package final tetap hanya boleh disimpan saat FINAL_GATE: PASS**.
def export_evidence():
findings.to_csv(OUTPUT_DIR / "pm1_findings.csv", index=False)
cleaning_rules.to_csv(OUTPUT_DIR / "pm1_cleaning_rulebook.csv", index=False)
cleaning_log.to_csv(OUTPUT_DIR / "pm1_cleaning_log.csv", index=False)
validation_df.to_csv(OUTPUT_DIR / "pm1_validation_results.csv", index=False)
summary = {
"participant_name": PARTICIPANT_NAME,
"variant_id": VARIANT_ID,
"final_gate": FINAL_GATE,
"final_gate_reasons": FINAL_GATE_REASONS,
"raw_integrity_pass": RAW_INTEGRITY_PASS,
"final_judgment_rationale": FINAL_JUDGMENT_RATIONALE,
}
with open(OUTPUT_DIR / "pm1_readiness_summary.json", "w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
print("EVIDENCE EXPORT: PASS")
print("Saved to:", OUTPUT_DIR)
return True
# Hapus tanda # pada baris berikut setelah evidence sudah diisi:
# export_evidence()
### Technical
- [ ] `IDENTITY GATE: PASS`
- [ ] `TECHNICAL GATE: PASS`
- [ ] `SOURCE ACCESS CHECK: PASS`
- [ ] `RAW LOAD GATE: PASS`
- [ ] `SCHEMA GATE: PASS`
- [ ] `RAW INTEGRITY CHECK: PASS`
### Intake, Profiling & Judgment
- [ ] 5 source berhasil dibaca.
- [ ] Grain dan candidate key sudah diperiksa.
- [ ] Relationship utama sudah diperiksa.
- [ ] Material findings sudah diverifikasi.
- [ ] FIX / STANDARDIZE / KEEP / INVESTIGATE memiliki evidence dan alasan.
- [ ] Finding yang menghasilkan cleaning memiliki Rule ID.
### Cleaning & Validation
- [ ] Rulebook dibuat sebelum implementation.
- [ ] Cleaning hanya dilakukan pada working copy.
- [ ] Cleaning Log lengkap.
- [ ] `V-01` sampai `V-15` sudah dicatat.
- [ ] `PM1 DATA READINESS GATE: PASS`
- [ ] 5 clean CSV berhasil diekspor.
```text
Raw Data
↓
Technical & Source Gate
↓
Understand Grain & Key
↓
Profile → Find → Verify → Judge
↓
Define Cleaning Rule
↓
Clean Working Copy
↓
Validate V-01 ... V-15
↓
Raw Integrity Check
↓
FINAL GATE
↓
Export Clean Package
```