# 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 = "Adinda"
VARIANT_ID = "SB-P10" # 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 : Adinda Variant ID : SB-P10
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\MIND From Home\OneDrive\Documents\New folder\File Kuliah Adin\Futuremakers Boothcamp\Bootcamp_Data_Analyst RAW_DIR : C:\Users\MIND From Home\OneDrive\Documents\New folder\File Kuliah Adin\Futuremakers Boothcamp\Bootcamp_Data_Analyst\data\raw\pm1_swiftbite PROCESSED_DIR : C:\Users\MIND From Home\OneDrive\Documents\New folder\File Kuliah Adin\Futuremakers Boothcamp\Bootcamp_Data_Analyst\data\processed\pm1_swiftbite OUTPUT_DIR : C:\Users\MIND From Home\OneDrive\Documents\New folder\File Kuliah Adin\Futuremakers Boothcamp\Bootcamp_Data_Analyst\outputs\pm1_swiftbite DOCS_DIR : C:\Users\MIND From Home\OneDrive\Documents\New folder\File Kuliah Adin\Futuremakers Boothcamp\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.2 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\MIND From Home\OneDrive\Documents\New... |
| 1 | orders | swiftbite_orders.xlsx | True | C:\Users\MIND From Home\OneDrive\Documents\New... |
| 2 | order_items | swiftbite_order_items.csv | True | C:\Users\MIND From Home\OneDrive\Documents\New... |
| 3 | payments | swiftbite_payments.txt | True | C:\Users\MIND From Home\OneDrive\Documents\New... |
| 4 | restaurants | swiftbite_restaurants.csv | True | C:\Users\MIND From Home\OneDrive\Documents\New... |
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=(163, 7) ===
| customer_id | full_name | phone_number | signup_date | customer_zone | customer_segment | ||
|---|---|---|---|---|---|---|---|
| 0 | C0001 | Tio Saputra | tiosaputra1@example.com | 083179415500 | 2025-12-04 | South | Regular |
| 1 | C0002 | Bima Nugroho | bimanugroho2@example.com | 082595271797 | 2025-07-24 | West | New |
| 2 | C0003 | Eka Sari | ekasari3@example.com | 082501922935 | 2025-11-28 | North | Regular |
=== Orders | shape=(328, 10) ===
| order_id | customer_id | restaurant_id | order_timestamp | order_status | promo_code | subtotal_amount | delivery_fee | discount_amount | total_amount | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | O00001 | C0096 | R0010 | 2026-02-28 05:06:00 | completed | NEWUSER | 119000 | 15000 | 10000 | 124000 |
| 1 | O00002 | C0103 | R0015 | 2026-01-13 22:33:00 | completed | NEWUSER | 158000 | 12000 | 0 | 170000 |
| 2 | O00003 | C0110 | R0020 | 2026-03-28 06:34:00 | completed | NaN | 123000 | 18000 | 5000 | 136000 |
=== Order Items | shape=(801, 9) ===
| order_item_id | order_id | line_number | item_name | item_category | quantity | unit_price | line_discount | line_amount | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | OI00001 | O00001 | 1 | Mie Special | Main | 1 | 26000 | 2000 | 24000 |
| 1 | OI00002 | O00001 | 2 | Ice Cream | Dessert | 2 | 20000 | 5000 | 35000 |
| 2 | OI00003 | O00001 | 3 | Juice | Drink | 3 | 20000 | 0 | 60000 |
=== Payments | shape=(384, 7) ===
| payment_id | order_id | payment_method | payment_status | payment_amount | payment_timestamp | attempt_number | |
|---|---|---|---|---|---|---|---|
| 0 | P00001 | O00001 | e_wallet | successful | 124000 | 2026-02-28 05:09:00 | 1 |
| 1 | P00002 | O00002 | bank_transfer | successful | 170000 | 2026-01-13 22:36:00 | 1 |
| 2 | P00003 | O00003 | credit_card | successful | 136000 | 2026-03-28 06:37:00 | 1 |
=== Restaurants | shape=(23, 7) ===
| restaurant_id | restaurant_name | cuisine_type | restaurant_zone | price_tier | onboarding_date | active_status | |
|---|---|---|---|---|---|---|---|
| 0 | R0001 | SwiftBite Partner 01 | Dessert | East | Mid | 2024-11-28 | active |
| 1 | R0002 | SwiftBite Partner 02 | Indonesian | West | Budget | 2024-07-20 | active |
| 2 | R0003 | SwiftBite Partner 03 | Asian | North | Mid | 2024-12-07 | 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 | 163 | 7 | [customer_id, full_name, email, phone_number, ... |
| 1 | Orders | 328 | 10 | [order_id, customer_id, restaurant_id, order_t... |
| 2 | Order Items | 801 | 9 | [order_item_id, order_id, line_number, item_na... |
| 3 | Payments | 384 | 7 | [payment_id, order_id, payment_method, payment... |
| 4 | Restaurants | 23 | 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 | 163 | 162 | 0 | 2 | False |
| 1 | Orders | order_id | 328 | 328 | 0 | 0 | True |
| 2 | Order Items | order_item_id | 801 | 801 | 0 | 0 | True |
| 3 | Order Items — candidate business key | order_id, line_number | 801 | 801 | 0 | 0 | True |
| 4 | Payments | payment_id | 384 | 384 | 0 | 0 | True |
| 5 | Restaurants | restaurant_id | 23 | 23 | 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 | |
|---|---|---|
| 8 | O00009 | 4 |
| 327 | O00328 | 4 |
| 32 | O00033 | 4 |
| 34 | O00035 | 4 |
| 119 | O00120 | 4 |
| 92 | O00093 | 4 |
| 64 | O00065 | 4 |
| 71 | O00072 | 4 |
| 54 | O00055 | 4 |
| 255 | O00256 | 4 |
Payments cardinality
| order_id | payment_rows | |
|---|---|---|
| 22 | O00023 | 2 |
| 21 | O00022 | 2 |
| 20 | O00021 | 2 |
| 8 | O00009 | 2 |
| 327 | O00328 | 2 |
| 324 | O00325 | 2 |
| 323 | O00324 | 2 |
| 322 | O00323 | 2 |
| 321 | O00322 | 2 |
| 320 | O00321 | 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 | 163 | 7 | 2 | 1 | 0 |
| 1 | Orders | 328 | 10 | 0 | 0 | 151 |
| 2 | Order Items | 801 | 9 | 0 | 0 | 0 |
| 3 | Payments | 384 | 7 | 0 | 0 | 0 |
| 4 | Restaurants | 23 | 7 | 0 | 0 | 0 |
# Ganti object untuk memeriksa dataset lain.
if DATA_READY:
display(column_profile(customers_raw))
display(column_profile(orders_raw))
display(column_profile(order_items_raw))
display(column_profile(payments_raw))
display(column_profile(restaurants_raw))
| column | dtype | null_count | null_pct | unique_count | sample_values | |
|---|---|---|---|---|---|---|
| 0 | customer_id | str | 0 | 0.0 | 162 | [C0001, C0002, C0003, C0004, C0005] |
| 1 | full_name | str | 0 | 0.0 | 116 | [Tio Saputra, Bima Nugroho, Eka Sari, Tio Nugr... |
| 2 | str | 0 | 0.0 | 162 | [tiosaputra1@example.com, bimanugroho2@example... | |
| 3 | phone_number | str | 0 | 0.0 | 162 | [083179415500, 082595271797, 082501922935, 081... |
| 4 | signup_date | str | 0 | 0.0 | 122 | [2025-12-04, 2025-07-24, 2025-11-28, 2025-12-2... |
| 5 | customer_zone | str | 0 | 0.0 | 5 | [South, West, North, Central, East] |
| 6 | customer_segment | str | 0 | 0.0 | 5 | [Regular, New, Loyal, NEW , LOYAL ] |
| column | dtype | null_count | null_pct | unique_count | sample_values | |
|---|---|---|---|---|---|---|
| 0 | order_id | str | 0 | 0.0000 | 328 | [O00001, O00002, O00003, O00004, O00005] |
| 1 | customer_id | str | 0 | 0.0000 | 162 | [C0096, C0103, C0110, C0117, C0124] |
| 2 | restaurant_id | str | 0 | 0.0000 | 23 | [R0010, R0015, R0020, R0002, R0007] |
| 3 | order_timestamp | str | 0 | 0.0000 | 327 | [2026-02-28 05:06:00, 2026-01-13 22:33:00, 202... |
| 4 | order_status | str | 0 | 0.0000 | 3 | [completed, COMPLETED , cancelled] |
| 5 | promo_code | str | 151 | 0.4604 | 3 | [NEWUSER, HEMAT15, SAVE10] |
| 6 | subtotal_amount | int64 | 0 | 0.0000 | 160 | [119000, 158000, 123000, 80000, 96000] |
| 7 | delivery_fee | int64 | 0 | 0.0000 | 5 | [15000, 12000, 18000, 10000, 8000] |
| 8 | discount_amount | int64 | 0 | 0.0000 | 4 | [10000, 0, 5000, 15000] |
| 9 | total_amount | int64 | 0 | 0.0000 | 161 | [124000, 170000, 136000, 90000, 108000] |
| column | dtype | null_count | null_pct | unique_count | sample_values | |
|---|---|---|---|---|---|---|
| 0 | order_item_id | str | 0 | 0.0 | 801 | [OI00001, OI00002, OI00003, OI00004, OI00005] |
| 1 | order_id | str | 0 | 0.0 | 328 | [O00001, O00002, O00003, O00004, O00005] |
| 2 | line_number | int64 | 0 | 0.0 | 4 | [1, 2, 3, 4] |
| 3 | item_name | str | 0 | 0.0 | 14 | [Mie Special, Ice Cream, Juice, Cake Slice, Ch... |
| 4 | item_category | str | 0 | 0.0 | 6 | [Main, Dessert, Drink, Snack, MAIN ] |
| 5 | quantity | str | 0 | 0.0 | 4 | [1, 2, 3, 2 pcs] |
| 6 | unit_price | int64 | 0 | 0.0 | 11 | [26000, 20000, 24000, 42000, 9000] |
| 7 | line_discount | int64 | 0 | 0.0 | 3 | [2000, 5000, 0] |
| 8 | line_amount | int64 | 0 | 0.0 | 67 | [24000, 35000, 60000, 19000, 126000] |
| column | dtype | null_count | null_pct | unique_count | sample_values | |
|---|---|---|---|---|---|---|
| 0 | payment_id | str | 0 | 0.0 | 384 | [P00001, P00002, P00003, P00004, P00005] |
| 1 | order_id | str | 0 | 0.0 | 328 | [O00001, O00002, O00003, O00004, O00005] |
| 2 | payment_method | str | 0 | 0.0 | 5 | [e_wallet, bank_transfer, credit_card, cash, C... |
| 3 | payment_status | str | 0 | 0.0 | 3 | [successful, failed, refunded] |
| 4 | payment_amount | int64 | 0 | 0.0 | 161 | [124000, 170000, 136000, 90000, 108000] |
| 5 | payment_timestamp | str | 0 | 0.0 | 381 | [2026-02-28 05:09:00, 2026-01-13 22:36:00, 202... |
| 6 | attempt_number | int64 | 0 | 0.0 | 2 | [1, 2] |
| column | dtype | null_count | null_pct | unique_count | sample_values | |
|---|---|---|---|---|---|---|
| 0 | restaurant_id | str | 0 | 0.0 | 23 | [R0001, R0002, R0003, R0004, R0005] |
| 1 | restaurant_name | str | 0 | 0.0 | 23 | [SwiftBite Partner 01, SwiftBite Partner 02, S... |
| 2 | cuisine_type | str | 0 | 0.0 | 6 | [Dessert, Indonesian, Asian, Western, Fast Food] |
| 3 | restaurant_zone | str | 0 | 0.0 | 5 | [East, West, North, South, Central] |
| 4 | price_tier | str | 0 | 0.0 | 4 | [Mid, Budget, BUDGET , Premium] |
| 5 | onboarding_date | str | 0 | 0.0 | 23 | [2024-11-28, 2024-07-20, 2024-12-07, 2024-02-1... |
| 6 | active_status | str | 0 | 0.0 | 2 | [active, inactive] |
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)
display(category_review(customers_raw, "customer_segment"))
display(category_review(orders_raw, "order_status"))
display(category_review(order_items_raw, "item_category"))
display(category_review(payments_raw, "payment_method"))
display(category_review(payments_raw, "payment_status"))
display(category_review(restaurants_raw, "price_tier"))
display(category_review(restaurants_raw, "cuisine_type"))
display(category_review(restaurants_raw, "restaurant_zone"))
display(category_review(restaurants_raw, "active_status"))
| customer_segment | count | pct | |
|---|---|---|---|
| 0 | Regular | 80 | 0.4908 |
| 1 | New | 44 | 0.2699 |
| 2 | Loyal | 37 | 0.2270 |
| 3 | NEW | 1 | 0.0061 |
| 4 | LOYAL | 1 | 0.0061 |
| order_status | count | pct | |
|---|---|---|---|
| 0 | completed | 290 | 0.8841 |
| 1 | cancelled | 36 | 0.1098 |
| 2 | COMPLETED | 2 | 0.0061 |
| item_category | count | pct | |
|---|---|---|---|
| 0 | Main | 334 | 0.4170 |
| 1 | Drink | 241 | 0.3009 |
| 2 | Snack | 128 | 0.1598 |
| 3 | Dessert | 96 | 0.1199 |
| 4 | MAIN | 1 | 0.0012 |
| 5 | DESSERT | 1 | 0.0012 |
| payment_method | count | pct | |
|---|---|---|---|
| 0 | e_wallet | 98 | 0.2552 |
| 1 | cash | 98 | 0.2552 |
| 2 | credit_card | 94 | 0.2448 |
| 3 | bank_transfer | 92 | 0.2396 |
| 4 | CREDIT CARD | 2 | 0.0052 |
| payment_status | count | pct | |
|---|---|---|---|
| 0 | successful | 304 | 0.7917 |
| 1 | failed | 68 | 0.1771 |
| 2 | refunded | 12 | 0.0312 |
| price_tier | count | pct | |
|---|---|---|---|
| 0 | Mid | 11 | 0.4783 |
| 1 | Budget | 5 | 0.2174 |
| 2 | Premium | 5 | 0.2174 |
| 3 | BUDGET | 2 | 0.0870 |
| cuisine_type | count | pct | |
|---|---|---|---|
| 0 | Dessert | 4 | 0.1739 |
| 1 | Indonesian | 4 | 0.1739 |
| 2 | Asian | 4 | 0.1739 |
| 3 | Western | 4 | 0.1739 |
| 4 | Fast Food | 4 | 0.1739 |
| 5 | Cafe & Beverage | 3 | 0.1304 |
| restaurant_zone | count | pct | |
|---|---|---|---|
| 0 | North | 7 | 0.3043 |
| 1 | East | 5 | 0.2174 |
| 2 | West | 5 | 0.2174 |
| 3 | South | 4 | 0.1739 |
| 4 | Central | 2 | 0.0870 |
| active_status | count | pct | |
|---|---|---|---|
| 0 | active | 21 | 0.913 |
| 1 | inactive | 2 | 0.087 |
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
display(numeric_profile(orders_raw))
display(numeric_profile(order_items_raw))
display(numeric_profile(payments_raw))
| count | mean | std | min | 25% | 50% | 75% | max | |
|---|---|---|---|---|---|---|---|---|
| subtotal_amount | 328.0 | 113006.097561 | 60385.256210 | 7000.0 | 69750.0 | 106500.0 | 146000.0 | 600000.0 |
| delivery_fee | 328.0 | 12798.780488 | 3525.668008 | 8000.0 | 10000.0 | 12000.0 | 15000.0 | 18000.0 |
| discount_amount | 328.0 | 5945.121951 | 5762.106573 | 0.0 | 0.0 | 5000.0 | 10000.0 | 15000.0 |
| total_amount | 328.0 | 119859.756098 | 60975.293256 | 11000.0 | 76000.0 | 112500.0 | 152250.0 | 613000.0 |
| count | mean | std | min | 25% | 50% | 75% | max | |
|---|---|---|---|---|---|---|---|---|
| line_number | 801.0 | 1.860175 | 0.866270 | 1.0 | 1.0 | 2.0 | 2.0 | 4.0 |
| unit_price | 801.0 | 24409.488140 | 22032.750846 | 9000.0 | 18000.0 | 22000.0 | 28000.0 | 602000.0 |
| line_discount | 801.0 | 1538.077403 | 1993.454489 | 0.0 | 0.0 | 0.0 | 2000.0 | 5000.0 |
| line_amount | 801.0 | 46264.669164 | 32342.268978 | 4000.0 | 24000.0 | 43000.0 | 61000.0 | 600000.0 |
| count | mean | std | min | 25% | 50% | 75% | max | |
|---|---|---|---|---|---|---|---|---|
| payment_amount | 384.0 | 121252.604167 | 60885.084099 | 11000.0 | 77750.0 | 113000.0 | 155250.0 | 613000.0 |
| attempt_number | 384.0 | 1.145833 | 0.353400 | 1.0 | 1.0 | 1.0 | 1.0 | 2.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
```
# F-01
new_finding = {
"finding_id": "F-01",
"dataset": "Customers",
"field_key": "customer_id",
"finding_evidence": "Terdapat 3 exact full-row duplicate pada customer_id",
"why_it_matters": "Pelanggan yang sama bisa terhitung lebih dari sekali",
"verification_method": "Key uniqueness test & duplicate check",
"verification_evidence_result": "exact_duplicate_extras = 1",
"judgment": "FIX",
"reason_for_judgment": "Exact duplicate, terbukti dengan evidence",
"cleaning_rule_id": "CR-01",
}
findings.loc[len(findings)] = new_finding
# F-02
new_finding = {
"finding_id": "F-02",
"dataset": "Customers",
"field_key": "customer_segment",
"finding_evidence": "Ditemukan varian penulisan huruf kapital (NEW, LOYAL) pada kategori yang sama (New, Loyal)",
"why_it_matters": "Muncul varian kategori tambahan dengan penulisan kapital yang berbeda",
"verification_method": "Category review helper",
"verification_evidence_result": "customer_segment = Regular, New, Loyal, NEW, LOYAL",
"judgment": "STANDARDIZE",
"reason_for_judgment": "Varian penulisan merujuk pada canonical label yang sama dan jelas",
"cleaning_rule_id": "CR-02",
}
findings.loc[len(findings)] = new_finding
# F-03
new_finding = {
"finding_id": "F-03",
"dataset": "Orders",
"field_key": "promo_code",
"finding_evidence": "Terdapat sebanyak 151 baris null",
"why_it_matters": "Nilai null bisa dianggap adanya kesalahan data",
"verification_method": "Null count & column profiling",
"verification_evidence_result": "null_cells = 151",
"judgment": "INVESTIGATE",
"reason_for_judgment": "Evidence yang diberikan tidak mencantumkan nilai apa yang harus diisi",
"cleaning_rule_id": "",
}
findings.loc[len(findings)] = new_finding
# F-04
new_finding = {
"finding_id": "F-04",
"dataset": "Orders",
"field_key": "order_status",
"finding_evidence": "Ditemukan varian penulisan huruf kapital (COMPLETED) pada kategori yang sama (completed)",
"why_it_matters": "Muncul varian kategori tambahan dengan penulisan kapital yang berbeda",
"verification_method": "Category review helper",
"verification_evidence_result": "order_status = completed, cancelled, COMPLETED",
"judgment": "STANDARDIZE",
"reason_for_judgment": "Varian penulisan merujuk pada canonical label yang sama dan jelas",
"cleaning_rule_id": "CR-03",
}
findings.loc[len(findings)] = new_finding
# F-05
new_finding = {
"finding_id": "F-05",
"dataset": "Orders",
"field_key": "total_amount",
"finding_evidence": "Terdapat nilai ekstrem (max 613.000)",
"why_it_matters": "Berpotensi menjadi outlier yang merusak rata-rata",
"verification_method": "Numeric review helper",
"verification_evidence_result": "total_amount max = 613.000",
"judgment": "KEEP",
"reason_for_judgment": "Masih valid secara bisnis",
"cleaning_rule_id": "",
}
findings.loc[len(findings)] = new_finding
# F-06
new_finding = {
"finding_id": "F-06",
"dataset": "Order_Items",
"field_key": "item_category",
"finding_evidence": "Ditemukan varian penulisan huruf kapital (MAIN, DESSERT) pada kategori yang sama (Main, Dessert)",
"why_it_matters": "Muncul varian kategori tambahan dengan penulisan kapital yang berbeda",
"verification_method": "Category review helper",
"verification_evidence_result": "item_category = Main, Drink, Snack, Dessert, MAIN, DESSERT",
"judgment": "STANDARDIZE",
"reason_for_judgment": "Varian penulisan merujuk pada canonical label yang sama dan jelas",
"cleaning_rule_id": "CR-04",
}
findings.loc[len(findings)] = new_finding
# F-07
new_finding = {
"finding_id": "F-07",
"dataset": "Order_Items",
"field_key": "quantity",
"finding_evidence": "Terdapat teks tambahan ' pcs' pada nilai quantity",
"why_it_matters": "Kolom quantity dapat terbaca sebagai string",
"verification_method": "Column profiling & numeric review",
"verification_evidence_result": "quantity = 1, 2, 3, 2 pcs",
"judgment": "FIX",
"reason_for_judgment": "Jika dibiarkan menyebabkan gagalnya perhitungan matematis",
"cleaning_rule_id": "CR-05",
}
findings.loc[len(findings)] = new_finding
# F-08
new_finding = {
"finding_id": "F-08",
"dataset": "Order_Items",
"field_key": "unit_price",
"finding_evidence": "Terdapat nilai ekstrem (max 602.000)",
"why_it_matters": "Berpotensi menjadi outlier yang merusak rata-rata",
"verification_method": "Numeric review helper",
"verification_evidence_result": "total_amount max = 602.000",
"judgment": "KEEP",
"reason_for_judgment": "Masih valid secara bisnis",
"cleaning_rule_id": "",
}
findings.loc[len(findings)] = new_finding
# F-09
new_finding = {
"finding_id": "F-09",
"dataset": "Payments",
"field_key": "payment_method",
"finding_evidence": "Ditemukan varian penulisan huruf kapital tanpa underscore (CREDIT CARD) pada kategori yang sama (credit_card)",
"why_it_matters": "Muncul varian kategori tambahan dengan penulisan kapital dan underscore yang berbeda",
"verification_method": "Category review helper",
"verification_evidence_result": "payment_method = e_wallet, cash, credit_card, bank_transfer, CREDIT CARD",
"judgment": "STANDARDIZE",
"reason_for_judgment": "Varian penulisan merujuk pada canonical label yang sama dan jelas",
"cleaning_rule_id": "CR-06",
}
findings.loc[len(findings)] = new_finding
# F-10
new_finding = {
"finding_id": "F-10",
"dataset": "Payments",
"field_key": "payment_amount",
"finding_evidence": "Terdapat nilai ekstrem (max 613.000)",
"why_it_matters": "Berpotensi menjadi outlier yang merusak rata-rata",
"verification_method": "Numeric review helper",
"verification_evidence_result": "total_amount max = 613.000",
"judgment": "KEEP",
"reason_for_judgment": "Masih valid secara bisnis",
"cleaning_rule_id": "",
}
findings.loc[len(findings)] = new_finding
# F-11
new_finding = {
"finding_id": "F-11",
"dataset": "Restaurants",
"field_key": "price_tier",
"finding_evidence": "Ditemukan varian penulisan huruf kapital (BUDGET) pada kategori yang sama (Budget)",
"why_it_matters": "Muncul varian kategori tambahan dengan penulisan kapital yang berbeda",
"verification_method": "Category review helper",
"verification_evidence_result": "price_tier = Mid, Budget, Premium, BUDGET",
"judgment": "STANDARDIZE",
"reason_for_judgment": "Varian penulisan merujuk pada canonical label yang sama dan jelas",
"cleaning_rule_id": "CR-07",
}
findings.loc[len(findings)] = new_finding
# F-12
new_finding = {
"finding_id": "F-12",
"dataset": "Order_Items",
"field_key": "line_amount",
"finding_evidence": "Ditemukan ketidakcocokan (mismatch) matematis pada perhitungan formula baris, di mana nilai line_amount tidak sesuai dengan hasil perkalian quantity × unit_price - line_discount",
"why_it_matters": "Jika dibiarkan akan menyebabkan kegagalan perhitungan aturan bisnis dan validasi rumus",
"verification_method": "Business-Rule Verification",
"verification_evidence_result": "2 baris mismatch",
"judgment": "FIX",
"reason_for_judgment": "Ketidaksesuaian nilai nominal harus dikoreksi/disesuaikan agar memenuhi aturan bisnis",
"cleaning_rule_id": "CR-08",
}
findings.loc[len(findings)] = new_finding
# F-13
new_finding = {
"finding_id": "F-13",
"dataset": "Orders ↔ Order_Items",
"field_key": "subtotal_amount / line_amount",
"finding_evidence": "Akumulasi total SUM(line_amount) per pesanan tidak sesuai dengan nilai subtotal_amount di tabel Orders",
"why_it_matters": "Menyebabkan kegagalan pada cross-table reconciliation",
"verification_method": "Orders ↔ Order Items Reconciliation",
"verification_evidence_result": "Raw reconciliation mismatch count: 3",
"judgment": "FIX",
"reason_for_judgment": "Inkonsistensi rekapitulasi finansial harus diselaraskan agar laporan valid",
"cleaning_rule_id": "CR-09",
}
findings.loc[len(findings)] = new_finding
display(findings)
| finding_id | dataset | field_key | finding_evidence | why_it_matters | verification_method | verification_evidence_result | judgment | reason_for_judgment | cleaning_rule_id | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | F-01 | Customers | customer_id | Terdapat 3 exact full-row duplicate pada custo... | Pelanggan yang sama bisa terhitung lebih dari ... | Key uniqueness test & duplicate check | exact_duplicate_extras = 1 | FIX | Exact duplicate, terbukti dengan evidence | CR-01 |
| 1 | F-02 | Customers | customer_segment | Ditemukan varian penulisan huruf kapital (NEW,... | Muncul varian kategori tambahan dengan penulis... | Category review helper | customer_segment = Regular, New, Loyal, NEW, L... | STANDARDIZE | Varian penulisan merujuk pada canonical label ... | CR-02 |
| 2 | F-03 | Orders | promo_code | Terdapat sebanyak 151 baris null | Nilai null bisa dianggap adanya kesalahan data | Null count & column profiling | null_cells = 151 | INVESTIGATE | Evidence yang diberikan tidak mencantumkan nil... | |
| 3 | F-04 | Orders | order_status | Ditemukan varian penulisan huruf kapital (COMP... | Muncul varian kategori tambahan dengan penulis... | Category review helper | order_status = completed, cancelled, COMPLETED | STANDARDIZE | Varian penulisan merujuk pada canonical label ... | CR-03 |
| 4 | F-05 | Orders | total_amount | Terdapat nilai ekstrem (max 613.000) | Berpotensi menjadi outlier yang merusak rata-rata | Numeric review helper | total_amount max = 613.000 | KEEP | Masih valid secara bisnis | |
| 5 | F-06 | Order_Items | item_category | Ditemukan varian penulisan huruf kapital (MAIN... | Muncul varian kategori tambahan dengan penulis... | Category review helper | item_category = Main, Drink, Snack, Dessert, M... | STANDARDIZE | Varian penulisan merujuk pada canonical label ... | CR-04 |
| 6 | F-07 | Order_Items | quantity | Terdapat teks tambahan ' pcs' pada nilai quantity | Kolom quantity dapat terbaca sebagai string | Column profiling & numeric review | quantity = 1, 2, 3, 2 pcs | FIX | Jika dibiarkan menyebabkan gagalnya perhitunga... | CR-05 |
| 7 | F-08 | Order_Items | unit_price | Terdapat nilai ekstrem (max 602.000) | Berpotensi menjadi outlier yang merusak rata-rata | Numeric review helper | total_amount max = 602.000 | KEEP | Masih valid secara bisnis | |
| 8 | F-09 | Payments | payment_method | Ditemukan varian penulisan huruf kapital tanpa... | Muncul varian kategori tambahan dengan penulis... | Category review helper | payment_method = e_wallet, cash, credit_card, ... | STANDARDIZE | Varian penulisan merujuk pada canonical label ... | CR-06 |
| 9 | F-10 | Payments | payment_amount | Terdapat nilai ekstrem (max 613.000) | Berpotensi menjadi outlier yang merusak rata-rata | Numeric review helper | total_amount max = 613.000 | KEEP | Masih valid secara bisnis | |
| 10 | F-11 | Restaurants | price_tier | Ditemukan varian penulisan huruf kapital (BUDG... | Muncul varian kategori tambahan dengan penulis... | Category review helper | price_tier = Mid, Budget, Premium, BUDGET | STANDARDIZE | Varian penulisan merujuk pada canonical label ... | CR-07 |
| 11 | F-12 | Order_Items | line_amount | Ditemukan ketidakcocokan (mismatch) matematis ... | Jika dibiarkan akan menyebabkan kegagalan perh... | Business-Rule Verification | 2 baris mismatch | FIX | Ketidaksesuaian nilai nominal harus dikoreksi/... | CR-08 |
| 12 | F-13 | Orders ↔ Order_Items | subtotal_amount / line_amount | Akumulasi total SUM(line_amount) per pesanan t... | Menyebabkan kegagalan pada cross-table reconci... | Orders ↔ Order Items Reconciliation | Raw reconciliation mismatch count: 3 | FIX | Inkonsistensi rekapitulasi finansial harus dis... | CR-09 |
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 | 162 | 0 | [] |
| 1 | Orders → Restaurants | 23 | 0 | [] |
| 2 | Order Items → Orders | 328 | 0 | [] |
| 3 | Payments → Orders | 328 | 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 | 1 | 26000 | 2000 | 24000 | 24000.0 | True |
| 1 | OI00002 | O00001 | 2 | 20000 | 5000 | 35000 | 35000.0 | True |
| 2 | OI00003 | O00001 | 3 | 20000 | 0 | 60000 | 60000.0 | True |
| 3 | OI00004 | O00002 | 1 | 24000 | 5000 | 19000 | 19000.0 | True |
| 4 | OI00005 | O00002 | 3 | 42000 | 0 | 126000 | 126000.0 | True |
| order_id | subtotal_amount | delivery_fee | discount_amount | total_amount | expected_total_amount | order_formula_match | |
|---|---|---|---|---|---|---|---|
| 0 | O00001 | 119000 | 15000 | 10000 | 124000 | 124000 | True |
| 1 | O00002 | 158000 | 12000 | 0 | 170000 | 170000 | True |
| 2 | O00003 | 123000 | 18000 | 5000 | 136000 | 136000 | True |
| 3 | O00004 | 80000 | 10000 | 0 | 90000 | 90000 | True |
| 4 | O00005 | 96000 | 12000 | 0 | 108000 | 108000 | 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 | 119000 | 119000 | 119000 | True |
| 1 | O00002 | 158000 | 158000 | 158000 | True |
| 2 | O00003 | 123000 | 123000 | 123000 | True |
| 3 | O00004 | 80000 | 80000 | 80000 | True |
| 4 | O00005 | 96000 | 96000 | 96000 | 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
```
# CR-01
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-01",
"source_finding_id": "F-01",
"dataset": "Customers",
"trigger_condition": "Terdapat exact full-row duplicate pada customer_id",
"decision": "FIX",
"cleaning_action": "DROP_EXACT_DUPLICATES",
"reason_evidence": "Exact duplicate terbukti dengan evidence",
"implementation_note": "df.drop_duplicates(keep='first')",
"validation_criteria": "Duplicate extras = 0",
"rule_status": "Approved",
}
# CR-02
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-02",
"source_finding_id": "F-02",
"dataset": "Customers",
"trigger_condition": "Kategori pada customer_segment memiliki varian huruf kapital (NEW, LOYAL)",
"decision": "STANDARDIZE",
"cleaning_action": "STANDARDIZE_CATEGORY",
"reason_evidence": "Varian merujuk ke canonical label yang jelas",
"implementation_note": "str.strip().str.capitalize()",
"validation_criteria": "Kategori cutomer_segment hanya Regular, New, dan Loyal",
"rule_status": "Approved",
}
# CR-03
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-03",
"source_finding_id": "F-04",
"dataset": "Orders",
"trigger_condition": "Kategori pada order_status memiliki varian huruf kapital (COMPLETED)",
"decision": "STANDARDIZE",
"cleaning_action": "STANDARDIZE_CATEGORY",
"reason_evidence": "Varian merujuk ke canonical label yang jelas",
"implementation_note": "str.strip().str.lower()",
"validation_criteria": "Kategori order_status hanya completed, cancelled",
"rule_status": "Approved",
}
# CR-04
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-04",
"source_finding_id": "F-06",
"dataset": "Order_Items",
"trigger_condition": "Kategori pada item_category memiliki varian huruf kapital (MAIN, DESSERT)",
"decision": "STANDARDIZE",
"cleaning_action": "STANDARDIZE_CATEGORY",
"reason_evidence": "Varian merujuk ke canonical label yang jelas",
"implementation_note": "str.strip().str.capitalize()",
"validation_criteria": "Kategori item_category hanya Main, Drink, Snack, Dessert",
"rule_status": "Approved",
}
# CR-05
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-05",
"source_finding_id": "F-07",
"dataset": "Order_Items",
"trigger_condition": "Terdapat teks ' pcs' pada kolom quantity",
"decision": "FIX",
"cleaning_action": "STRIP_AND_CONVERT_NUMERIC",
"reason_evidence": "Membersihkan string agar dapat dihitung secara matematis",
"implementation_note": "str.replace(' pcs', '').astype(int)",
"validation_criteria": "Tidak ada string \"pcs\" tersisa",
"rule_status": "Approved",
}
# CR-06
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-06",
"source_finding_id": "F-08",
"dataset": "Payments",
"trigger_condition": "Kategori pada payment_method memiliki varian huruf kapital tanpa underscore (CREDIT CARD)",
"decision": "STANDARDIZE",
"cleaning_action": "STANDARDIZE_CATEGORY",
"reason_evidence": "Varian merujuk ke canonical label yang jelas",
"implementation_note": "str.strip().str.lower().str.replace(' ', '_', regex=False)",
"validation_criteria": "Kategori payment_method hanya e_wallet, cash, credit_card, bank_transfer",
"rule_status": "Approved",
}
# CR-07
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-07",
"source_finding_id": "F-10",
"dataset": "Restaurants",
"trigger_condition": "Kategori pada price_tier memiliki varian huruf kapital (BUDGET)",
"decision": "STANDARDIZE",
"cleaning_action": "STANDARDIZE_CATEGORY",
"reason_evidence": "Varian merujuk ke canonical label yang jelas",
"implementation_note": "str.strip().str.capitalize()",
"validation_criteria": "Kategori price_tier hanya Mid, Budget, Premium",
"rule_status": "Approved",
}
# CR-08
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-08",
"source_finding_id": "F-12",
"dataset": "Order_Items",
"trigger_condition": "Terdapat ketidakcocokan line_amount dengan hasil formula item",
"decision": "FIX",
"cleaning_action": "RECALCULATE_LINE_AMOUNT",
"reason_evidence": "Nilai line_amount yang tidak sesuai dengan rumus harus di perbaiki agar laporan finansial per item akurat",
"implementation_note": "order_items_clean['line_amount'] = order_items_clean['quantity'] * order_items_clean['unit_price'] - order_items_clean['line_discount']",
"validation_criteria": "Formula match V-09 = True",
"rule_status": "Approved",
}
# CR-09
cleaning_rules.loc[len(cleaning_rules)] = {
"rule_id": "CR-09",
"source_finding_id": "F-13",
"dataset": "Orders ↔ Order_Items",
"trigger_condition": "Akumulasi SUM(line_amount) tidak konsisten dengan subtotal_amount di tabel orders",
"decision": "FIX",
"cleaning_action": "ALIGN_SUBTOTAL_WITH_ITEMS",
"reason_evidence": "Jika dibiarkan menyebabkan kerusakan reliabilitas data antar-tabel dan laporan keuangan bisa selisih",
"implementation_note": "item_agg = order_items_clean.groupby('order_id', as_index=False)['line_amount'].sum()\norders_clean = orders_clean.merge(item_agg, on='order_id', how='left')\norders_clean['subtotal_amount'] = orders_clean['line_amount']",
"validation_criteria": "Reconciliation match V-11 = True",
"rule_status": "Approved",
}
display(cleaning_rules)
| rule_id | source_finding_id | dataset | trigger_condition | decision | cleaning_action | reason_evidence | implementation_note | validation_criteria | rule_status | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | CR-01 | F-01 | Customers | Terdapat exact full-row duplicate pada custome... | FIX | DROP_EXACT_DUPLICATES | Exact duplicate terbukti dengan evidence | df.drop_duplicates(keep='first') | Duplicate extras = 0 | Approved |
| 1 | CR-02 | F-02 | Customers | Kategori pada customer_segment memiliki varian... | STANDARDIZE | STANDARDIZE_CATEGORY | Varian merujuk ke canonical label yang jelas | str.strip().str.capitalize() | Kategori cutomer_segment hanya Regular, New, d... | Approved |
| 2 | CR-03 | F-04 | Orders | Kategori pada order_status memiliki varian hur... | STANDARDIZE | STANDARDIZE_CATEGORY | Varian merujuk ke canonical label yang jelas | str.strip().str.lower() | Kategori order_status hanya completed, cancelled | Approved |
| 3 | CR-04 | F-06 | Order_Items | Kategori pada item_category memiliki varian hu... | STANDARDIZE | STANDARDIZE_CATEGORY | Varian merujuk ke canonical label yang jelas | str.strip().str.capitalize() | Kategori item_category hanya Main, Drink, Snac... | Approved |
| 4 | CR-05 | F-07 | Order_Items | Terdapat teks ' pcs' pada kolom quantity | FIX | STRIP_AND_CONVERT_NUMERIC | Membersihkan string agar dapat dihitung secara... | str.replace(' pcs', '').astype(int) | Tidak ada string "pcs" tersisa | Approved |
| 5 | CR-06 | F-08 | Payments | Kategori pada payment_method memiliki varian h... | STANDARDIZE | STANDARDIZE_CATEGORY | Varian merujuk ke canonical label yang jelas | str.strip().str.lower().str.replace(' ', '_', ... | Kategori payment_method hanya e_wallet, cash, ... | Approved |
| 6 | CR-07 | F-10 | Restaurants | Kategori pada price_tier memiliki varian huruf... | STANDARDIZE | STANDARDIZE_CATEGORY | Varian merujuk ke canonical label yang jelas | str.strip().str.capitalize() | Kategori price_tier hanya Mid, Budget, Premium | Approved |
| 7 | CR-08 | F-12 | Order_Items | Terdapat ketidakcocokan line_amount dengan has... | FIX | RECALCULATE_LINE_AMOUNT | Nilai line_amount yang tidak sesuai dengan rum... | order_items_clean['line_amount'] = order_items... | Formula match V-09 = True | Approved |
| 8 | CR-09 | F-13 | Orders ↔ Order_Items | Akumulasi SUM(line_amount) tidak konsisten den... | FIX | ALIGN_SUBTOTAL_WITH_ITEMS | Jika dibiarkan menyebabkan kerusakan reliabili... | item_agg = order_items_clean.groupby('order_id... | Reconciliation match V-11 = True | Approved |
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.")
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
# ============================================================
# CR-01
customers_clean = customers_clean.drop_duplicates(keep='first')
# CR-02
customers_clean['customer_segment'] = customers_clean['customer_segment'].str.strip().str.capitalize()
# CR-03
orders_clean['order_status'] = orders_clean['order_status'].str.strip().str.lower()
# CR-04
order_items_clean['item_category'] = order_items_clean['item_category'].str.strip().str.capitalize()
# CR-05
order_items_clean['quantity'] = pd.to_numeric(
order_items_clean['quantity'].astype(str).str.replace(' pcs', '', regex=False).str.strip(),
errors='coerce'
)
# CR-06
payments_clean['payment_method'] = payments_clean['payment_method'].str.strip().str.lower().str.replace(' ', '_', regex=False)
# CR-07
restaurants_clean['price_tier'] = restaurants_clean['price_tier'].str.strip().str.lower().str.capitalize()
# CR-08
order_items_clean['line_amount'] = (
order_items_clean['quantity'] * order_items_clean['unit_price'] - order_items_clean['line_discount']
)
# CR-09
item_agg = order_items_clean.groupby('order_id', as_index=False)['line_amount'].sum().rename(columns={'line_amount': 'computed_subtotal'})
orders_clean = orders_clean.merge(item_agg, on='order_id', how='left')
orders_clean['subtotal_amount'] = orders_clean['computed_subtotal']
orders_clean.drop(columns=['computed_subtotal'], inplace=True)
orders_clean['total_amount'] = (
orders_clean['subtotal_amount'] + orders_clean['delivery_fee'] - orders_clean['discount_amount']
)
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))
VALIDATION HARNESS READY Required IDs: V-01, V-02, V-03, V-04, V-05, V-06, V-07, V-08, V-09, V-10, V-11, V-12, V-13, V-14, V-15
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
# ========================================================
# V-01: Schema Check
passed_v1 = all(len(df) > 0 for df in clean_tables.values())
record_check(
"V-01", "Schema", "All clean datasets",
"Apakah seluruh required column masih tersedia?",
"Required columns available",
{"status": "checked"},
passed_v1,
)
# V-02: Customers Key Check (Sesuai contoh template)
result_v2 = key_check(customers_clean, "customer_id", "Customers")
passed_v2 = bool(result_v2.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_v2.to_dict("records")[0],
passed_v2,
)
# V-03: Orders Key Check
result_v3 = key_check(orders_clean, "order_id", "Orders")
passed_v3 = bool(result_v3.loc[0, "candidate_key_unique"])
record_check(
"V-03", "Key", "Orders",
"Apakah order_id valid sesuai grain order?",
"No null key; one row per order",
result_v3.to_dict("records")[0],
passed_v3,
)
# V-04: Order Items Key Check
result_v4 = key_check(order_items_clean, "order_item_id", "Order Items")
passed_v4 = bool(result_v4.loc[0, "candidate_key_unique"])
record_check(
"V-04", "Key", "Order Items",
"Apakah order_item_id / candidate business key valid?",
"No invalid duplicate key",
result_v4.to_dict("records")[0],
passed_v4,
)
# V-05: Payments Key Check
result_v5 = key_check(payments_clean, "payment_id", "Payments")
passed_v5 = bool(result_v5.loc[0, "candidate_key_unique"])
record_check(
"V-05", "Key", "Payments",
"Apakah payment_id unique tanpa menghapus repeated order_id yang valid?",
"payment_id unique; repeated order_id allowed by grain",
result_v5.to_dict("records")[0],
passed_v5,
)
Clean dataset shapes: Customers (162, 7) Orders (328, 10) Order Items (801, 9) Payments (384, 7) Restaurants (23, 7)
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
# ========================================================
# V-06
v6_passed = bool(customers_clean['customer_segment'].isin(['Regular', 'New', 'Loyal']).all())
record_check(
"V-06", "Value", "Customers / categories",
"Apakah category dan missing representation sudah konsisten?",
"No unexpected canonical-category issue",
{"canonical_categories_only": v6_passed, "unique_segments": customers_clean['customer_segment'].unique().tolist()},
v6_passed,
related_rule_id="CR-02"
)
# V-07
v7_passed = bool(orders_clean['order_status'].isin(['completed', 'cancelled']).all())
record_check(
"V-07", "Value", "Orders / categories",
"Apakah order status dan representation sudah konsisten?",
"Only approved canonical values",
{"canonical_status_only": v7_passed, "unique_statuses": orders_clean['order_status'].unique().tolist()},
v7_passed,
related_rule_id="CR-03"
)
# V-08
v8_pm = payments_clean['payment_method'].isin(['e_wallet', 'cash', 'credit_card', 'bank_transfer']).all()
v8_pt = restaurants_clean['price_tier'].isin(['Mid', 'Budget', 'Premium']).all()
v8_passed = bool(v8_pm and v8_pt)
record_check(
"V-08", "Value", "Payments / Restaurants",
"Apakah category representation sudah konsisten?",
"Only approved canonical values",
{"payment_method_valid": bool(v8_pm), "price_tier_valid": bool(v8_pt)},
v8_passed,
related_rule_id="CR-05, CR-06"
)
# V-09
v9_calc = (order_items_clean['quantity'] * order_items_clean['unit_price'] - order_items_clean['line_discount'])
v9_passed = bool(np.isclose(v9_calc, order_items_clean['line_amount'], atol=1e-2).all())
record_check(
"V-09", "Business Rule", "Order Items",
"Apakah line_amount memenuhi formula item?",
"quantity × unit_price - line_discount = line_amount",
{"formula_match": v9_passed},
v9_passed,
)
# V-10
v10_calc = (orders_clean['subtotal_amount'] + orders_clean['delivery_fee'] - orders_clean['discount_amount'])
v10_passed = bool(np.isclose(v10_calc, orders_clean['total_amount'], atol=1e-2).all())
record_check(
"V-10", "Business Rule", "Orders",
"Apakah total_amount memenuhi formula order?",
"subtotal + delivery_fee - discount_amount = total_amount",
{"formula_match": v10_passed},
v10_passed,
)
# V-11
item_agg = order_items_clean.groupby('order_id', as_index=False)['line_amount'].sum()
recon_df = orders_clean[['order_id', 'subtotal_amount']].merge(item_agg, on='order_id', how='left')
v11_passed = bool(np.isclose(recon_df['subtotal_amount'], recon_df['line_amount'], atol=1e-2).all())
record_check(
"V-11", "Cross-table", "Orders ↔ Order Items",
"Apakah subtotal order konsisten dengan detail item?",
"SUM(line_amount) = subtotal_amount",
{"reconciliation_match": v11_passed},
v11_passed,
)
# V-12
v12_unmatched = int((~orders_clean['customer_id'].isin(customers_clean['customer_id'])).sum())
v12_passed = bool(v12_unmatched == 0)
record_check(
"V-12", "Cross-table", "Orders ↔ Customers",
"Apakah seluruh customer reference valid?",
"Unmatched customer = 0",
{"unmatched_customer_count": v12_unmatched},
v12_passed,
)
# V-13
v13_unmatched = int((~orders_clean['restaurant_id'].isin(restaurants_clean['restaurant_id'])).sum())
v13_passed = bool(v13_unmatched == 0)
record_check(
"V-13", "Cross-table", "Orders → Restaurants",
"Apakah seluruh restaurant reference valid?",
"Unmatched restaurant = 0",
{"unmatched_restaurant_count": v13_unmatched},
v13_passed,
)
# V-14
v14_items = int((~order_items_clean['order_id'].isin(orders_clean['order_id'])).sum())
v14_payments = int((~payments_clean['order_id'].isin(orders_clean['order_id'])).sum())
v14_passed = bool(v14_items == 0 and v14_payments == 0)
record_check(
"V-14", "Cross-table", "Order Items / Payments → Orders",
"Apakah seluruh order reference valid?",
"Orphan order reference = 0",
{"orphan_items_count": v14_items, "orphan_payments_count": v14_payments},
v14_passed,
)
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
# ============================================================
if DATA_READY:
# Membuktikan bahwa temuan KEEP (outlier nilai ekstrem yang sah, misal max total_amount) tetap dipertahankan
v15_passed = bool(orders_clean['total_amount'].max() == orders_raw['total_amount'].max())
record_check(
"V-15", "Judgment", "KEEP findings",
"Apakah legitimate anomaly yang diputuskan KEEP masih dipertahankan?",
"KEEP findings remain unless new evidence justifies change",
{"max_total_amount_preserved": int(orders_clean['total_amount'].max()), "status": "Preserved"},
v15_passed,
notes="Legitimate extreme values in total_amount (F-05) are preserved as KEEP."
)
else:
print("VALIDATION SKIPPED — DATA READY GATE belum 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")
| check_id | validation_level | dataset_relationship | validation_question | expected_criteria | actual_result_metric | status | related_rule_id | notes | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | V-01 | Schema | All clean datasets | Apakah seluruh required column masih tersedia? | Required columns available | {'status': 'checked'} | PASS | ||
| 1 | V-02 | Key | Customers | Apakah customer_id valid sesuai grain customer? | No null key; uniqueness sesuai grain | {'dataset': 'Customers', 'key_cols': 'customer... | PASS | ||
| 2 | V-03 | Key | Orders | Apakah order_id valid sesuai grain order? | No null key; one row per order | {'dataset': 'Orders', 'key_cols': 'order_id', ... | PASS | ||
| 3 | V-04 | Key | Order Items | Apakah order_item_id / candidate business key ... | No invalid duplicate key | {'dataset': 'Order Items', 'key_cols': 'order_... | PASS | ||
| 4 | V-05 | Key | Payments | Apakah payment_id unique tanpa menghapus repea... | payment_id unique; repeated order_id allowed b... | {'dataset': 'Payments', 'key_cols': 'payment_i... | PASS | ||
| 5 | V-06 | Value | Customers / categories | Apakah category dan missing representation sud... | No unexpected canonical-category issue | {'canonical_categories_only': True, 'unique_se... | PASS | CR-02 | |
| 6 | V-07 | Value | Orders / categories | Apakah order status dan representation sudah k... | Only approved canonical values | {'canonical_status_only': True, 'unique_status... | PASS | CR-03 | |
| 7 | V-08 | Value | Payments / Restaurants | Apakah category representation sudah konsisten? | Only approved canonical values | {'payment_method_valid': True, 'price_tier_val... | PASS | CR-05, CR-06 | |
| 8 | V-09 | Business Rule | Order Items | Apakah line_amount memenuhi formula item? | quantity × unit_price - line_discount = line_a... | {'formula_match': True} | PASS | ||
| 9 | V-10 | Business Rule | Orders | Apakah total_amount memenuhi formula order? | subtotal + delivery_fee - discount_amount = to... | {'formula_match': True} | PASS | ||
| 10 | V-11 | Cross-table | Orders ↔ Order Items | Apakah subtotal order konsisten dengan detail ... | SUM(line_amount) = subtotal_amount | {'reconciliation_match': True} | PASS | ||
| 11 | V-12 | Cross-table | Orders ↔ Customers | Apakah seluruh customer reference valid? | Unmatched customer = 0 | {'unmatched_customer_count': 0} | PASS | ||
| 12 | V-13 | Cross-table | Orders → Restaurants | Apakah seluruh restaurant reference valid? | Unmatched restaurant = 0 | {'unmatched_restaurant_count': 0} | PASS | ||
| 13 | V-14 | Cross-table | Order Items / Payments → Orders | Apakah seluruh order reference valid? | Orphan order reference = 0 | {'orphan_items_count': 0, 'orphan_payments_cou... | PASS | ||
| 14 | V-15 | Judgment | KEEP findings | Apakah legitimate anomaly yang diputuskan KEEP... | KEEP findings remain unless new evidence justi... | {'max_total_amount_preserved': 613000, 'status... | PASS | Legitimate extreme values in total_amount (F-0... |
status PASS 15 Name: count, dtype: int64 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 = "Data yang sudah bersih dinyatakan siap digunakan karena Identity Gate PASS, seluruh validation check V-01 sampai V-15 PASS, dan Raw Integrity PASS."
print(FINAL_JUDGMENT_RATIONALE)
PM1 DATA READINESS GATE: PASS Data yang sudah bersih dinyatakan siap digunakan karena Identity Gate PASS, seluruh validation check V-01 sampai V-15 PASS, dan Raw Integrity PASS.
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()
CLEAN PACKAGE SAVE: PASS Saved to: C:\Users\MIND From Home\OneDrive\Documents\New folder\File Kuliah Adin\Futuremakers Boothcamp\Bootcamp_Data_Analyst\data\processed\pm1_swiftbite
True
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()
EVIDENCE EXPORT: PASS Saved to: C:\Users\MIND From Home\OneDrive\Documents\New folder\File Kuliah Adin\Futuremakers Boothcamp\Bootcamp_Data_Analyst\outputs\pm1_swiftbite
True
### 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
```