{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d17f0d7e",
   "metadata": {},
   "source": [
    "# 03 실전 반도체 공정 데이터 분석 · 3~4. 결측값 처리 · 분산 0 제거\n",
    "\n",
    "- 강의 페이지: `Web/강좌/03_실전_반도체_공정_데이터분석/실전_반도체_공정_데이터분석_강의자료.html` → 목차 **결측값 처리 · 분산 0 제거**\n",
    "- 결측이 많은 열을 지우고 중앙값으로 채운 뒤, 값이 변하지 않는 센서를 제거합니다.\n",
    "- `fab.csv`가 이 노트북과 같은 폴더에 있어야 합니다.\n",
    "- 위에서 아래로 순서대로 실행하세요. 다른 노트북의 변수를 사용하지 않으므로 이 파일만 열어도 실행됩니다."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6e7c519",
   "metadata": {},
   "source": [
    "### 3단계 · 결측값 처리 (적극 모드)\n",
    "- 설명: 결측이 너무 많은 컬럼은 통째로 제거"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43973678",
   "metadata": {},
   "source": [
    "### 준비 · 라이브러리 + 데이터 읽기 (1~2단계)\n",
    "\n",
    "앞 단계 코드를 그대로 모아 한 번에 실행합니다. 출력은 앞 노트북과 같습니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a756b33a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ── 1단계 ──\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.feature_selection import SelectKBest, f_classif   # ⭐ NEW\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc\n",
    "\n",
    "# 그래프 한글 설정 (Mac은 'AppleGothic', Colab·리눅스는 'NanumGothic')\n",
    "plt.rcParams['font.family'] = 'Malgun Gothic'\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "\n",
    "# ── 2단계 ──\n",
    "df = pd.read_csv('fab.csv')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd4f4be3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1️⃣ 컬럼별 결측률 계산\n",
    "miss_pct = (df.isnull().sum() / len(df) * 100).round(2)\n",
    "print(miss_pct.sort_values(ascending=False).head(10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2e15483",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2️⃣ 결측률 50% 초과 컬럼 제거\n",
    "THRESHOLD = 50.0\n",
    "cols_to_drop = miss_pct[miss_pct > THRESHOLD].index.tolist()\n",
    "print(f\"🗑️ 제거할 컬럼: {len(cols_to_drop)}개\")\n",
    "df = df.drop(columns=cols_to_drop)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "792d583d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3️⃣ 남은 결측치는 중앙값으로 채우기 (타겟 제외!)\n",
    "numeric_cols = df.select_dtypes(include='number').columns.tolist()\n",
    "numeric_cols.remove('Pass_Fail')   # ⚠️ 타겟은 절대 채우지 말 것!\n",
    "\n",
    "df[numeric_cols] = df[numeric_cols].fillna(df[numeric_cols].median())\n",
    "print(f\"✅ 결측 처리 완료. 남은 결측: {df.isnull().sum().sum()}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1d15f9d",
   "metadata": {},
   "source": [
    "## 4단계 · 의미 없는 컬럼 제거 NEW"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b22f47c9",
   "metadata": {},
   "source": [
    "### 4단계 · 의미 없는 컬럼 제거 NEW\n",
    "- 설명: 분산이 거의 없는 컬럼을 제거해 학습에 불필요한 변수를 줄입니다.\n",
    "- 수업 메모: 분산이 0인 센서는 학습에 전혀 도움 안 됩니다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "09b38ddb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 분산 = 0 컬럼 + 거의 0인 컬럼 모두 제거\n",
    "variances = df[numeric_cols].var()\n",
    "\n",
    "constant_cols    = variances[variances == 0].index.tolist()\n",
    "near_constant    = variances[(variances > 0) & (variances < 1e-6)].index.tolist()\n",
    "\n",
    "print(f\"분산 0  컬럼: {len(constant_cols)}개\")\n",
    "print(f\"분산 ≈0 컬럼: {len(near_constant)}개\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e522ca95",
   "metadata": {},
   "outputs": [],
   "source": [
    "to_drop_var = constant_cols + near_constant\n",
    "df = df.drop(columns=to_drop_var)\n",
    "numeric_cols = [c for c in numeric_cols if c not in to_drop_var]\n",
    "\n",
    "print(f\"✅ 사용 가능한 센서: {len(numeric_cols)}개\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bed52b7e",
   "metadata": {},
   "source": [
    "## 마무리\n",
    "\n",
    "- 결측률 50% 초과 28개 열 제거 → 중앙값 채우기 → 분산 0·≈0 센서 126개 제거로 **436개 센서**가 남습니다."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
