{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7e273b60",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2장 pandas \n",
    "# pandas는 행과 열로 이루어진 2차원의 데이터프레임 구조이다. \n",
    "# pandas의 활용을 위해서는 pandas 패키지의 import가 필요\n",
    "# 일반적으로 pd 약어로 표현한다.\n",
    "# pandas 작업형1,2,3 모두 사용되기 때문에 댜양한 데이터 셋을 활용해서 반복 연습이 필요\n",
    "# 시리즈와 데이터 프레임의 데이터 유형 차이를 알고 있어야 한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d3b7a989",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'C:\\\\Users\\\\MEDIA-CAM2'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pwd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "db1e04b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "489181f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (1) 시리즈(Series)와 데이터 프레임(DataFrame) 생성\n",
    "# 시리즈(Series) 1차원 배열 형태의 구조이다.\n",
    "# 시리즈 = 값(value) + 인덱스(index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "66c9c0f0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    170\n",
      "1    175\n",
      "2    165\n",
      "dtype: int64\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1) 시리즈 정수형 생성\n",
    "# pd.Series(객체)\n",
    "height=pd.Series([170,175,165])\n",
    "print(height)\n",
    "type(height)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "72e28332",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[170 175 165]\n"
     ]
    }
   ],
   "source": [
    "# 시리즈의 value 확인\n",
    "# 시리즈의 변수명.values\n",
    "print(height.values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "1efb4330",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0      male\n",
      "1    female\n",
      "2      male\n",
      "dtype: object\n"
     ]
    }
   ],
   "source": [
    "# 2)시리즈 문자열 생성\n",
    "gender=pd.Series([\"male\",\"female\",\"male\"])\n",
    "print(gender)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c84e7b7d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['male' 'female' 'male']\n"
     ]
    }
   ],
   "source": [
    "# 시리즈의 value 확인\n",
    "print(gender.values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "fc2fe7f3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    70\n",
      "1    75\n",
      "2    65\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "#3)시리즈 정수형 생성\n",
    "weight=pd.Series([70,75,65])\n",
    "print(weight)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c0c230c4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   gender  height  weight\n",
      "0    male     170      70\n",
      "1  female     175      75\n",
      "2    male     165      65\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "pandas.core.frame.DataFrame"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#(2)데이터 프레임 생성\n",
    "# 데이터 프레임을 딕셔너리 형태로 생성, pd.DataFrame({\"컬럼명\":데이터})\n",
    "df=pd.DataFrame({\n",
    "    \"gender\":gender,\n",
    "    \"height\":height,\n",
    "    \"weight\":weight\n",
    "})\n",
    "print(df)\n",
    "type(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "cdac0cb6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(3) csv 파일 읽기/저장\n",
    "# 데이터프레임 변수명=pd.read_csv('경로 포함한 파일명') : csv 파일 읽기\n",
    "# 컬럼명이 없는 경우에 read_csv('경로 포함한 파일명',\n",
    "# header=None, names=['열변수1','열변수2']  ..)\n",
    "# 데이터프레임 변수명.to_csv('수험번호.csv',index=False) : csv 파일 저장\n",
    "# index=False, 인덱스 컬럼은 출력 안함\n",
    "# csv 저장은 작업형 2유형 반드시 사용해야 함"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "a37f1b99",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.frame.DataFrame"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/Data1.csv')\n",
    "type(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "35bb3272-041d-4cbc-bc22-2512b687851e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1925 entries, 0 to 1924\n",
      "Data columns (total 26 columns):\n",
      " #   Column     Non-Null Count  Dtype  \n",
      "---  ------     --------------  -----  \n",
      " 0   Q1         1925 non-null   int64  \n",
      " 1   Q2         1925 non-null   int64  \n",
      " 2   Q3         1925 non-null   int64  \n",
      " 3   Q4         1925 non-null   int64  \n",
      " 4   Q5         1925 non-null   int64  \n",
      " 5   Q6         1925 non-null   int64  \n",
      " 6   Q7         1925 non-null   int64  \n",
      " 7   Q8         1925 non-null   int64  \n",
      " 8   Q9         1925 non-null   int64  \n",
      " 9   Q10        1925 non-null   int64  \n",
      " 10  Q11        1925 non-null   int64  \n",
      " 11  Q12        1925 non-null   int64  \n",
      " 12  Q13        1925 non-null   int64  \n",
      " 13  Q14        1925 non-null   int64  \n",
      " 14  Q15        1925 non-null   int64  \n",
      " 15  Q16        1925 non-null   int64  \n",
      " 16  Q17        1925 non-null   int64  \n",
      " 17  Q18        1925 non-null   int64  \n",
      " 18  Q19        1925 non-null   int64  \n",
      " 19  Q20        1925 non-null   int64  \n",
      " 20  Gender     1925 non-null   int64  \n",
      " 21  EDU        1925 non-null   int64  \n",
      " 22  BF         1925 non-null   float64\n",
      " 23  BM         1925 non-null   float64\n",
      " 24  Happiness  1925 non-null   float64\n",
      " 25  Peace      1925 non-null   float64\n",
      "dtypes: float64(4), int64(22)\n",
      "memory usage: 391.1 KB\n"
     ]
    }
   ],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ce4fccf9-8467-44a7-99d7-442ca06da520",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.6</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1920</th>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>1.8</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1921</th>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>2.4</td>\n",
       "      <td>1.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1922</th>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>4.2</td>\n",
       "      <td>2.2</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1923</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>3.2</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1924</th>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "      <td>3</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1925 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  \\\n",
       "0      4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4   \n",
       "1      4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1   \n",
       "2      4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3   \n",
       "3      5   4   4   4   4   4   4   4   4    4  ...    4    4    4    4   \n",
       "4      4   4   4   4   4   4   4   4   2    4  ...    4    4    4    4   \n",
       "...   ..  ..  ..  ..  ..  ..  ..  ..  ..  ...  ...  ...  ...  ...  ...   \n",
       "1920   2   2   2   1   2   2   2   2   2    2  ...    2    2    2    2   \n",
       "1921   3   2   2   2   3   1   1   1   1    1  ...    4    5    2    2   \n",
       "1922   5   4   4   4   4   2   2   2   2    3  ...    3    4    4    4   \n",
       "1923   4   4   4   2   2   4   2   4   4    3  ...    4    4    3    4   \n",
       "1924   3   3   1   1   2   1   1   1   1    1  ...    4    4    3    2   \n",
       "\n",
       "      Gender  EDU   BF   BM  Happiness  Peace  \n",
       "0          0    1  3.4  3.2        4.0    4.0  \n",
       "1          0    1  4.0  3.4        4.0    2.8  \n",
       "2          0    2  3.6  3.6        3.8    3.8  \n",
       "3          0    1  4.2  4.0        4.0    4.0  \n",
       "4          0    2  4.0  3.6        4.0    4.0  \n",
       "...      ...  ...  ...  ...        ...    ...  \n",
       "1920       1    2  1.8  2.0        2.0    2.0  \n",
       "1921       0    2  2.4  1.0        3.4    3.4  \n",
       "1922       0    2  4.2  2.2        3.4    3.6  \n",
       "1923       1    2  3.2  3.4        3.0    3.8  \n",
       "1924       0    3  2.0  1.0        3.0    3.2  \n",
       "\n",
       "[1925 rows x 26 columns]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_csv('c:/data/.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "b4d8b52d",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.to_csv('result.csv',index=False) # index=False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "2c8de284",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'C:\\\\Users\\\\MEDIA-CAM2'"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pwd # 현재 pc 저장 위치를 확인"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "34904ed7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender  \\\n",
       "0   4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4       0   \n",
       "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1       0   \n",
       "2   4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3       0   \n",
       "\n",
       "   EDU   BF   BM  Happiness  Peace  \n",
       "0    1  3.4  3.2        4.0    4.0  \n",
       "1    1  4.0  3.4        4.0    2.8  \n",
       "2    2  3.6  3.6        3.8    3.8  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_csv('c:/data/001.csv').head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "4d754011",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.to_csv('002.csv') # index=False을 사용하지 않은 경우"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "1da4a099",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Unnamed: 0</th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 27 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Unnamed: 0  Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  ...  Q17  Q18  Q19  Q20  \\\n",
       "0           0   4   4   2   3   4   2   2   4   4  ...    4    4    4    4   \n",
       "1           1   4   4   4   4   4   3   2   4   4  ...    3    4    2    1   \n",
       "2           2   4   4   4   4   2   4   4   4   4  ...    4    4    4    3   \n",
       "\n",
       "   Gender  EDU   BF   BM  Happiness  Peace  \n",
       "0       0    1  3.4  3.2        4.0    4.0  \n",
       "1       0    1  4.0  3.4        4.0    2.8  \n",
       "2       0    2  3.6  3.6        3.8    3.8  \n",
       "\n",
       "[3 rows x 27 columns]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_csv('c:/data/002.csv').head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "cf8168fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(4) 데이터 확인 및 탐색\n",
    "# 작업형 1~3 유형에 모두 사용됨\n",
    "# 데이터 확인 및 탐색에 사용하는 함수의 활용 능력을 검정함\n",
    "# 1) info() 함수는 데이터에 대한 전반적인 정보 제공\n",
    "# 데이터프레임을 구성하는 행과 열의 크기, 컬럼명, \n",
    "# 컬럼을 구성하는 값의 자료형 등을 출력\n",
    "# 데이터프레임 변수명.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "92a62cea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1925 entries, 0 to 1924\n",
      "Data columns (total 26 columns):\n",
      " #   Column     Non-Null Count  Dtype  \n",
      "---  ------     --------------  -----  \n",
      " 0   Q1         1925 non-null   int64  \n",
      " 1   Q2         1925 non-null   int64  \n",
      " 2   Q3         1925 non-null   int64  \n",
      " 3   Q4         1925 non-null   int64  \n",
      " 4   Q5         1925 non-null   int64  \n",
      " 5   Q6         1925 non-null   int64  \n",
      " 6   Q7         1925 non-null   int64  \n",
      " 7   Q8         1925 non-null   int64  \n",
      " 8   Q9         1925 non-null   int64  \n",
      " 9   Q10        1925 non-null   int64  \n",
      " 10  Q11        1925 non-null   int64  \n",
      " 11  Q12        1925 non-null   int64  \n",
      " 12  Q13        1925 non-null   int64  \n",
      " 13  Q14        1925 non-null   int64  \n",
      " 14  Q15        1925 non-null   int64  \n",
      " 15  Q16        1925 non-null   int64  \n",
      " 16  Q17        1925 non-null   int64  \n",
      " 17  Q18        1925 non-null   int64  \n",
      " 18  Q19        1925 non-null   int64  \n",
      " 19  Q20        1925 non-null   int64  \n",
      " 20  Gender1    1925 non-null   int64  \n",
      " 21  EDU1       1925 non-null   int64  \n",
      " 22  BF         1925 non-null   float64\n",
      " 23  BM         1925 non-null   float64\n",
      " 24  Happiness  1925 non-null   float64\n",
      " 25  Peace      1925 non-null   float64\n",
      "dtypes: float64(4), int64(22)\n",
      "memory usage: 391.1 KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/Data1.csv')\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4251977d-9a29-4962-b2fe-5d78627f1e37",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 153 entries, 0 to 152\n",
      "Data columns (total 6 columns):\n",
      " #   Column   Non-Null Count  Dtype  \n",
      "---  ------   --------------  -----  \n",
      " 0   Ozone    116 non-null    float64\n",
      " 1   Solar.R  146 non-null    float64\n",
      " 2   Wind     153 non-null    float64\n",
      " 3   Temp     153 non-null    int64  \n",
      " 4   Month    153 non-null    int64  \n",
      " 5   Day      153 non-null    int64  \n",
      "dtypes: float64(3), int64(3)\n",
      "memory usage: 7.3 KB\n"
     ]
    }
   ],
   "source": [
    "df1=pd.read_csv(\"c:/data/airquality.csv\")\n",
    "df1.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "8666ce38-9dfd-4aad-a67c-63a5dfc5c74f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 891 entries, 0 to 890\n",
      "Data columns (total 12 columns):\n",
      " #   Column       Non-Null Count  Dtype  \n",
      "---  ------       --------------  -----  \n",
      " 0   PassengerId  891 non-null    int64  \n",
      " 1   Survived     891 non-null    int64  \n",
      " 2   Pclass       891 non-null    int64  \n",
      " 3   Name         891 non-null    object \n",
      " 4   Gender       891 non-null    object \n",
      " 5   Age          714 non-null    float64\n",
      " 6   SibSp        891 non-null    int64  \n",
      " 7   Parch        891 non-null    int64  \n",
      " 8   Ticket       891 non-null    object \n",
      " 9   Fare         891 non-null    float64\n",
      " 10  Cabin        204 non-null    object \n",
      " 11  Embarked     889 non-null    object \n",
      "dtypes: float64(2), int64(5), object(5)\n",
      "memory usage: 83.7+ KB\n"
     ]
    }
   ],
   "source": [
    "df2=pd.read_csv('c:/data/titanic.csv')\n",
    "df2.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "08914ca1-4d49-44cc-886e-9d8e0ddb95ee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'C:\\\\Users\\\\emhu8'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pwd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "8bbae958",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10', 'Q11',\n",
       "       'Q12', 'Q13', 'Q14', 'Q15', 'Q16', 'Q17', 'Q18', 'Q19', 'Q20', 'Gender',\n",
       "       'EDU', 'BF', 'BM', 'Happiness', 'Peace'],\n",
       "      dtype='object')"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2) 컬럼명 확인\n",
    "# 데이터프레임 변수명.columns\n",
    "df.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "c5f68c40",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1925, 26)"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 3) 행,열의 크기를 확인\n",
    "# 데이터프레임 변수명.shape\n",
    "df.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "95044a20",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>3.535584</td>\n",
       "      <td>3.291429</td>\n",
       "      <td>2.928312</td>\n",
       "      <td>3.061299</td>\n",
       "      <td>3.041039</td>\n",
       "      <td>2.795844</td>\n",
       "      <td>3.086234</td>\n",
       "      <td>3.048831</td>\n",
       "      <td>3.065974</td>\n",
       "      <td>2.882597</td>\n",
       "      <td>...</td>\n",
       "      <td>3.515844</td>\n",
       "      <td>3.803636</td>\n",
       "      <td>3.363636</td>\n",
       "      <td>3.348571</td>\n",
       "      <td>0.409870</td>\n",
       "      <td>2.615584</td>\n",
       "      <td>3.171584</td>\n",
       "      <td>2.975792</td>\n",
       "      <td>3.547065</td>\n",
       "      <td>3.564260</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.940764</td>\n",
       "      <td>0.938191</td>\n",
       "      <td>1.019077</td>\n",
       "      <td>0.965832</td>\n",
       "      <td>1.018477</td>\n",
       "      <td>1.117515</td>\n",
       "      <td>1.088039</td>\n",
       "      <td>1.091788</td>\n",
       "      <td>1.138218</td>\n",
       "      <td>0.944804</td>\n",
       "      <td>...</td>\n",
       "      <td>1.000719</td>\n",
       "      <td>0.948183</td>\n",
       "      <td>0.911196</td>\n",
       "      <td>0.928613</td>\n",
       "      <td>0.491937</td>\n",
       "      <td>0.827519</td>\n",
       "      <td>0.744109</td>\n",
       "      <td>0.777280</td>\n",
       "      <td>0.748004</td>\n",
       "      <td>0.657075</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.400000</td>\n",
       "      <td>1.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.600000</td>\n",
       "      <td>2.400000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>4.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.200000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.600000</td>\n",
       "      <td>3.600000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.800000</td>\n",
       "      <td>3.600000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>8 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                Q1           Q2           Q3           Q4           Q5  \\\n",
       "count  1925.000000  1925.000000  1925.000000  1925.000000  1925.000000   \n",
       "mean      3.535584     3.291429     2.928312     3.061299     3.041039   \n",
       "std       0.940764     0.938191     1.019077     0.965832     1.018477   \n",
       "min       1.000000     1.000000     1.000000     1.000000     1.000000   \n",
       "25%       3.000000     3.000000     2.000000     2.000000     2.000000   \n",
       "50%       4.000000     3.000000     3.000000     3.000000     3.000000   \n",
       "75%       4.000000     4.000000     4.000000     4.000000     4.000000   \n",
       "max       5.000000     5.000000     5.000000     5.000000     5.000000   \n",
       "\n",
       "                Q6           Q7           Q8           Q9          Q10  ...  \\\n",
       "count  1925.000000  1925.000000  1925.000000  1925.000000  1925.000000  ...   \n",
       "mean      2.795844     3.086234     3.048831     3.065974     2.882597  ...   \n",
       "std       1.117515     1.088039     1.091788     1.138218     0.944804  ...   \n",
       "min       1.000000     1.000000     1.000000     1.000000     1.000000  ...   \n",
       "25%       2.000000     2.000000     2.000000     2.000000     2.000000  ...   \n",
       "50%       3.000000     3.000000     3.000000     3.000000     3.000000  ...   \n",
       "75%       4.000000     4.000000     4.000000     4.000000     4.000000  ...   \n",
       "max       5.000000     5.000000     5.000000     5.000000     5.000000  ...   \n",
       "\n",
       "               Q17          Q18          Q19          Q20      Gender1  \\\n",
       "count  1925.000000  1925.000000  1925.000000  1925.000000  1925.000000   \n",
       "mean      3.515844     3.803636     3.363636     3.348571     0.409870   \n",
       "std       1.000719     0.948183     0.911196     0.928613     0.491937   \n",
       "min       1.000000     1.000000     1.000000     1.000000     0.000000   \n",
       "25%       3.000000     4.000000     3.000000     3.000000     0.000000   \n",
       "50%       4.000000     4.000000     3.000000     3.000000     0.000000   \n",
       "75%       4.000000     4.000000     4.000000     4.000000     1.000000   \n",
       "max       5.000000     5.000000     5.000000     5.000000     1.000000   \n",
       "\n",
       "              EDU1           BF           BM    Happiness        Peace  \n",
       "count  1925.000000  1925.000000  1925.000000  1925.000000  1925.000000  \n",
       "mean      2.615584     3.171584     2.975792     3.547065     3.564260  \n",
       "std       0.827519     0.744109     0.777280     0.748004     0.657075  \n",
       "min       1.000000     1.000000     1.000000     1.400000     1.200000  \n",
       "25%       2.000000     2.600000     2.400000     3.000000     3.200000  \n",
       "50%       3.000000     3.200000     3.000000     3.600000     3.600000  \n",
       "75%       3.000000     3.800000     3.600000     4.000000     4.000000  \n",
       "max       4.000000     5.000000     5.000000     5.000000     5.000000  \n",
       "\n",
       "[8 rows x 26 columns]"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 4) 요약 통계량 확인\n",
    "# 데이터프레임 변수명.describe()\n",
    "df.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "4b830d94-7986-4c08-993e-61919e1bf294",
   "metadata": {},
   "outputs": [],
   "source": [
    "df2=pd.read_csv('c:/data/titanic.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "3b666210-d680-43d4-b678-d30880fe0ad8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 891 entries, 0 to 890\n",
      "Data columns (total 12 columns):\n",
      " #   Column       Non-Null Count  Dtype  \n",
      "---  ------       --------------  -----  \n",
      " 0   PassengerId  891 non-null    int64  \n",
      " 1   Survived     891 non-null    int64  \n",
      " 2   Pclass       891 non-null    int64  \n",
      " 3   Name         891 non-null    object \n",
      " 4   Gender       891 non-null    object \n",
      " 5   Age          714 non-null    float64\n",
      " 6   SibSp        891 non-null    int64  \n",
      " 7   Parch        891 non-null    int64  \n",
      " 8   Ticket       891 non-null    object \n",
      " 9   Fare         891 non-null    float64\n",
      " 10  Cabin        204 non-null    object \n",
      " 11  Embarked     889 non-null    object \n",
      "dtypes: float64(2), int64(5), object(5)\n",
      "memory usage: 83.7+ KB\n"
     ]
    }
   ],
   "source": [
    "df2.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "7ca1d7cb-1fc0-4b70-bfa4-d54acdaa18b7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Name</th>\n",
       "      <th>Gender</th>\n",
       "      <th>Ticket</th>\n",
       "      <th>Cabin</th>\n",
       "      <th>Embarked</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>891</td>\n",
       "      <td>891</td>\n",
       "      <td>891</td>\n",
       "      <td>204</td>\n",
       "      <td>889</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>unique</th>\n",
       "      <td>891</td>\n",
       "      <td>2</td>\n",
       "      <td>681</td>\n",
       "      <td>147</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>top</th>\n",
       "      <td>Braund, Mr. Owen Harris</td>\n",
       "      <td>male</td>\n",
       "      <td>347082</td>\n",
       "      <td>B96 B98</td>\n",
       "      <td>S</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>freq</th>\n",
       "      <td>1</td>\n",
       "      <td>577</td>\n",
       "      <td>7</td>\n",
       "      <td>4</td>\n",
       "      <td>644</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                           Name Gender  Ticket    Cabin Embarked\n",
       "count                       891    891     891      204      889\n",
       "unique                      891      2     681      147        3\n",
       "top     Braund, Mr. Owen Harris   male  347082  B96 B98        S\n",
       "freq                          1    577       7        4      644"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2.describe(include='object')\n",
    "df2.select_dtypes(include='number')  # 수치형 자료만 모아줘\n",
    "df2.select_dtypes(include='object')  # 범주형 자료만 모아줘"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "021492c0-2d96-4eea-bcc9-6b5f8880edfa",
   "metadata": {},
   "outputs": [],
   "source": [
    "df3=df2.select_dtypes(include='number')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bbda2349-78b5-4da1-a512-31422568f717",
   "metadata": {},
   "outputs": [],
   "source": [
    "df3.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "c93ef856-06d8-49fe-956d-ab97f370b306",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "      <td>1925.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>3.535584</td>\n",
       "      <td>3.291429</td>\n",
       "      <td>2.928312</td>\n",
       "      <td>3.061299</td>\n",
       "      <td>3.041039</td>\n",
       "      <td>2.795844</td>\n",
       "      <td>3.086234</td>\n",
       "      <td>3.048831</td>\n",
       "      <td>3.065974</td>\n",
       "      <td>2.882597</td>\n",
       "      <td>...</td>\n",
       "      <td>3.515844</td>\n",
       "      <td>3.803636</td>\n",
       "      <td>3.363636</td>\n",
       "      <td>3.348571</td>\n",
       "      <td>0.409870</td>\n",
       "      <td>2.615584</td>\n",
       "      <td>3.171584</td>\n",
       "      <td>2.975792</td>\n",
       "      <td>3.547065</td>\n",
       "      <td>3.564260</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.940764</td>\n",
       "      <td>0.938191</td>\n",
       "      <td>1.019077</td>\n",
       "      <td>0.965832</td>\n",
       "      <td>1.018477</td>\n",
       "      <td>1.117515</td>\n",
       "      <td>1.088039</td>\n",
       "      <td>1.091788</td>\n",
       "      <td>1.138218</td>\n",
       "      <td>0.944804</td>\n",
       "      <td>...</td>\n",
       "      <td>1.000719</td>\n",
       "      <td>0.948183</td>\n",
       "      <td>0.911196</td>\n",
       "      <td>0.928613</td>\n",
       "      <td>0.491937</td>\n",
       "      <td>0.827519</td>\n",
       "      <td>0.744109</td>\n",
       "      <td>0.777280</td>\n",
       "      <td>0.748004</td>\n",
       "      <td>0.657075</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.400000</td>\n",
       "      <td>1.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.600000</td>\n",
       "      <td>2.400000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>4.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.200000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.600000</td>\n",
       "      <td>3.600000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.800000</td>\n",
       "      <td>3.600000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>...</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>8 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                Q1           Q2           Q3           Q4           Q5  \\\n",
       "count  1925.000000  1925.000000  1925.000000  1925.000000  1925.000000   \n",
       "mean      3.535584     3.291429     2.928312     3.061299     3.041039   \n",
       "std       0.940764     0.938191     1.019077     0.965832     1.018477   \n",
       "min       1.000000     1.000000     1.000000     1.000000     1.000000   \n",
       "25%       3.000000     3.000000     2.000000     2.000000     2.000000   \n",
       "50%       4.000000     3.000000     3.000000     3.000000     3.000000   \n",
       "75%       4.000000     4.000000     4.000000     4.000000     4.000000   \n",
       "max       5.000000     5.000000     5.000000     5.000000     5.000000   \n",
       "\n",
       "                Q6           Q7           Q8           Q9          Q10  ...  \\\n",
       "count  1925.000000  1925.000000  1925.000000  1925.000000  1925.000000  ...   \n",
       "mean      2.795844     3.086234     3.048831     3.065974     2.882597  ...   \n",
       "std       1.117515     1.088039     1.091788     1.138218     0.944804  ...   \n",
       "min       1.000000     1.000000     1.000000     1.000000     1.000000  ...   \n",
       "25%       2.000000     2.000000     2.000000     2.000000     2.000000  ...   \n",
       "50%       3.000000     3.000000     3.000000     3.000000     3.000000  ...   \n",
       "75%       4.000000     4.000000     4.000000     4.000000     4.000000  ...   \n",
       "max       5.000000     5.000000     5.000000     5.000000     5.000000  ...   \n",
       "\n",
       "               Q17          Q18          Q19          Q20      Gender1  \\\n",
       "count  1925.000000  1925.000000  1925.000000  1925.000000  1925.000000   \n",
       "mean      3.515844     3.803636     3.363636     3.348571     0.409870   \n",
       "std       1.000719     0.948183     0.911196     0.928613     0.491937   \n",
       "min       1.000000     1.000000     1.000000     1.000000     0.000000   \n",
       "25%       3.000000     4.000000     3.000000     3.000000     0.000000   \n",
       "50%       4.000000     4.000000     3.000000     3.000000     0.000000   \n",
       "75%       4.000000     4.000000     4.000000     4.000000     1.000000   \n",
       "max       5.000000     5.000000     5.000000     5.000000     1.000000   \n",
       "\n",
       "              EDU1           BF           BM    Happiness        Peace  \n",
       "count  1925.000000  1925.000000  1925.000000  1925.000000  1925.000000  \n",
       "mean      2.615584     3.171584     2.975792     3.547065     3.564260  \n",
       "std       0.827519     0.744109     0.777280     0.748004     0.657075  \n",
       "min       1.000000     1.000000     1.000000     1.400000     1.200000  \n",
       "25%       2.000000     2.600000     2.400000     3.000000     3.200000  \n",
       "50%       3.000000     3.200000     3.000000     3.600000     3.600000  \n",
       "75%       3.000000     3.800000     3.600000     4.000000     4.000000  \n",
       "max       4.000000     5.000000     5.000000     5.000000     5.000000  \n",
       "\n",
       "[8 rows x 26 columns]"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.describe(include='number')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "caae3f19-bf62-48ed-88d2-d4595517ae4c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# df.describe(include='object')\n",
    "# object 타입이 없으면 오류가 발생함\n",
    "# 가능하면 include와 object 타입을 구분해서 연습 추천함 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "3c24887b-0f3d-4392-a083-372b31d81697",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0       4\n",
       "1       4\n",
       "2       4\n",
       "3       5\n",
       "4       4\n",
       "       ..\n",
       "1920    2\n",
       "1921    3\n",
       "1922    5\n",
       "1923    4\n",
       "1924    3\n",
       "Name: Q1, Length: 1925, dtype: int64"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['Q1'] # [  ] 인덱싱 한다는 의미임 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "cee48838",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1\n",
       "4    1053\n",
       "3     354\n",
       "2     290\n",
       "5     181\n",
       "1      47\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 5) 시리즈(Series)의 각각의 값의 횟수 확인\n",
    "# 시리즈.value_counts()\n",
    "df['Q1'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "a1c7ed12-fe83-4a7d-bdb5-799d3aef2ce6",
   "metadata": {},
   "outputs": [],
   "source": [
    "df2=pd.read_csv('c:/data/titanic.csv')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "cee67381-5cd6-478d-9f7d-e85743772a7a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Gender\n",
       "male      0.647587\n",
       "female    0.352413\n",
       "Name: proportion, dtype: float64"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2['Gender'].value_counts(normalize=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "65d556e1-25bd-41d5-8b3f-8572bcbb1394",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Cabin\n",
       "NaN            687\n",
       "C23 C25 C27      4\n",
       "G6               4\n",
       "B96 B98          4\n",
       "C22 C26          3\n",
       "              ... \n",
       "E34              1\n",
       "C7               1\n",
       "C54              1\n",
       "E36              1\n",
       "C148             1\n",
       "Name: count, Length: 148, dtype: int64"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2['Cabin'].value_counts(dropna=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "0b489687-e92e-440b-a9ee-ac7164c04241",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 891 entries, 0 to 890\n",
      "Data columns (total 12 columns):\n",
      " #   Column       Non-Null Count  Dtype  \n",
      "---  ------       --------------  -----  \n",
      " 0   PassengerId  891 non-null    int64  \n",
      " 1   Survived     891 non-null    int64  \n",
      " 2   Pclass       891 non-null    int64  \n",
      " 3   Name         891 non-null    object \n",
      " 4   Gender       891 non-null    object \n",
      " 5   Age          714 non-null    float64\n",
      " 6   SibSp        891 non-null    int64  \n",
      " 7   Parch        891 non-null    int64  \n",
      " 8   Ticket       891 non-null    object \n",
      " 9   Fare         891 non-null    float64\n",
      " 10  Cabin        204 non-null    object \n",
      " 11  Embarked     889 non-null    object \n",
      "dtypes: float64(2), int64(5), object(5)\n",
      "memory usage: 83.7+ KB\n"
     ]
    }
   ],
   "source": [
    "df2.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "e97f06bc-b47c-4ed0-b07e-70755afb4fc5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1\n",
       "4    1053\n",
       "3     354\n",
       "2     290\n",
       "5     181\n",
       "1      47\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['Q1'].value_counts(dropna=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "318f795d-7f0a-400c-86f9-feaecda29530",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1\n",
       "4    0.547013\n",
       "3    0.183896\n",
       "2    0.150649\n",
       "5    0.094026\n",
       "1    0.024416\n",
       "Name: proportion, dtype: float64"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['Q1'].value_counts(normalize=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "152e8742",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([4, 5, 3, 2, 1], dtype=int64)"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 6) 시리즈(Series)의 값의 종류 확인\n",
    "df['Q1'].unique()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "99ba8552",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender1  \\\n",
      "0   4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4        0   \n",
      "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1        0   \n",
      "2   4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3        0   \n",
      "\n",
      "   EDU1   BF   BM  Happiness  Peace  \n",
      "0     1  3.4  3.2        4.0    4.0  \n",
      "1     1  4.0  3.4        4.0    2.8  \n",
      "2     2  3.6  3.6        3.8    3.8  \n",
      "\n",
      "[3 rows x 26 columns]\n",
      "      Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  \\\n",
      "1922   5   4   4   4   4   2   2   2   2    3  ...    3    4    4    4   \n",
      "1923   4   4   4   2   2   4   2   4   4    3  ...    4    4    3    4   \n",
      "1924   3   3   1   1   2   1   1   1   1    1  ...    4    4    3    2   \n",
      "\n",
      "      Gender1  EDU1   BF   BM  Happiness  Peace  \n",
      "1922        0     2  4.2  2.2        3.4    3.6  \n",
      "1923        1     2  3.2  3.4        3.0    3.8  \n",
      "1924        0     3  2.0  1.0        3.0    3.2  \n",
      "\n",
      "[3 rows x 26 columns]\n"
     ]
    }
   ],
   "source": [
    "# 7) 데이터의 상위 및 하위 N행 확인\n",
    "# head() 함수는 데이터의 상위 5행을 출력\n",
    "# tail() 함수는 데이터의 하위 5행을 출력\n",
    "# 괄호()안에 원하는 숫자만큼 행을 출력\n",
    "print(df.head(3))\n",
    "print(df.tail(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "a54afe1b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>665</th>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>1.8</td>\n",
       "      <td>2.6</td>\n",
       "      <td>2.4</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>550</th>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>3</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>894</th>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>1.6</td>\n",
       "      <td>1.6</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  \\\n",
       "665   1   1   2   1   4   2   3   2   3    3  ...    3    3    3    2   \n",
       "550   1   3   3   1   2   2   1   2   2    3  ...    3    4    3    3   \n",
       "894   1   1   2   2   2   1   1   2   2    2  ...    2    2    3    4   \n",
       "\n",
       "     Gender1  EDU1   BF   BM  Happiness  Peace  \n",
       "665        1     3  1.8  2.6        2.4    2.8  \n",
       "550        0     3  2.0  2.0        3.0    2.8  \n",
       "894        1     4  1.6  1.6        2.0    2.6  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#8)정렬\n",
    "# 데이터프레임 변수명.sort_values()\n",
    "df.sort_values(by='Q1').head(3)# Q1 열변수 기준으로 오름차순,ascending=True,기본값"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "292b028f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>507</th>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>613</th>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>4.2</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>499</th>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>3</td>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.6</td>\n",
       "      <td>3.4</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  \\\n",
       "507   5   2   2   4   2   2   3   4   4    4  ...    3    4    4    3   \n",
       "613   5   4   4   2   3   4   2   5   5    5  ...    4    5    5    5   \n",
       "499   5   5   3   5   2   3   2   4   2    2  ...    2    2    5    2   \n",
       "\n",
       "     Gender1  EDU1   BF   BM  Happiness  Peace  \n",
       "507        0     2  3.0  3.4        3.6    3.6  \n",
       "613        1     2  3.6  4.2        5.0    4.6  \n",
       "499        1     3  4.0  2.6        3.4    2.8  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.sort_values(by='Q1',ascending=False).head(3) # Q1 열변수 기준으로 내림차순"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "5256d883-1f2c-4c96-9088-916d29e9af16",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "665     1\n",
       "550     1\n",
       "894     1\n",
       "896     1\n",
       "204     1\n",
       "       ..\n",
       "935     5\n",
       "1229    5\n",
       "422     5\n",
       "1568    5\n",
       "561     5\n",
       "Name: Q1, Length: 1925, dtype: int64"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['Q1'].sort_values()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "b82eabc0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>22</th>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.8</td>\n",
       "      <td>4.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>93</th>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.2</td>\n",
       "      <td>4.2</td>\n",
       "      <td>4.2</td>\n",
       "      <td>4.2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "    Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender1  \\\n",
       "3    5   4   4   4   4   4   4   4   4    4  ...    4    4    4    4        0   \n",
       "22   5   5   5   5   5   5   5   5   5    5  ...    4    4    4    5        0   \n",
       "93   5   4   4   4   4   5   4   4   4    4  ...    4    4    4    4        0   \n",
       "\n",
       "    EDU1   BF   BM  Happiness  Peace  \n",
       "3      1  4.2  4.0        4.0    4.0  \n",
       "22     1  5.0  5.0        4.8    4.2  \n",
       "93     1  4.2  4.2        4.2    4.2  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 복수의 컬럼 기준으로 각각 내림차순과 오름차순 정렬\n",
    "df.sort_values(['Q1','EDU'],ascending=[False,True]).head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "14f6b9fc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>gender</th>\n",
       "      <th>edu</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  gender  \\\n",
       "0   4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4       0   \n",
       "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1       0   \n",
       "2   4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3       0   \n",
       "\n",
       "   edu   BF   BM  Happiness  Peace  \n",
       "0    1  3.4  3.2        4.0    4.0  \n",
       "1    1  4.0  3.4        4.0    2.8  \n",
       "2    2  3.6  3.6        3.8    3.8  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 9) 열변수명 변경, 행인덱스 변경\n",
    "# 데이터프레임 변수명.rename(columns={'변경전 변수이름': '변경후 변수이름'})\n",
    "# 열변수이름  'Gender'->'gender','EDU'->'edu' 변경\n",
    "df=df.rename(columns={'Gender':'gender','EDU':'edu'})\n",
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "5b60b04d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>gender</th>\n",
       "      <th>edu</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>a</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  gender  \\\n",
       "a   4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4       0   \n",
       "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1       0   \n",
       "2   4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3       0   \n",
       "\n",
       "   edu   BF   BM  Happiness  Peace  \n",
       "a    1  3.4  3.2        4.0    4.0  \n",
       "1    1  4.0  3.4        4.0    2.8  \n",
       "2    2  3.6  3.6        3.8    3.8  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 행 인덱스 변경\n",
    "df.rename(index={0:'a'}).head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "5d23a5b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(5) 인덱싱(indexing), 슬라이싱(slicing)\n",
    "# numpy에서 [ ]연산자는 행의 위치, 열의 위치, 슬라이싱 범위 지정\n",
    "# pandas에서 [ ]연산자는 컬럼명 문자 또는 인덱스로 변환 가능한 표현"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "49806f6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1) 컬럼명으로 데이터 추출\n",
    "# 하나의 열을 추출, 데이터프레임 변수명['컬럼명']\n",
    "# 시리즈(Series)로 추출된다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "395c34ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0       4.0\n",
      "1       2.8\n",
      "2       3.8\n",
      "3       4.0\n",
      "4       4.0\n",
      "       ... \n",
      "1920    2.0\n",
      "1921    3.4\n",
      "1922    3.6\n",
      "1923    3.8\n",
      "1924    3.2\n",
      "Name: Peace, Length: 1925, dtype: float64\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df=pd.read_csv('c:/data/Data1.csv')\n",
    "print(df['Peace'])\n",
    "df1=df['Peace'] # Peace 변수 추출\n",
    "type(df1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "1363e276",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      Peace  Happiness\n",
      "0       4.0        4.0\n",
      "1       2.8        4.0\n",
      "2       3.8        3.8\n",
      "3       4.0        4.0\n",
      "4       4.0        4.0\n",
      "...     ...        ...\n",
      "1920    2.0        2.0\n",
      "1921    3.4        3.4\n",
      "1922    3.6        3.4\n",
      "1923    3.8        3.0\n",
      "1924    3.2        3.0\n",
      "\n",
      "[1925 rows x 2 columns]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "pandas.core.frame.DataFrame"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2개 이상의 컬럼을 추출할때 데이터프레임 변수명[['컬럼이름1','컬럼이름2']]\n",
    "# 시리즈가 아닌 데이터프레임 형태로 추출된다.\n",
    "print(df[[\"Peace\",\"Happiness\"]])\n",
    "df2=df[[\"Peace\",\"Happiness\"]]\n",
    "type(df2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "bc6869c2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.6</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender  \\\n",
       "0   4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4       0   \n",
       "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1       0   \n",
       "2   4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3       0   \n",
       "3   5   4   4   4   4   4   4   4   4    4  ...    4    4    4    4       0   \n",
       "4   4   4   4   4   4   4   4   4   2    4  ...    4    4    4    4       0   \n",
       "\n",
       "   EDU   BF   BM  Happiness  Peace  \n",
       "0    1  3.4  3.2        4.0    4.0  \n",
       "1    1  4.0  3.4        4.0    2.8  \n",
       "2    2  3.6  3.6        3.8    3.8  \n",
       "3    1  4.2  4.0        4.0    4.0  \n",
       "4    2  4.0  3.6        4.0    4.0  \n",
       "\n",
       "[5 rows x 26 columns]"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#(2) 인덱스,슬라이싱으로 추출 데이터프레임변수[인덱스 시작:인덱스 종료]\n",
    "df[:] # 모든 행 추출\n",
    "df[0:5]# 첫5행까지 추출"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "18049195",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(3) loc,iloc 함수 \n",
    "# 원하는 행과 열을 추출할 때 사용\n",
    "# 데이터프레임변수.loc['행이름','열이름']: '이름'을 통해 선택\n",
    "# loc 함수는 행위치에서는 데이터 프레임의 인덱스 값, 열 위치에서의 컬럼명 사용\n",
    "# 데이터프레임변수.iloc[행번호,열번호] : 위치 번호를 통해 선택\n",
    "# iloc 함수는 위치 기반으로 인덱싱 하기 때문에 행과 열의값으로 정수형 사용"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "c3d21f05",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender1  \\\n",
       "0   4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4        0   \n",
       "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1        0   \n",
       "2   4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3        0   \n",
       "\n",
       "   EDU1   BF   BM  Happiness  Peace  \n",
       "0     1  3.4  3.2        4.0    4.0  \n",
       "1     1  4.0  3.4        4.0    2.8  \n",
       "2     2  3.6  3.6        3.8    3.8  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1)loc 함수로 첫번째 행과 열(Q1) 값을 추출하기\n",
    "print(df.loc[0,'Q1'])\n",
    "df.head(3)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "ba7e79e0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0       4.0\n",
       "1       4.0\n",
       "2       3.8\n",
       "3       4.0\n",
       "4       4.0\n",
       "       ... \n",
       "1920    2.0\n",
       "1921    3.4\n",
       "1922    3.4\n",
       "1923    3.0\n",
       "1924    3.0\n",
       "Name: Happiness, Length: 1925, dtype: float64"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2)loc 함수로 특정 열('Happiness')값만 추출하기\n",
    "df.loc[:,'Happiness'] # 시리즈로 출력"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "bf39f31a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Happiness  Peace\n",
       "0        4.0    4.0\n",
       "1        4.0    2.8\n",
       "2        3.8    3.8"
      ]
     },
     "execution_count": 101,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.loc[:,['Happiness','Peace']].head(3) # 데이터프레임으로 출력\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "921add60",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0     4.0\n",
      "1     4.0\n",
      "2     3.8\n",
      "3     4.0\n",
      "4     4.0\n",
      "5     4.0\n",
      "6     4.8\n",
      "7     4.4\n",
      "8     3.8\n",
      "9     4.0\n",
      "10    4.0\n",
      "Name: Happiness, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# loc 함수는 행의 위치에 슬라이싱 적용하면 복수행의 데이터 값을 추출할 수 있다.\n",
    "print(df.loc[0:10,'Happiness']) # 인덱스 이름이므로 10이 포함된다.\n",
    "# print(df.loc[0:10,['Happiness']]) # 대괄호 2개, 데이터 프레임으로 출력"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "id": "0100b324",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    4.0\n",
       "Q2    4.0\n",
       "Q3    2.0\n",
       "Name: 0, dtype: float64"
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#3)Ioc 함수로 특정 행값만 추출하기\n",
    "df.loc[0].head(3) # 0번째 행만 추출하기"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "id": "45bed397",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#4)iloc 함수로 df의 첫번째 행과 열의 값을 추출\n",
    "df.iloc[0,0] # [행위치,열위치]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "id": "2cd2e5f5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>2 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender1  \\\n",
       "0   4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4        0   \n",
       "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1        0   \n",
       "\n",
       "   EDU1   BF   BM  Happiness  Peace  \n",
       "0     1  3.4  3.2        4.0    4.0  \n",
       "1     1  4.0  3.4        4.0    2.8  \n",
       "\n",
       "[2 rows x 26 columns]"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.iloc[:2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "id": "ae3a7bdf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    4\n",
       "1    4\n",
       "2    4\n",
       "3    5\n",
       "Name: Q1, dtype: int64"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#5)iloc 함수로 df 0~3행의 첫번째 열의 값을 추출\n",
    "df.iloc[0:4,0]\n",
    "# index로 추출하기 때문에 4가 포함되지 않음"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "id": "1bf8b104",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0       4\n",
       "1       4\n",
       "2       4\n",
       "3       5\n",
       "4       4\n",
       "       ..\n",
       "1920    2\n",
       "1921    3\n",
       "1922    5\n",
       "1923    4\n",
       "1924    3\n",
       "Name: Q1, Length: 1925, dtype: int64"
      ]
     },
     "execution_count": 113,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#6) iloc 함수로 특정 열만 추출하기\n",
    "df.iloc[:,0] # 첫번째 열변수 'Q1' 추출하기"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "id": "1871d531",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    4.0\n",
       "Q2    4.0\n",
       "Q3    2.0\n",
       "Q4    3.0\n",
       "Q5    4.0\n",
       "Name: 0, dtype: float64"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#7)iloc 함수로 df의 첫번째 행만 추출하기\n",
    "df.iloc[0].head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "id": "58883be5",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(4) 데이터 특정 조건 추출\n",
    "# 작업형 제1유형에서 반드시 사용\n",
    "# 논리 자료형 (True,False) \n",
    "# 비교 연산자(>,<,==,!=,>=,<=)\n",
    "# 복수 조건등은  NOT(~), AND(&), OR(|) 연산자를 통해 추출할 수 있다.\n",
    "# 논리 자료형이 '대괄호'[ ]에서 해당 조건이 참(True)인 행만을 선택한다.\n",
    "df=pd.read_csv('c:/data/Data1.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "id": "34381084",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Happiness  Peace\n",
       "0        4.0    4.0\n",
       "1        4.0    2.8\n",
       "2        3.8    3.8"
      ]
     },
     "execution_count": 119,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#1) 데이터프레임 추출, 데이터프레임변수명[[\"열변수1\",\"열변수2\"]]\n",
    "df[['Happiness','Peace']].head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "id": "6460b5fe",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0       3.4\n",
       "1       4.0\n",
       "2       3.6\n",
       "3       4.2\n",
       "4       4.0\n",
       "       ... \n",
       "1920    1.8\n",
       "1921    2.4\n",
       "1922    4.2\n",
       "1923    3.2\n",
       "1924    2.0\n",
       "Name: BF, Length: 1925, dtype: float64"
      ]
     },
     "execution_count": 121,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 데이터프레임변수명['열변수'], 시리즈로 출력\n",
    "df['BF']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "id": "f77a4c89",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0        True\n",
       "1       False\n",
       "2       False\n",
       "3       False\n",
       "4       False\n",
       "        ...  \n",
       "1920    False\n",
       "1921    False\n",
       "1922    False\n",
       "1923    False\n",
       "1924    False\n",
       "Name: BF, Length: 1925, dtype: bool"
      ]
     },
     "execution_count": 123,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['BF']==3.4 # 비교 연산자 결과 참이면 True 거짓이면 False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "id": "e41b5a7b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50</th>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.6</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>51</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "    Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender1  \\\n",
       "0    4   4   2   3   4   2   2   4   4    4  ...    4    4    4    4        0   \n",
       "50   2   2   4   4   5   1   5   4   4    4  ...    4    4    4    4        0   \n",
       "51   4   4   3   3   3   2   4   4   4    2  ...    4    4    2    4        0   \n",
       "\n",
       "    EDU1   BF   BM  Happiness  Peace  \n",
       "0      1  3.4  3.2        4.0    4.0  \n",
       "50     1  3.4  3.6        4.0    4.0  \n",
       "51     1  3.4  3.2        3.6    3.6  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 125,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[df['BF']==3.4].head(3) # 대괄호[]안에 참(True)만 출력"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "3f236c17",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender  \\\n",
       "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1       0   \n",
       "2   4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3       0   \n",
       "3   5   4   4   4   4   4   4   4   4    4  ...    4    4    4    4       0   \n",
       "\n",
       "   EDU   BF   BM  Happiness  Peace  \n",
       "1    1  4.0  3.4        4.0    2.8  \n",
       "2    2  3.6  3.6        3.8    3.8  \n",
       "3    1  4.2  4.0        4.0    4.0  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# and 조건일 때 '&', or 조건일 때 '|', not 조건일 떄 '~' 사용\n",
    "df[(df['BF']>3.4)&  \n",
    "   (df['BM']>1.2)].head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "id": "a14bfdf4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender1</th>\n",
       "      <th>EDU1</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender1  \\\n",
       "1   4   4   4   4   4   3   2   4   4    4  ...    3    4    2    1        0   \n",
       "2   4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3        0   \n",
       "3   5   4   4   4   4   4   4   4   4    4  ...    4    4    4    4        0   \n",
       "\n",
       "   EDU1   BF   BM  Happiness  Peace  \n",
       "1     1  4.0  3.4        4.0    2.8  \n",
       "2     2  3.6  3.6        3.8    3.8  \n",
       "3     1  4.2  4.0        4.0    4.0  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 129,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[(df['BF']>3.4)&\n",
    "   (df['BM']>1.2)&\n",
    "   (df['Gender']==0)].head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "a04f94b2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>Gender</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.6</td>\n",
       "      <td>3.8</td>\n",
       "      <td>3.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.6</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "    Q1  Q2  Q3  Q4  Q5  Q6  Q7  Q8  Q9  Q10  ...  Q17  Q18  Q19  Q20  Gender  \\\n",
       "2    4   4   4   4   2   4   4   4   4    2  ...    4    4    4    3       0   \n",
       "4    4   4   4   4   4   4   4   4   2    4  ...    4    4    4    4       0   \n",
       "10   4   4   4   4   4   2   4   4   4    2  ...    4    4    4    4       0   \n",
       "\n",
       "    EDU   BF   BM  Happiness  Peace  \n",
       "2     2  3.6  3.6        3.8    3.8  \n",
       "4     2  4.0  3.6        4.0    4.0  \n",
       "10    2  4.0  3.2        4.0    4.0  \n",
       "\n",
       "[3 rows x 26 columns]"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[(df['BF']>3.4)&\n",
    "   (df['BM']>1.2)&\n",
    "   (df['Gender']==0)&\n",
    "    ~(df['EDU']==1)].head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "id": "d6320a32",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    6806.0\n",
       "Q2    6336.0\n",
       "Q3    5637.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 133,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2) 모든 열변수의 집계함수\n",
    "df.sum().head(3) # 각 열변수별로 합계"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "id": "e9658890",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    1925\n",
       "Q2    1925\n",
       "Q3    1925\n",
       "dtype: int64"
      ]
     },
     "execution_count": 135,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.count().head(3) # 각 열변수별로 행의 수"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "e4c69602",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    1.0\n",
       "Q2    1.0\n",
       "Q3    1.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 137,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.min().head(3) # 각 열변수별로 최소값"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "8bd0ff31",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    5.0\n",
       "Q2    5.0\n",
       "Q3    5.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 139,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.max().head(3) # 각 열변수별로 최대값"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "id": "a57562a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    0.885038\n",
       "Q2    0.880202\n",
       "Q3    1.038517\n",
       "dtype: float64"
      ]
     },
     "execution_count": 141,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.var().head(3)  # 각 열변수별로 분산"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "id": "f9c54962",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    4.0\n",
       "Q2    3.0\n",
       "Q3    3.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 143,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.median().head(3) # 각 열변수별로 중위값"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "id": "5b25ccb6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Q1    0.940764\n",
       "Q2    0.938191\n",
       "Q3    1.019077\n",
       "dtype: float64"
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.std().head(3)  # 각 열변수별로 표준편차"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "2538a5ea",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Happiness    3.547065\n",
       "dtype: float64"
      ]
     },
     "execution_count": 147,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2) 특정컬럼(변수)의 집계함수\n",
    "df[['Happiness']].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "id": "8022fc6b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Happiness    1.4\n",
       "dtype: float64"
      ]
     },
     "execution_count": 149,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].min()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "id": "646a82ef",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Happiness    5.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 151,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "id": "553bf7c1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Happiness    0.559509\n",
       "dtype: float64"
      ]
     },
     "execution_count": 153,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].var()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "id": "cd59f846",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Happiness    0.748004\n",
       "dtype: float64"
      ]
     },
     "execution_count": 155,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "57624ad3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.6"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].median()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 163,
   "id": "e2a781d4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Happiness</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Happiness\n",
       "0        4.0"
      ]
     },
     "execution_count": 163,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].mode() # 최빈값"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 167,
   "id": "7c507a00-3356-428d-9e24-6dc67123846e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.0"
      ]
     },
     "execution_count": 167,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['Happiness'].mode()[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 175,
   "id": "ed1bea5a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Happiness   -0.369651\n",
       "dtype: float64"
      ]
     },
     "execution_count": 175,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].skew() # 왜도"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 177,
   "id": "7c13eae4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Happiness   -0.193014\n",
       "dtype: float64"
      ]
     },
     "execution_count": 177,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].kurt() # 첨도 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 179,
   "id": "72a8732a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Happiness</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>1925.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>3.547065</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.748004</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1.400000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>3.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>3.600000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>4.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>5.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         Happiness\n",
       "count  1925.000000\n",
       "mean      3.547065\n",
       "std       0.748004\n",
       "min       1.400000\n",
       "25%       3.000000\n",
       "50%       3.600000\n",
       "75%       4.000000\n",
       "max       5.000000"
      ]
     },
     "execution_count": 179,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[['Happiness']].describe() # 특정변수의 기술 통계량"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 181,
   "id": "c66a0b9f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.0"
      ]
     },
     "execution_count": 181,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# quantile(.75)= 상위 25%\n",
    "df['Happiness'].quantile(.75)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "id": "1cbb490c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.0"
      ]
     },
     "execution_count": 183,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# quantile(.25)=하위 25%\n",
    "df['Happiness'].quantile(.25)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "id": "3db0ef75",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0       False\n",
       "1       False\n",
       "2       False\n",
       "3       False\n",
       "4       False\n",
       "        ...  \n",
       "1920    False\n",
       "1921    False\n",
       "1922    False\n",
       "1923    False\n",
       "1924    False\n",
       "Name: Happiness, Length: 1925, dtype: bool"
      ]
     },
     "execution_count": 185,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 상위 25% 데이터 추출\n",
    "df['Happiness'].quantile(.75)<df['Happiness']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "65440fdc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "315"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1=df['Happiness'].quantile(.75)<df['Happiness']\n",
    "len(df[df1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "979f28c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3) 그룹별 집계함수\n",
    "# 데이터프레임 변수명.groupby('그룹 열변수')\n",
    "# 데이터를 그룹별로 분할하여 독립된 그룹에 대하여 별도로 데이터를 처리(혹은 적용)하거나 \n",
    "# 그룹별 통계량을 확인하고자 할 때 유용한 함수"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "bbd794b3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q16</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Gender</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3.539613</td>\n",
       "      <td>3.249120</td>\n",
       "      <td>2.868838</td>\n",
       "      <td>3.014085</td>\n",
       "      <td>2.954225</td>\n",
       "      <td>2.674296</td>\n",
       "      <td>3.069542</td>\n",
       "      <td>3.073063</td>\n",
       "      <td>3.071303</td>\n",
       "      <td>2.841549</td>\n",
       "      <td>...</td>\n",
       "      <td>3.848592</td>\n",
       "      <td>3.537852</td>\n",
       "      <td>3.876761</td>\n",
       "      <td>3.375880</td>\n",
       "      <td>3.345951</td>\n",
       "      <td>2.519366</td>\n",
       "      <td>3.125088</td>\n",
       "      <td>2.945863</td>\n",
       "      <td>3.565933</td>\n",
       "      <td>3.596655</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3.529785</td>\n",
       "      <td>3.352345</td>\n",
       "      <td>3.013942</td>\n",
       "      <td>3.129278</td>\n",
       "      <td>3.166033</td>\n",
       "      <td>2.970849</td>\n",
       "      <td>3.110266</td>\n",
       "      <td>3.013942</td>\n",
       "      <td>3.058302</td>\n",
       "      <td>2.941698</td>\n",
       "      <td>...</td>\n",
       "      <td>3.708492</td>\n",
       "      <td>3.484157</td>\n",
       "      <td>3.698352</td>\n",
       "      <td>3.346008</td>\n",
       "      <td>3.352345</td>\n",
       "      <td>2.754119</td>\n",
       "      <td>3.238530</td>\n",
       "      <td>3.018885</td>\n",
       "      <td>3.519899</td>\n",
       "      <td>3.517617</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>2 rows × 25 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "              Q1        Q2        Q3        Q4        Q5        Q6        Q7  \\\n",
       "Gender                                                                         \n",
       "0       3.539613  3.249120  2.868838  3.014085  2.954225  2.674296  3.069542   \n",
       "1       3.529785  3.352345  3.013942  3.129278  3.166033  2.970849  3.110266   \n",
       "\n",
       "              Q8        Q9       Q10  ...       Q16       Q17       Q18  \\\n",
       "Gender                                ...                                 \n",
       "0       3.073063  3.071303  2.841549  ...  3.848592  3.537852  3.876761   \n",
       "1       3.013942  3.058302  2.941698  ...  3.708492  3.484157  3.698352   \n",
       "\n",
       "             Q19       Q20       EDU        BF        BM  Happiness     Peace  \n",
       "Gender                                                                         \n",
       "0       3.375880  3.345951  2.519366  3.125088  2.945863   3.565933  3.596655  \n",
       "1       3.346008  3.352345  2.754119  3.238530  3.018885   3.519899  3.517617  \n",
       "\n",
       "[2 rows x 25 columns]"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.groupby('Gender').mean() # 'Gender'별로 평균값 확인"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "baea3949-bd71-4207-90aa-de52a30315ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "df2=pd.read_csv('c:/data/titanic.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "f0d193df-3ca7-45e6-aed3-629a3a78d4c9",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "agg function failed [how->mean,dtype->object]",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\groupby\\groupby.py:1944\u001b[0m, in \u001b[0;36mGroupBy._agg_py_fallback\u001b[1;34m(self, how, values, ndim, alt)\u001b[0m\n\u001b[0;32m   1943\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m-> 1944\u001b[0m     res_values \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_grouper\u001b[38;5;241m.\u001b[39magg_series(ser, alt, preserve_dtype\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[0;32m   1945\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\groupby\\ops.py:873\u001b[0m, in \u001b[0;36mBaseGrouper.agg_series\u001b[1;34m(self, obj, func, preserve_dtype)\u001b[0m\n\u001b[0;32m    871\u001b[0m     preserve_dtype \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m--> 873\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_aggregate_series_pure_python(obj, func)\n\u001b[0;32m    875\u001b[0m npvalues \u001b[38;5;241m=\u001b[39m lib\u001b[38;5;241m.\u001b[39mmaybe_convert_objects(result, try_float\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\groupby\\ops.py:894\u001b[0m, in \u001b[0;36mBaseGrouper._aggregate_series_pure_python\u001b[1;34m(self, obj, func)\u001b[0m\n\u001b[0;32m    893\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i, group \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(splitter):\n\u001b[1;32m--> 894\u001b[0m     res \u001b[38;5;241m=\u001b[39m func(group)\n\u001b[0;32m    895\u001b[0m     res \u001b[38;5;241m=\u001b[39m extract_result(res)\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\groupby\\groupby.py:2461\u001b[0m, in \u001b[0;36mGroupBy.mean.<locals>.<lambda>\u001b[1;34m(x)\u001b[0m\n\u001b[0;32m   2458\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m   2459\u001b[0m     result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_cython_agg_general(\n\u001b[0;32m   2460\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmean\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m-> 2461\u001b[0m         alt\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mlambda\u001b[39;00m x: Series(x, copy\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\u001b[38;5;241m.\u001b[39mmean(numeric_only\u001b[38;5;241m=\u001b[39mnumeric_only),\n\u001b[0;32m   2462\u001b[0m         numeric_only\u001b[38;5;241m=\u001b[39mnumeric_only,\n\u001b[0;32m   2463\u001b[0m     )\n\u001b[0;32m   2464\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m result\u001b[38;5;241m.\u001b[39m__finalize__(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mobj, method\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgroupby\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\series.py:6570\u001b[0m, in \u001b[0;36mSeries.mean\u001b[1;34m(self, axis, skipna, numeric_only, **kwargs)\u001b[0m\n\u001b[0;32m   6562\u001b[0m \u001b[38;5;129m@doc\u001b[39m(make_doc(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmean\u001b[39m\u001b[38;5;124m\"\u001b[39m, ndim\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m1\u001b[39m))\n\u001b[0;32m   6563\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mmean\u001b[39m(\n\u001b[0;32m   6564\u001b[0m     \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m   6568\u001b[0m     \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs,\n\u001b[0;32m   6569\u001b[0m ):\n\u001b[1;32m-> 6570\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m NDFrame\u001b[38;5;241m.\u001b[39mmean(\u001b[38;5;28mself\u001b[39m, axis, skipna, numeric_only, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\generic.py:12485\u001b[0m, in \u001b[0;36mNDFrame.mean\u001b[1;34m(self, axis, skipna, numeric_only, **kwargs)\u001b[0m\n\u001b[0;32m  12478\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mmean\u001b[39m(\n\u001b[0;32m  12479\u001b[0m     \u001b[38;5;28mself\u001b[39m,\n\u001b[0;32m  12480\u001b[0m     axis: Axis \u001b[38;5;241m|\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0\u001b[39m,\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m  12483\u001b[0m     \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs,\n\u001b[0;32m  12484\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Series \u001b[38;5;241m|\u001b[39m \u001b[38;5;28mfloat\u001b[39m:\n\u001b[1;32m> 12485\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_stat_function(\n\u001b[0;32m  12486\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmean\u001b[39m\u001b[38;5;124m\"\u001b[39m, nanops\u001b[38;5;241m.\u001b[39mnanmean, axis, skipna, numeric_only, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs\n\u001b[0;32m  12487\u001b[0m     )\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\generic.py:12442\u001b[0m, in \u001b[0;36mNDFrame._stat_function\u001b[1;34m(self, name, func, axis, skipna, numeric_only, **kwargs)\u001b[0m\n\u001b[0;32m  12440\u001b[0m validate_bool_kwarg(skipna, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mskipna\u001b[39m\u001b[38;5;124m\"\u001b[39m, none_allowed\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\n\u001b[1;32m> 12442\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_reduce(\n\u001b[0;32m  12443\u001b[0m     func, name\u001b[38;5;241m=\u001b[39mname, axis\u001b[38;5;241m=\u001b[39maxis, skipna\u001b[38;5;241m=\u001b[39mskipna, numeric_only\u001b[38;5;241m=\u001b[39mnumeric_only\n\u001b[0;32m  12444\u001b[0m )\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\series.py:6478\u001b[0m, in \u001b[0;36mSeries._reduce\u001b[1;34m(self, op, name, axis, skipna, numeric_only, filter_type, **kwds)\u001b[0m\n\u001b[0;32m   6474\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\n\u001b[0;32m   6475\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mSeries.\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m does not allow \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mkwd_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m=\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mnumeric_only\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m   6476\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mwith non-numeric dtypes.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m   6477\u001b[0m     )\n\u001b[1;32m-> 6478\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m op(delegate, skipna\u001b[38;5;241m=\u001b[39mskipna, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwds)\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\nanops.py:147\u001b[0m, in \u001b[0;36mbottleneck_switch.__call__.<locals>.f\u001b[1;34m(values, axis, skipna, **kwds)\u001b[0m\n\u001b[0;32m    146\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m--> 147\u001b[0m     result \u001b[38;5;241m=\u001b[39m alt(values, axis\u001b[38;5;241m=\u001b[39maxis, skipna\u001b[38;5;241m=\u001b[39mskipna, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwds)\n\u001b[0;32m    149\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m result\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\nanops.py:404\u001b[0m, in \u001b[0;36m_datetimelike_compat.<locals>.new_func\u001b[1;34m(values, axis, skipna, mask, **kwargs)\u001b[0m\n\u001b[0;32m    402\u001b[0m     mask \u001b[38;5;241m=\u001b[39m isna(values)\n\u001b[1;32m--> 404\u001b[0m result \u001b[38;5;241m=\u001b[39m func(values, axis\u001b[38;5;241m=\u001b[39maxis, skipna\u001b[38;5;241m=\u001b[39mskipna, mask\u001b[38;5;241m=\u001b[39mmask, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[0;32m    406\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m datetimelike:\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\nanops.py:720\u001b[0m, in \u001b[0;36mnanmean\u001b[1;34m(values, axis, skipna, mask)\u001b[0m\n\u001b[0;32m    719\u001b[0m the_sum \u001b[38;5;241m=\u001b[39m values\u001b[38;5;241m.\u001b[39msum(axis, dtype\u001b[38;5;241m=\u001b[39mdtype_sum)\n\u001b[1;32m--> 720\u001b[0m the_sum \u001b[38;5;241m=\u001b[39m _ensure_numeric(the_sum)\n\u001b[0;32m    722\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m axis \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;28mgetattr\u001b[39m(the_sum, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mndim\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mFalse\u001b[39;00m):\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\nanops.py:1701\u001b[0m, in \u001b[0;36m_ensure_numeric\u001b[1;34m(x)\u001b[0m\n\u001b[0;32m   1699\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(x, \u001b[38;5;28mstr\u001b[39m):\n\u001b[0;32m   1700\u001b[0m     \u001b[38;5;66;03m# GH#44008, GH#36703 avoid casting e.g. strings to numeric\u001b[39;00m\n\u001b[1;32m-> 1701\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCould not convert string \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mx\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m to numeric\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m   1702\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n",
      "\u001b[1;31mTypeError\u001b[0m: Could not convert string 'Cumings, Mrs. John Bradley (Florence Briggs Thayer)Heikkinen, Miss. LainaFutrelle, Mrs. Jacques Heath (Lily May Peel)Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)Nasser, Mrs. Nicholas (Adele Achem)Sandstrom, Miss. Marguerite RutBonnell, Miss. ElizabethVestrom, Miss. Hulda Amanda AdolfinaHewlett, Mrs. (Mary D Kingcome) Vander Planke, Mrs. Julius (Emelia Maria Vandemoortele)Masselmani, Mrs. FatimaMcGowan, Miss. Anna \"Annie\"Palsson, Miss. Torborg DaniraAsplund, Mrs. Carl Oscar (Selma Augusta Emilia Johansson)O'Dwyer, Miss. Ellen \"Nellie\"Spencer, Mrs. William Augustus (Marie Eugenie)Glynn, Miss. Mary AgathaVander Planke, Miss. Augusta MariaNicola-Yarred, Miss. JamilaAhlin, Mrs. Johan (Johanna Persdotter Larsson)Turpin, Mrs. William John Robert (Dorothy Ann Wonnacott)Laroche, Miss. Simonne Marie Anne AndreeDevaney, Miss. Margaret DeliaO'Driscoll, Miss. BridgetArnold-Franchi, Mrs. Josef (Josefine Franchi)Harper, Mrs. Henry Sleeper (Myna Haxtun)Faunthorpe, Mrs. Lizzie (Elizabeth Anne Wilkinson)Rugg, Miss. EmilyWest, Miss. Constance MiriumIcard, Miss. AmelieNye, Mrs. (Elizabeth Ramell)Andersson, Miss. Erna AlexandraGoodwin, Miss. Lillian AmyDowdell, Miss. ElizabethMcDermott, Miss. Brigdet DeliaIlett, Miss. BerthaBackstrom, Mrs. Karl Alfred (Maria Mathilda Gustafsson)Fortune, Miss. Mabel HelenDoling, Mrs. John T (Ada Julia Bone)Petranec, Miss. MatildaSalkjelsvik, Miss. Anna KristineMoran, Miss. BerthaZabour, Miss. HileniJussila, Miss. KatriinaAttalah, Miss. MalakeAndersson, Miss. Ellis Anna MariaWebber, Miss. SusanPeter, Miss. AnnaRobins, Mrs. Alexander A (Grace Charity Laury)Weisz, Mrs. Leopold (Mathilde Francoise Pede)Newsom, Miss. Helen MonypenyBoulos, Mrs. Joseph (Sultana)Nysten, Miss. Anna SofiaHakkarainen, Mrs. Pekka Pietari (Elin Matilda Dolck)Ford, Miss. Robina Maggie \"Ruby\"Pears, Mrs. Thomas (Edith Wearne)Gilnagh, Miss. Katherine \"Katie\"Watt, Mrs. James (Elizabeth \"Bessie\" Inglis Milne)Chibnall, Mrs. (Edith Martha Bowerman)Skoog, Mrs. William (Anna Bernhardina Karlsson)Johnson, Miss. Eleanor IleenIsham, Miss. Ann ElizabethSage, Miss. Constance GladysKink-Heilmann, Miss. Luise GretchenO'Brien, Mrs. Thomas (Johanna \"Hannah\" Godfrey)Pinsky, Mrs. (Rosa)Andersen-Jensen, Miss. Carla Christine NielsineBrown, Mrs. James Joseph (Margaret Tobin)Lurette, Miss. EliseMadigan, Miss. Margaret \"Maggie\"Yrois, Miss. Henriette (\"Mrs Harbeck\")Strom, Miss. Telma MatildaCarr, Miss. Helen \"Ellen\"Cameron, Miss. Clear AnnieNewell, Miss. MadeleineHonkanen, Miss. EliinaBazzani, Miss. AlbinaLefebre, Miss. MathildeHarris, Mrs. Henry Birkhardt (Irene Wallach)Asplund, Miss. Lillian GertrudHarknett, Miss. Alice PhoebeCollyer, Miss. Marjorie \"Lottie\"Zabour, Miss. ThamineMurphy, Miss. Katherine \"Kate\"Lindahl, Miss. Agda Thorilda ViktoriaHamalainen, Mrs. William (Anna)Strom, Mrs. Wilhelm (Elna Matilda Persson)Rosblom, Mrs. Viktor (Helena Wilhelmina)Touma, Mrs. Darwis (Hanne Youssef Razi)Thorne, Mrs. Gertrude MaybelleCherry, Miss. GladysWard, Miss. AnnaParrish, Mrs. (Lutie Davis)Henry, Miss. DeliaGraham, Mrs. William Thompson (Edith Junkins)Bissette, Miss. AmeliaMellinger, Mrs. (Elizabeth Anne Maidment)Healy, Miss. Hanora \"Nora\"Andrews, Miss. Kornelia TheodosiaLindblom, Miss. Augusta CharlottaAbbott, Mrs. Stanton (Rosa Hunt)Connolly, Miss. KateBarber, Miss. Ellen \"Nellie\"Bishop, Mrs. Dickinson H (Helen Walton)Haas, Miss. AloisiaAllison, Miss. Helen LoraineBaxter, Mrs. James (Helene DeLaudeniere Chaput)Kelly, Miss. Anna Katherine \"Annie Kate\"Keane, Miss. Nora AFleming, Miss. MargaretPenasco y Castellana, Mrs. Victor de Satode (Maria Josefa Perez de Soto y Vallejo)Francatelli, Miss. Laura MabelHays, Miss. Margaret BechsteinRyerson, Miss. Emily BorieLahtinen, Mrs. William (Anna Sylfven)Nilsson, Miss. Helmina JosefinaKantor, Mrs. Sinai (Miriam Sternin)Wick, Miss. Mary NatalieSpedden, Mrs. Frederic Oakley (Margaretta Corning Stone)Slayter, Miss. Hilda MaryCaldwell, Mrs. Albert Francis (Sylvia Mae Harbaugh)Young, Miss. Marie GriceBall, Mrs. (Ada E Hall)Goldsmith, Mrs. Frank John (Emily Alice Brown)Hippach, Miss. Jean GertrudeMcCoy, Miss. AgnesFrauenthal, Mrs. Henry William (Clara Heinsheimer)Burns, Miss. Elizabeth MargaretFortune, Miss. Alice ElizabethBrown, Miss. Amelia \"Mildred\"Smith, Miss. Marion ElsieDavison, Mrs. Thomas Henry (Mary E Finck)Bowerman, Miss. Elsie EdithFunk, Miss. Annie ClemmerMcGovern, Miss. MaryMockler, Miss. Helen Mary \"Ellie\"Barbara, Mrs. (Catherine David)Warren, Mrs. Frank Manley (Anna Sophia Atkinson)Moussa, Mrs. (Mantoura Boulos)Jermyn, Miss. AnnieAubart, Mme. Leontine PaulinePalsson, Miss. Stina ViolaMeyer, Mrs. Edgar Joseph (Leila Saks)Landergren, Miss. Aurora AdeliaBidois, Miss. RosalieNakid, Miss. Maria (\"Mary\")Holverson, Mrs. Alexander Oskar (Mary Aline Towner)Buss, Miss. KateLehmann, Miss. BerthaNewell, Miss. MarjorieSandstrom, Mrs. Hjalmar (Agnes Charlotta Bengtsson)Olsson, Miss. ElinaTrout, Mrs. William H (Jessie L)Jussila, Miss. Mari AinaOreskovic, Miss. MarijaLefebre, Miss. IdaMinahan, Miss. Daisy EMeek, Mrs. Thomas (Annie Louise Rowley)Drew, Mrs. James Vivian (Lulu Thorne Christian)Silven, Miss. Lyyli KaroliinaVan Impe, Miss. CatharinaDanbom, Mrs. Ernst Gilbert (Anna Sigrid Maria Brogren)Clarke, Mrs. Charles V (Ada Maria Winfield)Phillips, Miss. Kate Florence (\"Mrs Kate Louise Phillips Marshall\")Thorneycroft, Mrs. Percival (Florence Kate White)Louch, Mrs. Charles Alexander (Alice Adelaide Slow)Carter, Miss. Lucile PolkFord, Miss. Doolina Margaret \"Daisy\"Richards, Mrs. Sidney (Emily Hocking)Hart, Mrs. Benjamin (Esther Ada Bloomfield)Reynaldo, Ms. EncarnacionMellinger, Miss. Madeleine VioletBaclini, Miss. Marie CatherineKenyon, Mrs. Frederick R (Marion)Toomey, Miss. EllenBaclini, Miss. Helene BarbaraWest, Mrs. Edwy Arthur (Ada Mary Worth)Jerwan, Mrs. Amin S (Marie Marthe Thuillard)Strandberg, Miss. Ida SofiaHirvonen, Miss. Hildur ETurkula, Mrs. (Hedwig)Lefebre, Miss. JeannieHoyt, Mrs. Frederick Maxfield (Jane Anne Forby)Eustis, Miss. Elizabeth MusseyAllison, Mrs. Hudson J C (Bessie Waldo Daniels)Canavan, Miss. MaryO'Sullivan, Miss. Bridget MaryLaitinen, Miss. Kristina SofiaMaioni, Miss. RobertaQuick, Mrs. Frederick Charles (Jane Richards)Rothschild, Mrs. Martin (Elizabeth L. Barrett)Lemore, Mrs. (Amelia Milley)Angle, Mrs. William A (Florence \"Mary\" Agnes Hughes)Perreault, Miss. AnneHippach, Mrs. Louis Albert (Ida Sophia Fischer)Ridsdale, Miss. LucyQuick, Miss. Phyllis MayPeter, Mrs. Catherine (Catherine Rizk)Cacic, Miss. MarijaHart, Miss. Eva MiriamLeRoy, Miss. BerthaFrolicher, Miss. Hedwig MargarithaCrosby, Miss. Harriet RAndersson, Miss. Ingeborg ConstanziaAndersson, Miss. Sigrid ElisabethBeane, Mrs. Edward (Ethel Clarke)Ohman, Miss. VelinDuff Gordon, Lady. (Lucille Christiana Sutherland) (\"Mrs Morgan\")Taussig, Mrs. Emil (Tillie Mandelbaum)de Messemaeker, Mrs. Guillaume Joseph (Emma)Meanwell, Miss. (Marion Ogden)Palsson, Mrs. Nils (Alma Cornelia Berglund)Appleton, Mrs. Edward Dale (Charlotte Lamson)Kelly, Miss. MaryGarside, Miss. EthelSilvey, Mrs. William Baird (Alice Munger)Caram, Mrs. Joseph (Maria Elias)Christy, Miss. Julie RachelThayer, Mrs. John Borland (Marian Longstreth Morris)Taussig, Miss. RuthStephenson, Mrs. Walter Bertram (Martha Eustis)Bourke, Miss. MaryLeitch, Miss. Jessie WillsJacobsohn, Mrs. Sidney Samuel (Amy Frances Christy)Laroche, Mrs. Joseph (Juliette Marie Louise Lafargue)Shutes, Miss. Elizabeth WAndersson, Mrs. Anders Johan (Alfrida Konstantia Brogren)Murphy, Miss. Margaret JaneHerman, Miss. AliceLobb, Mrs. William Arthur (Cordelia K Stanlick)Becker, Miss. Marion LouiseLongley, Miss. Gretchen FiskeSkoog, Miss. MabelDavis, Miss. MaryPanula, Mrs. Juha (Maria Emilia Ojala)Sagesser, Mlle. EmmaSkoog, Miss. Margit ElizabethBaclini, Miss. EugenieStanley, Miss. Amy Zillah ElsieDoling, Miss. ElsieO'Leary, Miss. Hanora \"Norah\"Hegarty, Miss. Hanora \"Nora\"Bourke, Mrs. John (Catherine)Taylor, Mrs. Elmer Zebley (Juliet Cummins Wright)Brown, Mrs. Thomas William Solomon (Elizabeth Catherine Ford)Turja, Miss. Anna SofiaGoodwin, Mrs. Frederick (Augusta Tyler)Peters, Miss. KatieMadill, Miss. Georgette AlexandraKarun, Miss. MancaMullens, Miss. Katherine \"Katie\"Astor, Mrs. John Jacob (Madeleine Talmadge Force)Barbara, Miss. SaiideKelly, Mrs. Florence \"Fannie\"Cleaver, Miss. AliceMayne, Mlle. Berthe Antonine (\"Mrs de Villiers\")Endres, Miss. Caroline LouiseTroutt, Miss. Edwina Celia \"Winnie\"Harper, Miss. Annie Jessie \"Nina\"Renouf, Mrs. Peter Henry (Lillian Jefferys)Mannion, Miss. MargarethIlmakangas, Miss. Pieta SofiaAllen, Miss. Elisabeth WaltonFord, Mrs. Edward (Margaret Ann Watson)Ryerson, Miss. Susan Parker \"Suzette\"Sinkkonen, Miss. AnnaWells, Miss. JoanHerman, Mrs. Samuel (Jane Laver)Rothes, the Countess. of (Lucy Noel Martha Dyer-Edwards)Carter, Mrs. William Ernest (Lucile Polk)Hogeboom, Mrs. John C (Anna Andrews)Mangan, Miss. MaryMack, Mrs. (Mary)Hocking, Mrs. Elizabeth (Eliza Needs)Emanuel, Miss. Virginia EthelRobert, Mrs. Edward Scott (Elisabeth Walton McMillan)Ayoub, Miss. BanouraDick, Mrs. Albert Adrian (Vera Gillespie)Sjoblom, Miss. Anna SofiaSage, Miss. Stella AnnaLeader, Dr. Alice (Farnham)Osman, Mrs. MaraVan Impe, Mrs. Jean Baptiste (Rosalie Paula Govaert)Collyer, Mrs. Harvey (Charlotte Annie Tate)Pettersson, Miss. Ellen NataliaChambers, Mrs. Norman Campbell (Bertha Griggs)Andersson, Miss. Ebba Iris AlfridaHeininen, Miss. Wendla MariaHays, Mrs. Charles Melville (Clara Jennings Gregg)Moor, Mrs. (Beila)Stone, Mrs. George Nelson (Martha Evelyn)Yasbeck, Mrs. Antoni (Selini Alexander)Compton, Miss. Sara RebeccaSerepeca, Miss. AugustaGoldenberg, Mrs. Samuel L (Edwiga Grabowska)Boulos, Miss. NourelainLines, Miss. Mary ConoverCarter, Mrs. Ernest Courtenay (Lilian Hughes)Aks, Mrs. Sam (Leah Rosen)Wick, Mrs. George Dennick (Mary Hitchcock)Baclini, Mrs. Solomon (Latifa Qurban)Swift, Mrs. Frederick Joel (Margaret Welles Barron)Sage, Miss. Dorothy Edith \"Dolly\"Bystrom, Mrs. (Karolina)Duran y More, Miss. AsuncionBeckwith, Mrs. Richard Leonard (Sallie Monypeny)Abelson, Mrs. Samuel (Hannah Wizosky)Najib, Miss. Adele Kiamie \"Jane\"Potter, Mrs. Thomas Jr (Lily Alexenia Wilson)Shelley, Mrs. William (Imanita Parrish Hall)Dahlberg, Miss. Gerda UlrikaRice, Mrs. William (Margaret Norton)Graham, Miss. Margaret EdithJohnston, Miss. Catherine Helen \"Carrie\"' to numeric",
      "\nThe above exception was the direct cause of the following exception:\n",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[81], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m df2\u001b[38;5;241m.\u001b[39mgroupby(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mGender\u001b[39m\u001b[38;5;124m'\u001b[39m)\u001b[38;5;241m.\u001b[39mmean()\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\groupby\\groupby.py:2459\u001b[0m, in \u001b[0;36mGroupBy.mean\u001b[1;34m(self, numeric_only, engine, engine_kwargs)\u001b[0m\n\u001b[0;32m   2452\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_numba_agg_general(\n\u001b[0;32m   2453\u001b[0m         grouped_mean,\n\u001b[0;32m   2454\u001b[0m         executor\u001b[38;5;241m.\u001b[39mfloat_dtype_mapping,\n\u001b[0;32m   2455\u001b[0m         engine_kwargs,\n\u001b[0;32m   2456\u001b[0m         min_periods\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m0\u001b[39m,\n\u001b[0;32m   2457\u001b[0m     )\n\u001b[0;32m   2458\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m-> 2459\u001b[0m     result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_cython_agg_general(\n\u001b[0;32m   2460\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmean\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m   2461\u001b[0m         alt\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mlambda\u001b[39;00m x: Series(x, copy\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\u001b[38;5;241m.\u001b[39mmean(numeric_only\u001b[38;5;241m=\u001b[39mnumeric_only),\n\u001b[0;32m   2462\u001b[0m         numeric_only\u001b[38;5;241m=\u001b[39mnumeric_only,\n\u001b[0;32m   2463\u001b[0m     )\n\u001b[0;32m   2464\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m result\u001b[38;5;241m.\u001b[39m__finalize__(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mobj, method\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgroupby\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\groupby\\groupby.py:2005\u001b[0m, in \u001b[0;36mGroupBy._cython_agg_general\u001b[1;34m(self, how, alt, numeric_only, min_count, **kwargs)\u001b[0m\n\u001b[0;32m   2002\u001b[0m     result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_agg_py_fallback(how, values, ndim\u001b[38;5;241m=\u001b[39mdata\u001b[38;5;241m.\u001b[39mndim, alt\u001b[38;5;241m=\u001b[39malt)\n\u001b[0;32m   2003\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m result\n\u001b[1;32m-> 2005\u001b[0m new_mgr \u001b[38;5;241m=\u001b[39m data\u001b[38;5;241m.\u001b[39mgrouped_reduce(array_func)\n\u001b[0;32m   2006\u001b[0m res \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_wrap_agged_manager(new_mgr)\n\u001b[0;32m   2007\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m how \u001b[38;5;129;01min\u001b[39;00m [\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124midxmin\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124midxmax\u001b[39m\u001b[38;5;124m\"\u001b[39m]:\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\internals\\managers.py:1488\u001b[0m, in \u001b[0;36mBlockManager.grouped_reduce\u001b[1;34m(self, func)\u001b[0m\n\u001b[0;32m   1484\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m blk\u001b[38;5;241m.\u001b[39mis_object:\n\u001b[0;32m   1485\u001b[0m     \u001b[38;5;66;03m# split on object-dtype blocks bc some columns may raise\u001b[39;00m\n\u001b[0;32m   1486\u001b[0m     \u001b[38;5;66;03m#  while others do not.\u001b[39;00m\n\u001b[0;32m   1487\u001b[0m     \u001b[38;5;28;01mfor\u001b[39;00m sb \u001b[38;5;129;01min\u001b[39;00m blk\u001b[38;5;241m.\u001b[39m_split():\n\u001b[1;32m-> 1488\u001b[0m         applied \u001b[38;5;241m=\u001b[39m sb\u001b[38;5;241m.\u001b[39mapply(func)\n\u001b[0;32m   1489\u001b[0m         result_blocks \u001b[38;5;241m=\u001b[39m extend_blocks(applied, result_blocks)\n\u001b[0;32m   1490\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\internals\\blocks.py:395\u001b[0m, in \u001b[0;36mBlock.apply\u001b[1;34m(self, func, **kwargs)\u001b[0m\n\u001b[0;32m    389\u001b[0m \u001b[38;5;129m@final\u001b[39m\n\u001b[0;32m    390\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mapply\u001b[39m(\u001b[38;5;28mself\u001b[39m, func, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m \u001b[38;5;28mlist\u001b[39m[Block]:\n\u001b[0;32m    391\u001b[0m \u001b[38;5;250m    \u001b[39m\u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m    392\u001b[0m \u001b[38;5;124;03m    apply the function to my values; return a block if we are not\u001b[39;00m\n\u001b[0;32m    393\u001b[0m \u001b[38;5;124;03m    one\u001b[39;00m\n\u001b[0;32m    394\u001b[0m \u001b[38;5;124;03m    \"\"\"\u001b[39;00m\n\u001b[1;32m--> 395\u001b[0m     result \u001b[38;5;241m=\u001b[39m func(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mvalues, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[0;32m    397\u001b[0m     result \u001b[38;5;241m=\u001b[39m maybe_coerce_values(result)\n\u001b[0;32m    398\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_split_op_result(result)\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\groupby\\groupby.py:2002\u001b[0m, in \u001b[0;36mGroupBy._cython_agg_general.<locals>.array_func\u001b[1;34m(values)\u001b[0m\n\u001b[0;32m   1999\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m result\n\u001b[0;32m   2001\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m alt \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[1;32m-> 2002\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_agg_py_fallback(how, values, ndim\u001b[38;5;241m=\u001b[39mdata\u001b[38;5;241m.\u001b[39mndim, alt\u001b[38;5;241m=\u001b[39malt)\n\u001b[0;32m   2003\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m result\n",
      "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\groupby\\groupby.py:1948\u001b[0m, in \u001b[0;36mGroupBy._agg_py_fallback\u001b[1;34m(self, how, values, ndim, alt)\u001b[0m\n\u001b[0;32m   1946\u001b[0m     msg \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124magg function failed [how->\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mhow\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m,dtype->\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mser\u001b[38;5;241m.\u001b[39mdtype\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m]\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m   1947\u001b[0m     \u001b[38;5;66;03m# preserve the kind of exception that raised\u001b[39;00m\n\u001b[1;32m-> 1948\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;28mtype\u001b[39m(err)(msg) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01merr\u001b[39;00m\n\u001b[0;32m   1950\u001b[0m dtype \u001b[38;5;241m=\u001b[39m ser\u001b[38;5;241m.\u001b[39mdtype\n\u001b[0;32m   1951\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m dtype \u001b[38;5;241m==\u001b[39m \u001b[38;5;28mobject\u001b[39m:\n",
      "\u001b[1;31mTypeError\u001b[0m: agg function failed [how->mean,dtype->object]"
     ]
    }
   ],
   "source": [
    "df2.groupby('Gender').mean() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "3fc7d80e-363f-4dcd-8ca8-6db91b1e5294",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q16</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Gender</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3.539613</td>\n",
       "      <td>3.249120</td>\n",
       "      <td>2.868838</td>\n",
       "      <td>3.014085</td>\n",
       "      <td>2.954225</td>\n",
       "      <td>2.674296</td>\n",
       "      <td>3.069542</td>\n",
       "      <td>3.073063</td>\n",
       "      <td>3.071303</td>\n",
       "      <td>2.841549</td>\n",
       "      <td>...</td>\n",
       "      <td>3.848592</td>\n",
       "      <td>3.537852</td>\n",
       "      <td>3.876761</td>\n",
       "      <td>3.375880</td>\n",
       "      <td>3.345951</td>\n",
       "      <td>2.519366</td>\n",
       "      <td>3.125088</td>\n",
       "      <td>2.945863</td>\n",
       "      <td>3.565933</td>\n",
       "      <td>3.596655</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3.529785</td>\n",
       "      <td>3.352345</td>\n",
       "      <td>3.013942</td>\n",
       "      <td>3.129278</td>\n",
       "      <td>3.166033</td>\n",
       "      <td>2.970849</td>\n",
       "      <td>3.110266</td>\n",
       "      <td>3.013942</td>\n",
       "      <td>3.058302</td>\n",
       "      <td>2.941698</td>\n",
       "      <td>...</td>\n",
       "      <td>3.708492</td>\n",
       "      <td>3.484157</td>\n",
       "      <td>3.698352</td>\n",
       "      <td>3.346008</td>\n",
       "      <td>3.352345</td>\n",
       "      <td>2.754119</td>\n",
       "      <td>3.238530</td>\n",
       "      <td>3.018885</td>\n",
       "      <td>3.519899</td>\n",
       "      <td>3.517617</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>2 rows × 25 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "              Q1        Q2        Q3        Q4        Q5        Q6        Q7  \\\n",
       "Gender                                                                         \n",
       "0       3.539613  3.249120  2.868838  3.014085  2.954225  2.674296  3.069542   \n",
       "1       3.529785  3.352345  3.013942  3.129278  3.166033  2.970849  3.110266   \n",
       "\n",
       "              Q8        Q9       Q10  ...       Q16       Q17       Q18  \\\n",
       "Gender                                ...                                 \n",
       "0       3.073063  3.071303  2.841549  ...  3.848592  3.537852  3.876761   \n",
       "1       3.013942  3.058302  2.941698  ...  3.708492  3.484157  3.698352   \n",
       "\n",
       "             Q19       Q20       EDU        BF        BM  Happiness     Peace  \n",
       "Gender                                                                         \n",
       "0       3.375880  3.345951  2.519366  3.125088  2.945863   3.565933  3.596655  \n",
       "1       3.346008  3.352345  2.754119  3.238530  3.018885   3.519899  3.517617  \n",
       "\n",
       "[2 rows x 25 columns]"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.groupby('Gender').mean(numeric_only=True) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 197,
   "id": "bbb32e2e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Gender1</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3.596655</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3.517617</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Peace\n",
       "Gender1          \n",
       "0        3.596655\n",
       "1        3.517617"
      ]
     },
     "execution_count": 197,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.groupby('Gender1')[['Peace']].mean() # 특정변수의 평균값 확인"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "id": "dc4fe38d",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\MEDIA-CAM2\\AppData\\Local\\Temp\\ipykernel_5812\\316032338.py:1: FutureWarning: The provided callable <built-in function min> is currently using SeriesGroupBy.min. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string \"min\" instead.\n",
      "  df.groupby('Gender1')[['Peace']].agg([min,max,sum]) # 특정 변수의 최소,최대,합계 확인\n",
      "C:\\Users\\MEDIA-CAM2\\AppData\\Local\\Temp\\ipykernel_5812\\316032338.py:1: FutureWarning: The provided callable <built-in function max> is currently using SeriesGroupBy.max. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string \"max\" instead.\n",
      "  df.groupby('Gender1')[['Peace']].agg([min,max,sum]) # 특정 변수의 최소,최대,합계 확인\n",
      "C:\\Users\\MEDIA-CAM2\\AppData\\Local\\Temp\\ipykernel_5812\\316032338.py:1: FutureWarning: The provided callable <built-in function sum> is currently using SeriesGroupBy.sum. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string \"sum\" instead.\n",
      "  df.groupby('Gender1')[['Peace']].agg([min,max,sum]) # 특정 변수의 최소,최대,합계 확인\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th colspan=\"3\" halign=\"left\">Peace</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>min</th>\n",
       "      <th>max</th>\n",
       "      <th>sum</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Gender1</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1.4</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4085.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1.2</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2775.4</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Peace             \n",
       "          min  max     sum\n",
       "Gender1                   \n",
       "0         1.4  5.0  4085.8\n",
       "1         1.2  5.0  2775.4"
      ]
     },
     "execution_count": 199,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.groupby('Gender1')[['Peace']].agg([min,max,sum]) # 특정 변수의 최소,최대,합계 확인"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "f3ae732c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1925 entries, 0 to 1924\n",
      "Data columns (total 26 columns):\n",
      " #   Column     Non-Null Count  Dtype  \n",
      "---  ------     --------------  -----  \n",
      " 0   Q1         1925 non-null   int64  \n",
      " 1   Q2         1925 non-null   int64  \n",
      " 2   Q3         1925 non-null   int64  \n",
      " 3   Q4         1925 non-null   int64  \n",
      " 4   Q5         1925 non-null   int64  \n",
      " 5   Q6         1925 non-null   int64  \n",
      " 6   Q7         1925 non-null   int64  \n",
      " 7   Q8         1925 non-null   int64  \n",
      " 8   Q9         1925 non-null   int64  \n",
      " 9   Q10        1925 non-null   int64  \n",
      " 10  Q11        1925 non-null   int64  \n",
      " 11  Q12        1925 non-null   int64  \n",
      " 12  Q13        1925 non-null   int64  \n",
      " 13  Q14        1925 non-null   int64  \n",
      " 14  Q15        1925 non-null   int64  \n",
      " 15  Q16        1925 non-null   int64  \n",
      " 16  Q17        1925 non-null   int64  \n",
      " 17  Q18        1925 non-null   int64  \n",
      " 18  Q19        1925 non-null   int64  \n",
      " 19  Q20        1925 non-null   int64  \n",
      " 20  Gender     1925 non-null   int64  \n",
      " 21  EDU        1925 non-null   int64  \n",
      " 22  BF         1925 non-null   float64\n",
      " 23  BM         1925 non-null   float64\n",
      " 24  Happiness  1925 non-null   float64\n",
      " 25  Peace      1925 non-null   float64\n",
      "dtypes: float64(4), int64(22)\n",
      "memory usage: 391.1 KB\n"
     ]
    }
   ],
   "source": [
    "#(5) # 자료형 변환\n",
    "#1) float,int->category\n",
    "import pandas as pd\n",
    "df=pd.read_csv(\"c:/data/Data1.csv\")\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 205,
   "id": "f99e7a32",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['Gender']=df['Gender'].astype('category') # object->float,int # astype(\"flaot\")\n",
    "df['EDU']=df['EDU'].astype('category')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 207,
   "id": "f361b682",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1925 entries, 0 to 1924\n",
      "Data columns (total 26 columns):\n",
      " #   Column     Non-Null Count  Dtype   \n",
      "---  ------     --------------  -----   \n",
      " 0   Q1         1925 non-null   int64   \n",
      " 1   Q2         1925 non-null   int64   \n",
      " 2   Q3         1925 non-null   int64   \n",
      " 3   Q4         1925 non-null   int64   \n",
      " 4   Q5         1925 non-null   int64   \n",
      " 5   Q6         1925 non-null   int64   \n",
      " 6   Q7         1925 non-null   int64   \n",
      " 7   Q8         1925 non-null   int64   \n",
      " 8   Q9         1925 non-null   int64   \n",
      " 9   Q10        1925 non-null   int64   \n",
      " 10  Q11        1925 non-null   int64   \n",
      " 11  Q12        1925 non-null   int64   \n",
      " 12  Q13        1925 non-null   int64   \n",
      " 13  Q14        1925 non-null   int64   \n",
      " 14  Q15        1925 non-null   int64   \n",
      " 15  Q16        1925 non-null   int64   \n",
      " 16  Q17        1925 non-null   int64   \n",
      " 17  Q18        1925 non-null   int64   \n",
      " 18  Q19        1925 non-null   int64   \n",
      " 19  Q20        1925 non-null   int64   \n",
      " 20  Gender1    1925 non-null   category\n",
      " 21  EDU1       1925 non-null   category\n",
      " 22  BF         1925 non-null   float64 \n",
      " 23  BM         1925 non-null   float64 \n",
      " 24  Happiness  1925 non-null   float64 \n",
      " 25  Peace      1925 non-null   float64 \n",
      "dtypes: category(2), float64(4), int64(20)\n",
      "memory usage: 365.1 KB\n"
     ]
    }
   ],
   "source": [
    "df.info() # 데이터 타입 변경을 확인"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "id": "98b1bc99",
   "metadata": {},
   "outputs": [],
   "source": [
    "#2) 시리즈를 데이터 프레임으로 변경\n",
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/airquality.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "2978b587-d594-4c53-8419-ad30f82795e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.read_csv('c:/data/Data1.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "c782c068-69e4-465c-a699-6308ae434c02",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1925 entries, 0 to 1924\n",
      "Data columns (total 26 columns):\n",
      " #   Column     Non-Null Count  Dtype  \n",
      "---  ------     --------------  -----  \n",
      " 0   Q1         1925 non-null   int64  \n",
      " 1   Q2         1925 non-null   int64  \n",
      " 2   Q3         1925 non-null   int64  \n",
      " 3   Q4         1925 non-null   int64  \n",
      " 4   Q5         1925 non-null   int64  \n",
      " 5   Q6         1925 non-null   int64  \n",
      " 6   Q7         1925 non-null   int64  \n",
      " 7   Q8         1925 non-null   int64  \n",
      " 8   Q9         1925 non-null   int64  \n",
      " 9   Q10        1925 non-null   int64  \n",
      " 10  Q11        1925 non-null   int64  \n",
      " 11  Q12        1925 non-null   int64  \n",
      " 12  Q13        1925 non-null   int64  \n",
      " 13  Q14        1925 non-null   int64  \n",
      " 14  Q15        1925 non-null   int64  \n",
      " 15  Q16        1925 non-null   int64  \n",
      " 16  Q17        1925 non-null   int64  \n",
      " 17  Q18        1925 non-null   int64  \n",
      " 18  Q19        1925 non-null   int64  \n",
      " 19  Q20        1925 non-null   int64  \n",
      " 20  Gender     1925 non-null   int64  \n",
      " 21  EDU        1925 non-null   int64  \n",
      " 22  BF         1925 non-null   float64\n",
      " 23  BM         1925 non-null   float64\n",
      " 24  Happiness  1925 non-null   float64\n",
      " 25  Peace      1925 non-null   float64\n",
      "dtypes: float64(4), int64(22)\n",
      "memory usage: 391.1 KB\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Q1</th>\n",
       "      <th>Q2</th>\n",
       "      <th>Q3</th>\n",
       "      <th>Q4</th>\n",
       "      <th>Q5</th>\n",
       "      <th>Q6</th>\n",
       "      <th>Q7</th>\n",
       "      <th>Q8</th>\n",
       "      <th>Q9</th>\n",
       "      <th>Q10</th>\n",
       "      <th>...</th>\n",
       "      <th>Q16</th>\n",
       "      <th>Q17</th>\n",
       "      <th>Q18</th>\n",
       "      <th>Q19</th>\n",
       "      <th>Q20</th>\n",
       "      <th>EDU</th>\n",
       "      <th>BF</th>\n",
       "      <th>BM</th>\n",
       "      <th>Happiness</th>\n",
       "      <th>Peace</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Gender</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3.539613</td>\n",
       "      <td>3.249120</td>\n",
       "      <td>2.868838</td>\n",
       "      <td>3.014085</td>\n",
       "      <td>2.954225</td>\n",
       "      <td>2.674296</td>\n",
       "      <td>3.069542</td>\n",
       "      <td>3.073063</td>\n",
       "      <td>3.071303</td>\n",
       "      <td>2.841549</td>\n",
       "      <td>...</td>\n",
       "      <td>3.848592</td>\n",
       "      <td>3.537852</td>\n",
       "      <td>3.876761</td>\n",
       "      <td>3.375880</td>\n",
       "      <td>3.345951</td>\n",
       "      <td>2.519366</td>\n",
       "      <td>3.125088</td>\n",
       "      <td>2.945863</td>\n",
       "      <td>3.565933</td>\n",
       "      <td>3.596655</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3.529785</td>\n",
       "      <td>3.352345</td>\n",
       "      <td>3.013942</td>\n",
       "      <td>3.129278</td>\n",
       "      <td>3.166033</td>\n",
       "      <td>2.970849</td>\n",
       "      <td>3.110266</td>\n",
       "      <td>3.013942</td>\n",
       "      <td>3.058302</td>\n",
       "      <td>2.941698</td>\n",
       "      <td>...</td>\n",
       "      <td>3.708492</td>\n",
       "      <td>3.484157</td>\n",
       "      <td>3.698352</td>\n",
       "      <td>3.346008</td>\n",
       "      <td>3.352345</td>\n",
       "      <td>2.754119</td>\n",
       "      <td>3.238530</td>\n",
       "      <td>3.018885</td>\n",
       "      <td>3.519899</td>\n",
       "      <td>3.517617</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>2 rows × 25 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "              Q1        Q2        Q3        Q4        Q5        Q6        Q7  \\\n",
       "Gender                                                                         \n",
       "0       3.539613  3.249120  2.868838  3.014085  2.954225  2.674296  3.069542   \n",
       "1       3.529785  3.352345  3.013942  3.129278  3.166033  2.970849  3.110266   \n",
       "\n",
       "              Q8        Q9       Q10  ...       Q16       Q17       Q18  \\\n",
       "Gender                                ...                                 \n",
       "0       3.073063  3.071303  2.841549  ...  3.848592  3.537852  3.876761   \n",
       "1       3.013942  3.058302  2.941698  ...  3.708492  3.484157  3.698352   \n",
       "\n",
       "             Q19       Q20       EDU        BF        BM  Happiness     Peace  \n",
       "Gender                                                                         \n",
       "0       3.375880  3.345951  2.519366  3.125088  2.945863   3.565933  3.596655  \n",
       "1       3.346008  3.352345  2.754119  3.238530  3.018885   3.519899  3.517617  \n",
       "\n",
       "[2 rows x 25 columns]"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.info()\n",
    "df.groupby('Gender').mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "7b328aa9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>41.0</td>\n",
       "      <td>190.0</td>\n",
       "      <td>7.4</td>\n",
       "      <td>67</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>36.0</td>\n",
       "      <td>118.0</td>\n",
       "      <td>8.0</td>\n",
       "      <td>72</td>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12.0</td>\n",
       "      <td>149.0</td>\n",
       "      <td>12.6</td>\n",
       "      <td>74</td>\n",
       "      <td>5</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>18.0</td>\n",
       "      <td>313.0</td>\n",
       "      <td>11.5</td>\n",
       "      <td>62</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>14.3</td>\n",
       "      <td>56</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>28.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>14.9</td>\n",
       "      <td>66</td>\n",
       "      <td>5</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>23.0</td>\n",
       "      <td>299.0</td>\n",
       "      <td>8.6</td>\n",
       "      <td>65</td>\n",
       "      <td>5</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>19.0</td>\n",
       "      <td>99.0</td>\n",
       "      <td>13.8</td>\n",
       "      <td>59</td>\n",
       "      <td>5</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>8.0</td>\n",
       "      <td>19.0</td>\n",
       "      <td>20.1</td>\n",
       "      <td>61</td>\n",
       "      <td>5</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>NaN</td>\n",
       "      <td>194.0</td>\n",
       "      <td>8.6</td>\n",
       "      <td>69</td>\n",
       "      <td>5</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Ozone  Solar.R  Wind  Temp  Month  Day\n",
       "0   41.0    190.0   7.4    67      5    1\n",
       "1   36.0    118.0   8.0    72      5    2\n",
       "2   12.0    149.0  12.6    74      5    3\n",
       "3   18.0    313.0  11.5    62      5    4\n",
       "4    NaN      NaN  14.3    56      5    5\n",
       "5   28.0      NaN  14.9    66      5    6\n",
       "6   23.0    299.0   8.6    65      5    7\n",
       "7   19.0     99.0  13.8    59      5    8\n",
       "8    8.0     19.0  20.1    61      5    9\n",
       "9    NaN    194.0   8.6    69      5   10"
      ]
     },
     "execution_count": 93,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "46d9a361",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Month  Day\n",
       "5      1       7.4\n",
       "       2       8.0\n",
       "       3      12.6\n",
       "Name: Wind, dtype: float64"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1=df.groupby(['Month','Day'])['Wind'].mean() # 특정컬럼 평균\n",
    "df1.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "2fae6599",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(df1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "b0d56064",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>Wind</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"3\" valign=\"top\">5</th>\n",
       "      <th>1</th>\n",
       "      <td>7.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>12.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           Wind\n",
       "Month Day      \n",
       "5     1     7.4\n",
       "      2     8.0\n",
       "      3    12.6"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# pd.DataFrame(시리즈 변수명)\n",
    "df1=pd.DataFrame(df1)\n",
    "df1.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "c4bc911a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.frame.DataFrame"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(df1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6bbee22-f29d-426b-90aa-10d95c3b2aa5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "86018877",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "      <th>Wind</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>7.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>5</td>\n",
       "      <td>3</td>\n",
       "      <td>12.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Month  Day  Wind\n",
       "0      5    1   7.4\n",
       "1      5    2   8.0\n",
       "2      5    3  12.6"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# groupby( ),reset_index() 함수\n",
    "# 기존 행 인덱스를 제거하고 인덱스를 데이터 열로 추가\n",
    "df2=df.groupby(['Month','Day'])['Wind'].mean().reset_index()\n",
    "df2.head(3)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "id": "13a013e6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>41.0</td>\n",
       "      <td>190.0</td>\n",
       "      <td>7.4</td>\n",
       "      <td>67</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>36.0</td>\n",
       "      <td>118.0</td>\n",
       "      <td>8.0</td>\n",
       "      <td>72</td>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12.0</td>\n",
       "      <td>149.0</td>\n",
       "      <td>12.6</td>\n",
       "      <td>74</td>\n",
       "      <td>5</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>18.0</td>\n",
       "      <td>313.0</td>\n",
       "      <td>11.5</td>\n",
       "      <td>62</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>14.3</td>\n",
       "      <td>56</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Ozone  Solar.R  Wind  Temp  Month  Day\n",
       "0   41.0    190.0   7.4    67      5    1\n",
       "1   36.0    118.0   8.0    72      5    2\n",
       "2   12.0    149.0  12.6    74      5    3\n",
       "3   18.0    313.0  11.5    62      5    4\n",
       "4    NaN      NaN  14.3    56      5    5"
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 4장 결측치 처리와 이상값 검색\n",
    "# (1) isna(),isnull()= 결측치 확인, fillna()=결측치 대체,dropna()=결측치 삭제,drop() 열 또는 행 삭제\n",
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/airquality.csv')\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "ab2bb849",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>True</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Ozone  Solar.R   Wind   Temp  Month    Day\n",
       "0  False    False  False  False  False  False\n",
       "1  False    False  False  False  False  False\n",
       "2  False    False  False  False  False  False\n",
       "3  False    False  False  False  False  False\n",
       "4   True     True  False  False  False  False"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 결측값(NaN)은 True 반환한다\n",
    "df.isna().head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "id": "7b86fd72",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Ozone      37\n",
       "Solar.R     7\n",
       "Wind        0\n",
       "Temp        0\n",
       "Month       0\n",
       "Day         0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1) 결측치의 갯수\n",
    "df.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "25a141d7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Ozone      0\n",
       "Solar.R    0\n",
       "Wind       0\n",
       "Temp       0\n",
       "Month      0\n",
       "Day        0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2) 열변수의 평균값으로 결측치를 대체\n",
    "# 데이터프레임 변수명.fillna()\n",
    "df1=df.fillna(df.median()) # 열변수의 평균값으로 결측치를 대체\n",
    "df1.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12c78da8-8cbe-4edd-b464-8110561de743",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "63fddbae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>42.129310</td>\n",
       "      <td>185.931507</td>\n",
       "      <td>9.957516</td>\n",
       "      <td>77.882353</td>\n",
       "      <td>6.993464</td>\n",
       "      <td>15.803922</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>28.693372</td>\n",
       "      <td>87.960267</td>\n",
       "      <td>3.523001</td>\n",
       "      <td>9.465270</td>\n",
       "      <td>1.416522</td>\n",
       "      <td>8.864520</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>7.000000</td>\n",
       "      <td>1.700000</td>\n",
       "      <td>56.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>21.000000</td>\n",
       "      <td>120.000000</td>\n",
       "      <td>7.400000</td>\n",
       "      <td>72.000000</td>\n",
       "      <td>6.000000</td>\n",
       "      <td>8.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>42.129310</td>\n",
       "      <td>194.000000</td>\n",
       "      <td>9.700000</td>\n",
       "      <td>79.000000</td>\n",
       "      <td>7.000000</td>\n",
       "      <td>16.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>46.000000</td>\n",
       "      <td>256.000000</td>\n",
       "      <td>11.500000</td>\n",
       "      <td>85.000000</td>\n",
       "      <td>8.000000</td>\n",
       "      <td>23.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>168.000000</td>\n",
       "      <td>334.000000</td>\n",
       "      <td>20.700000</td>\n",
       "      <td>97.000000</td>\n",
       "      <td>9.000000</td>\n",
       "      <td>31.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Ozone     Solar.R        Wind        Temp       Month         Day\n",
       "count  153.000000  153.000000  153.000000  153.000000  153.000000  153.000000\n",
       "mean    42.129310  185.931507    9.957516   77.882353    6.993464   15.803922\n",
       "std     28.693372   87.960267    3.523001    9.465270    1.416522    8.864520\n",
       "min      1.000000    7.000000    1.700000   56.000000    5.000000    1.000000\n",
       "25%     21.000000  120.000000    7.400000   72.000000    6.000000    8.000000\n",
       "50%     42.129310  194.000000    9.700000   79.000000    7.000000   16.000000\n",
       "75%     46.000000  256.000000   11.500000   85.000000    8.000000   23.000000\n",
       "max    168.000000  334.000000   20.700000   97.000000    9.000000   31.000000"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "5959887b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>116.000000</td>\n",
       "      <td>146.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>42.129310</td>\n",
       "      <td>185.931507</td>\n",
       "      <td>9.957516</td>\n",
       "      <td>77.882353</td>\n",
       "      <td>6.993464</td>\n",
       "      <td>15.803922</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>32.987885</td>\n",
       "      <td>90.058422</td>\n",
       "      <td>3.523001</td>\n",
       "      <td>9.465270</td>\n",
       "      <td>1.416522</td>\n",
       "      <td>8.864520</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>7.000000</td>\n",
       "      <td>1.700000</td>\n",
       "      <td>56.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>18.000000</td>\n",
       "      <td>115.750000</td>\n",
       "      <td>7.400000</td>\n",
       "      <td>72.000000</td>\n",
       "      <td>6.000000</td>\n",
       "      <td>8.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>31.500000</td>\n",
       "      <td>205.000000</td>\n",
       "      <td>9.700000</td>\n",
       "      <td>79.000000</td>\n",
       "      <td>7.000000</td>\n",
       "      <td>16.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>63.250000</td>\n",
       "      <td>258.750000</td>\n",
       "      <td>11.500000</td>\n",
       "      <td>85.000000</td>\n",
       "      <td>8.000000</td>\n",
       "      <td>23.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>168.000000</td>\n",
       "      <td>334.000000</td>\n",
       "      <td>20.700000</td>\n",
       "      <td>97.000000</td>\n",
       "      <td>9.000000</td>\n",
       "      <td>31.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Ozone     Solar.R        Wind        Temp       Month         Day\n",
       "count  116.000000  146.000000  153.000000  153.000000  153.000000  153.000000\n",
       "mean    42.129310  185.931507    9.957516   77.882353    6.993464   15.803922\n",
       "std     32.987885   90.058422    3.523001    9.465270    1.416522    8.864520\n",
       "min      1.000000    7.000000    1.700000   56.000000    5.000000    1.000000\n",
       "25%     18.000000  115.750000    7.400000   72.000000    6.000000    8.000000\n",
       "50%     31.500000  205.000000    9.700000   79.000000    7.000000   16.000000\n",
       "75%     63.250000  258.750000   11.500000   85.000000    8.000000   23.000000\n",
       "max    168.000000  334.000000   20.700000   97.000000    9.000000   31.000000"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c076ad55-7372-4ec1-b5da-d8dadef705f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/airquality.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "e240d19e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3) 특정 변수(Ozone)의 평균값으로 대체\n",
    "df2=df.fillna((df['Ozone']).mean())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7031153e-f547-4702-b347-be2fe3a3327b",
   "metadata": {},
   "outputs": [],
   "source": [
    "df2.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "id": "88cc4417-4705-4c39-80a3-ee1dd9e9df89",
   "metadata": {},
   "outputs": [],
   "source": [
    "df1=pd.read_csv('c:/data/titanic.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "id": "b3c73254-9900-4e03-8712-e8066c0ee368",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 891 entries, 0 to 890\n",
      "Data columns (total 12 columns):\n",
      " #   Column       Non-Null Count  Dtype  \n",
      "---  ------       --------------  -----  \n",
      " 0   PassengerId  891 non-null    int64  \n",
      " 1   Survived     891 non-null    int64  \n",
      " 2   Pclass       891 non-null    int64  \n",
      " 3   Name         891 non-null    object \n",
      " 4   Gender       891 non-null    object \n",
      " 5   Age          714 non-null    float64\n",
      " 6   SibSp        891 non-null    int64  \n",
      " 7   Parch        891 non-null    int64  \n",
      " 8   Ticket       891 non-null    object \n",
      " 9   Fare         891 non-null    float64\n",
      " 10  Cabin        204 non-null    object \n",
      " 11  Embarked     889 non-null    object \n",
      "dtypes: float64(2), int64(5), object(5)\n",
      "memory usage: 83.7+ KB\n"
     ]
    }
   ],
   "source": [
    "df1.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc9168f5-8e80-49f9-9885-ebe2a42799a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "df1['Cabin']=df1.fillna(df1['Cabin'].mode())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "id": "f4193990-b364-4807-b70c-f66393377cfd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'B96 B98'"
      ]
     },
     "execution_count": 123,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1['Cabin'].mode()[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "id": "1385c018-47c7-4ed2-b232-d253baf12b65",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0        B96 B98\n",
       "1    C23 C25 C27\n",
       "2             G6\n",
       "Name: Cabin, dtype: object"
      ]
     },
     "execution_count": 125,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1['Cabin'].mode()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "70f211c5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "      <td>153.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>42.129310</td>\n",
       "      <td>179.352321</td>\n",
       "      <td>9.957516</td>\n",
       "      <td>77.882353</td>\n",
       "      <td>6.993464</td>\n",
       "      <td>15.803922</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>28.693372</td>\n",
       "      <td>92.982600</td>\n",
       "      <td>3.523001</td>\n",
       "      <td>9.465270</td>\n",
       "      <td>1.416522</td>\n",
       "      <td>8.864520</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>7.000000</td>\n",
       "      <td>1.700000</td>\n",
       "      <td>56.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>21.000000</td>\n",
       "      <td>95.000000</td>\n",
       "      <td>7.400000</td>\n",
       "      <td>72.000000</td>\n",
       "      <td>6.000000</td>\n",
       "      <td>8.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>42.129310</td>\n",
       "      <td>194.000000</td>\n",
       "      <td>9.700000</td>\n",
       "      <td>79.000000</td>\n",
       "      <td>7.000000</td>\n",
       "      <td>16.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>46.000000</td>\n",
       "      <td>256.000000</td>\n",
       "      <td>11.500000</td>\n",
       "      <td>85.000000</td>\n",
       "      <td>8.000000</td>\n",
       "      <td>23.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>168.000000</td>\n",
       "      <td>334.000000</td>\n",
       "      <td>20.700000</td>\n",
       "      <td>97.000000</td>\n",
       "      <td>9.000000</td>\n",
       "      <td>31.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Ozone     Solar.R        Wind        Temp       Month         Day\n",
       "count  153.000000  153.000000  153.000000  153.000000  153.000000  153.000000\n",
       "mean    42.129310  179.352321    9.957516   77.882353    6.993464   15.803922\n",
       "std     28.693372   92.982600    3.523001    9.465270    1.416522    8.864520\n",
       "min      1.000000    7.000000    1.700000   56.000000    5.000000    1.000000\n",
       "25%     21.000000   95.000000    7.400000   72.000000    6.000000    8.000000\n",
       "50%     42.129310  194.000000    9.700000   79.000000    7.000000   16.000000\n",
       "75%     46.000000  256.000000   11.500000   85.000000    8.000000   23.000000\n",
       "max    168.000000  334.000000   20.700000   97.000000    9.000000   31.000000"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "825000f7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "      <th>Ozone_na</th>\n",
       "      <th>ratio</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>41.0</td>\n",
       "      <td>190.0</td>\n",
       "      <td>7.4</td>\n",
       "      <td>67</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>NaN</td>\n",
       "      <td>0.110448</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>36.0</td>\n",
       "      <td>118.0</td>\n",
       "      <td>8.0</td>\n",
       "      <td>72</td>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>NaN</td>\n",
       "      <td>0.111111</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12.0</td>\n",
       "      <td>149.0</td>\n",
       "      <td>12.6</td>\n",
       "      <td>74</td>\n",
       "      <td>5</td>\n",
       "      <td>3</td>\n",
       "      <td>NaN</td>\n",
       "      <td>0.170270</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Ozone  Solar.R  Wind  Temp  Month  Day  Ozone_na     ratio\n",
       "0   41.0    190.0   7.4    67      5    1       NaN  0.110448\n",
       "1   36.0    118.0   8.0    72      5    2       NaN  0.111111\n",
       "2   12.0    149.0  12.6    74      5    3       NaN  0.170270"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 4) 변수 생성 후에 결측치로 채우기\n",
    "df=pd.read_csv(\"c:/data/airquality.csv\")\n",
    "import numpy as np\n",
    "# 변수 생성 [Ozone_na]\n",
    "df['Ozone_na']=np.nan\n",
    "# 판다스 DataFrame에서 새로운 컬럼을 만들 때 하나의 값만 넣으면, 그 값이 모든 행에 자동으로 채워지기 때문\n",
    "df.head(3)\n",
    "# 시리즈 개념을 통해 파생변수 생성\n",
    "df['ratio']=(df['Wind']/df['Temp']) # Wind/Temp 비율 변수 생성\n",
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "933e8897",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Ozone      0\n",
       "Solar.R    0\n",
       "Wind       0\n",
       "Temp       0\n",
       "Month      0\n",
       "Day        0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 5) 결측치 삭제하기,dropna()\n",
    "df=pd.read_csv(\"c:/data/airquality.csv\")\n",
    "df1=df.dropna()\n",
    "df1.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "feb90f98",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(111, 6)"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1.shape  # 결측치가 있는 행은 모두 삭제"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "6eae5722",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(153, 6)"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "e608de67",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "      <th>Month</th>\n",
       "      <th>Day</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12.0</td>\n",
       "      <td>149.0</td>\n",
       "      <td>12.6</td>\n",
       "      <td>74</td>\n",
       "      <td>5</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>18.0</td>\n",
       "      <td>313.0</td>\n",
       "      <td>11.5</td>\n",
       "      <td>62</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>28.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>14.9</td>\n",
       "      <td>66</td>\n",
       "      <td>5</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>23.0</td>\n",
       "      <td>299.0</td>\n",
       "      <td>8.6</td>\n",
       "      <td>65</td>\n",
       "      <td>5</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>19.0</td>\n",
       "      <td>99.0</td>\n",
       "      <td>13.8</td>\n",
       "      <td>59</td>\n",
       "      <td>5</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Ozone  Solar.R  Wind  Temp  Month  Day\n",
       "2   12.0    149.0  12.6    74      5    3\n",
       "3   18.0    313.0  11.5    62      5    4\n",
       "5   28.0      NaN  14.9    66      5    6\n",
       "6   23.0    299.0   8.6    65      5    7\n",
       "7   19.0     99.0  13.8    59      5    8"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 6)특정 행/열 삭제, drop()\n",
    "# 행 삭제\n",
    "df.drop(index=[0,1,4]).head(5) # 행번호 기준으로 행삭제"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "f481d51c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Ozone</th>\n",
       "      <th>Solar.R</th>\n",
       "      <th>Wind</th>\n",
       "      <th>Temp</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>41.0</td>\n",
       "      <td>190.0</td>\n",
       "      <td>7.4</td>\n",
       "      <td>67</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>36.0</td>\n",
       "      <td>118.0</td>\n",
       "      <td>8.0</td>\n",
       "      <td>72</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12.0</td>\n",
       "      <td>149.0</td>\n",
       "      <td>12.6</td>\n",
       "      <td>74</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Ozone  Solar.R  Wind  Temp\n",
       "0   41.0    190.0   7.4    67\n",
       "1   36.0    118.0   8.0    72\n",
       "2   12.0    149.0  12.6    74"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 열 삭제\n",
    "df.drop(columns=['Month','Day']).head(3) # Month,Day 열변수 삭제"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "82f3d1e8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Species</th>\n",
       "      <th>Weight</th>\n",
       "      <th>Length</th>\n",
       "      <th>Diagonal</th>\n",
       "      <th>Height</th>\n",
       "      <th>Width</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Bream</td>\n",
       "      <td>242.0</td>\n",
       "      <td>25.4</td>\n",
       "      <td>30.0</td>\n",
       "      <td>11.5200</td>\n",
       "      <td>4.0200</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Bream</td>\n",
       "      <td>290.0</td>\n",
       "      <td>26.3</td>\n",
       "      <td>31.2</td>\n",
       "      <td>12.4800</td>\n",
       "      <td>4.3056</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Bream</td>\n",
       "      <td>340.0</td>\n",
       "      <td>26.5</td>\n",
       "      <td>31.1</td>\n",
       "      <td>12.3778</td>\n",
       "      <td>4.6961</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  Species  Weight  Length  Diagonal   Height   Width\n",
       "0   Bream   242.0    25.4      30.0  11.5200  4.0200\n",
       "1   Bream   290.0    26.3      31.2  12.4800  4.3056\n",
       "2   Bream   340.0    26.5      31.1  12.3778  4.6961"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#7)특정 값 변경하기\n",
    "# replace(현재값, 변경값)\n",
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/fish.csv')\n",
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "ee18406f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 159 entries, 0 to 158\n",
      "Data columns (total 6 columns):\n",
      " #   Column    Non-Null Count  Dtype  \n",
      "---  ------    --------------  -----  \n",
      " 0   Species   159 non-null    object \n",
      " 1   Weight    159 non-null    float64\n",
      " 2   Length    159 non-null    float64\n",
      " 3   Diagonal  159 non-null    float64\n",
      " 4   Height    159 non-null    float64\n",
      " 5   Width     159 non-null    float64\n",
      "dtypes: float64(5), object(1)\n",
      "memory usage: 7.6+ KB\n"
     ]
    }
   ],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "2ca5adcd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Species\n",
       "Perch        56\n",
       "Bream        35\n",
       "Roach        20\n",
       "Pike         17\n",
       "Smelt        14\n",
       "Parkki       11\n",
       "Whitefish     6\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# object 타입의 종류 및 도수 확인\n",
    "df['Species'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "7db037d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 'Species'변수의 'Bream' 값을->'Br' 변경\n",
    "df['Species']=df['Species'].replace('Bream','Br')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "4048d7a0-6793-469f-a57c-9deb87392452",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Species\n",
       "Perch        56\n",
       "Br           35\n",
       "Roach        20\n",
       "Pike         17\n",
       "Smelt        14\n",
       "Parkki       11\n",
       "Whitefish     6\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['Species'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "9dd47641-fd00-4fda-80cb-4a6d0fc87120",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['Species']=df['Species'].replace({'Bream':'Br','Perch':'Pe'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "adf07e02-d267-46e5-9ee9-41fe4a688f23",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Species\n",
       "Pe           56\n",
       "Br           35\n",
       "Roach        20\n",
       "Pike         17\n",
       "Smelt        14\n",
       "Parkki       11\n",
       "Whitefish     6\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['Species'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "7d666bff-cc0b-4060-8aa2-7a1617a9a246",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 02 이상값(Outliers) 검색"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "5296109f-a8ce-4310-b05c-b0350018e120",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 상자그림(Boxplot)을 통한 이상값 확인"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "id": "eabe6f20-fda0-47d5-a1dc-a7a36cc2b2ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.read_csv('c:/data/fish.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "feeb136e-da19-4e84-8001-d007681db549",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "iris=sns.load_dataset('iris')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "ca59b23a-548c-4d33-8a94-6ff1706e7ad0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Axes: xlabel='sepal_width'>"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAhAAAAGxCAYAAAAzqI9fAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8hTgPZAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAX4klEQVR4nO3dfWyV9f3w8U9LeZxQnysO5EEUEAWZLFp0oMO4uSXTzDhDdu9m02wqzMf5jA7JYGDUqFtEIxrn02KMxjizGTELLbqhES3DIdNFQEgAcZMB08EPynX/sZvmV+XpczjtKfB6Jc3oOdfVfvrdl15vzzmlVUVRFAEAkFBd6QEAgH2PgAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIqyn1xG3btsWqVauiZ8+eUVVVVc6ZAIA2UhRFbNy4MY4++uiori79cYSSA2LVqlXRt2/fkj8xAFA5K1eujD59+pR8fskB0bNnz5YBevXqVfIAAED72bBhQ/Tt27flOl6qkgNi+9MWvXr1EhAAsI/Z25cfeBElAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkFZT6QGgPX300Uexfv36So9xwKmtrY26urpKjwGUkYDggPHRRx/F//nB/40t/7O50qMccDp36RpPPvG4iID9iIDggLF+/frY8j+b4z8Dx8a2brWVHiciIqr/86/ovmxe/GfAmNjW/eBKj9Mmqjetj1jaGOvXrxcQsB8REBxwtnWrjW1fOrzSY7SyrfvBHW4mgF3xIkoAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiD20KZNm+L999+PTZs2VXoUgH2S76P7FwGxh1asWBE/+clPYsWKFZUeBWCf5Pvo/kVAAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANJqKj3A/9bc3ByLFi2KTz75JA499NAYPnx4dOrUqdJjAdCBlPNa0RGvOx1xph3pMAExb968mDVrVqxZs6bltqOOOiomTpwYY8aMqeBkAHQU5bxWdMTrTkecaWc6xFMY8+bNiylTpsTAgQPj/vvvjz/84Q9x//33x8CBA2PKlCkxb968So8IQIWV81rREa87HXGmXal4QDQ3N8esWbOivr4+pk2bFsOGDYsePXrEsGHDYtq0aVFfXx8PPPBANDc3V3pUACqknNeKjnjd6Ygz7c4eP4WxefPm2Lx5c8v7GzZsKMsAixYtijVr1sRtt90W1dWte6a6ujq+//3vx6RJk2LRokUxcuTIsnzOvfHhhx9WegRK5P+7yrL+7M0eKOe1oiNedzriTLuzxwExY8aMmDp1atkH+OSTTyIiYsCAATu8f/vt24+rtOnTp1d6BNgn+bvD3ijntaIjXnc64ky7s8cBcfPNN8e1117b8v6GDRuib9++ez3AoYceGhERy5Yti2HDhn3h/mXLlrU6rtImT54c/fr1q/QYlODDDz90Easgf3fYm7+D5bxWdMTrTkecaXf2OCC6du0aXbt2LfsAw4cPj6OOOiqeeuqpmDZtWquHbrZt2xZPPfVU9O7dO4YPH172z12Kfv36xfHHH1/pMWCf4+8Oe6Oc14qOeN3piDPtTsVfRNmpU6eYOHFizJ8/P2699dZYvHhxfPbZZ7F48eK49dZbY/78+XH55Zd3yJ+BBaB9lPNa0RGvOx1xpt3pEP8OxJgxY2Lq1Kkxa9asmDRpUsvtvXv3jqlTp3a4n30FoP2V81rREa87HXGmXekQARHx34U7/fTT94l/fQuAyijntaIjXnc64kw702ECIuK/D+F0lB9PAaBjKue1oiNedzriTDtS8ddAAAD7HgEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAmIPHXPMMfHQQw/FMcccU+lRAPZJvo/uX2oqPcC+olu3bnH88cdXegyAfZbvo/sXj0AAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACAtJpKDwDtrXrT+kqP0KL6P/9q9b/7o4603kD5CAgOGLW1tdG5S9eIpY2VHuULui+bV+kR2lTnLl2jtra20mMAZSQgOGDU1dXFk088HuvX+y/i9lZbWxt1dXWVHgMoIwHBAaWurs6FDKAMvIgSAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagAAA0gQEAJAmIACANAEBAKQJCAAgTUAAAGkCAgBIExAAQJqAAADSBAQAkCYgAIA0AQEApAkIACBNQAAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASKsp9cSiKCIiYsOGDWUbBgBoW9uv29uv46UqOSA2btwYERF9+/bdqwEAgPa3cePGqK2tLfn8qqLEBNm2bVusWrUqevbsGVVVVSUP8HkbNmyIvn37xsqVK6NXr15l+7jsmnWvDOteGda9Mqx7ZXx+3YuiiI0bN8bRRx8d1dWlv5Kh5Ecgqquro0+fPiV/4t3p1auXDVYB1r0yrHtlWPfKsO6V8b/XfW8eedjOiygBgDQBAQCkdbiA6Nq1a0yZMiW6du1a6VEOKNa9Mqx7ZVj3yrDuldFW617yiygBgANXh3sEAgDo+AQEAJAmIACAtHYNiBkzZsRXv/rV6NmzZxx55JFx/vnnx3vvvbfb8xobG+OUU06Jbt26xcCBA+PBBx9sh2n3H6Wse0NDQ1RVVX3h7W9/+1s7Tb3ve+CBB2L48OEtP3tdX18fL7300i7Psdf3Xnbd7fW2MWPGjKiqqoqrr756l8fZ8+W1J+terj3frgHR2NgYkyZNitdffz1eeeWV2Lp1a5xzzjnx6aef7vScZcuWxbe+9a342te+Fk1NTXHLLbfElVdeGc8991w7Tr5vK2Xdt3vvvfdi9erVLW/HHXdcO0y8f+jTp0/MnDkzFixYEAsWLIivf/3rcd5558XixYt3eLy9Xh7Zdd/OXi+fN998Mx566KEYPnz4Lo+z58trT9d9u73e80UFrV27toiIorGxcafH3HDDDcWQIUNa3XbppZcWp512WluPt9/ak3WfO3duERHFunXr2m+wA8AhhxxSPPzwwzu8z15vO7tad3u9vDZu3Fgcd9xxxSuvvFKMHTu2uOqqq3Z6rD1fPpl1L9eer+hrINavXx8REYceeuhOj5k/f36cc845rW77xje+EQsWLIgtW7a06Xz7qz1Z9+1GjhwZvXv3jnHjxsXcuXPberT9VnNzczz99NPx6aefRn19/Q6PsdfLb0/WfTt7vTwmTZoU3/72t+Pss8/e7bH2fPlk1n27vd3zJf8ujL1VFEVce+21ccYZZ8SJJ5640+PWrFkTdXV1rW6rq6uLrVu3xj/+8Y/o3bt3W4+6X9nTde/du3c89NBDccopp8TmzZvjiSeeiHHjxkVDQ0OMGTOmHSfet73zzjtRX18fmzZtioMOOiief/75OOGEE3Z4rL1ePpl1t9fL5+mnn46333473nzzzT063p4vj+y6l2vPVywgfvrTn8aiRYvitdde2+2xn/9tn8X//7evyvlbQA8Ue7rugwcPjsGDB7e8X19fHytXroy77rrLN9WEwYMHx8KFC+Nf//pXPPfcczFhwoRobGzc6cXMXi+PzLrb6+WxcuXKuOqqq2LOnDnRrVu3PT7Pnt87pax7ufZ8RZ7CuOKKK+J3v/tdzJ07d7e/0fOoo46KNWvWtLpt7dq1UVNTE4cddlhbjrnfyaz7jpx22mnx97//vQ0m23916dIlBg0aFKNGjYoZM2bEiBEj4r777tvhsfZ6+WTWfUfs9by33nor1q5dG6ecckrU1NRETU1NNDY2xq9+9auoqamJ5ubmL5xjz++9UtZ9R0rZ8+36CERRFHHFFVfE888/Hw0NDTFgwIDdnlNfXx8vvvhiq9vmzJkTo0aNis6dO7fVqPuVUtZ9R5qamjykuJeKoojNmzfv8D57ve3sat13xF7PGzduXLzzzjutbvvRj34UQ4YMiRtvvDE6der0hXPs+b1XyrrvSEl7fq9egpl0+eWXF7W1tUVDQ0OxevXqlrfPPvus5Zibbrqp+MEPftDy/tKlS4sePXoU11xzTfHuu+8WjzzySNG5c+fi2Wefbc/R92mlrPs999xTPP/888X7779f/PWvfy1uuummIiKK5557rhJfwj7p5ptvLubNm1csW7asWLRoUXHLLbcU1dXVxZw5c4qisNfbSnbd7fW28/mfBrDn28fu1r1ce75dAyIidvj26KOPthwzYcKEYuzYsa3Oa2hoKEaOHFl06dKl6N+/f/HAAw+059j7vFLW/Y477iiOPfbYolu3bsUhhxxSnHHGGcXvf//79h9+H3bxxRcX/fr1K7p06VIcccQRxbhx41ouYkVhr7eV7Lrb623n8xcye7597G7dy7Xn/TZOACDN78IAANIEBACQJiAAgDQBAQCkCQgAIE1AAABpAgIASBMQAECagIAD1A9/+MM4//zzy/5xf/Ob38TBBx+8y2Nuv/32OPnkk3d5zPLly6OqqioWLlxYttmA8hEQQFlddNFF8f7776fOaauYAdpOu/42TmD/17179+jevXulxwDamEcgoEKeffbZOOmkk6J79+5x2GGHxdlnnx2ffvppREQ8+uijMXTo0OjWrVsMGTIkZs2a1XLe9of2n3766Rg9enR069Ythg0bFg0NDS3HNDc3xyWXXBIDBgyI7t27x+DBg+O+++4rac4XX3wxDj744Ni2bVtERCxcuDCqqqri+uuvbznm0ksvjfHjx0fEjp/CmDlzZtTV1UXPnj3jkksuiU2bNrXcd/vtt8djjz0WL7zwQlRVVUVVVVWrr2Xp0qVx1llnRY8ePWLEiBExf/78kr4OoLwEBFTA6tWrY/z48XHxxRfHkiVLoqGhIb773e9GURQxe/bsmDx5ckyfPj2WLFkSv/zlL+O2226Lxx57rNXHuP766+NnP/tZNDU1xejRo+M73/lO/POf/4yIiG3btkWfPn3imWeeiXfffTd+/vOfxy233BLPPPNMetYxY8bExo0bo6mpKSIiGhsb4/DDD4/GxsaWYxoaGmLs2LE7PP+ZZ56JKVOmxPTp02PBggXRu3fvVkF03XXXxfe+97345je/GatXr47Vq1fH6NGjW+6fPHlyXHfddbFw4cI4/vjjY/z48bF169b01wGU2d7+2lAg76233ioioli+fPkX7uvbt2/x29/+ttVtv/jFL4r6+vqiKIpi2bJlRUQUM2fObLl/y5YtRZ8+fYo77rhjp59z4sSJxQUXXNDy/oQJE4rzzjtvj+b9yle+Utx1111FURTF+eefX0yfPr3o0qVLsWHDhmL16tVFRBRLliwpiqIoHn300aK2trbl3Pr6+uKyyy5r9fFOPfXUYsSIEbucZfvX+fDDD7fctnjx4lafC6gcj0BABYwYMSLGjRsXJ510Ulx44YUxe/bsWLduXXz88cexcuXKuOSSS+Kggw5qeZs2bVp88MEHrT5GfX19y59rampi1KhRsWTJkpbbHnzwwRg1alQcccQRcdBBB8Xs2bNjxYoVJc175plnRkNDQxRFEa+++mqcd955ceKJJ8Zrr70Wc+fOjbq6uhgyZMgOz12yZEmrWT8/++4MHz685c+9e/eOiIi1a9eW8FUA5eRFlFABnTp1ildeeSX+/Oc/x5w5c+LXv/51TJ48OV588cWIiJg9e3aceuqpXzhnd6qqqiLiv08bXHPNNXH33XdHfX199OzZM+6888544403Spr3zDPPjEceeST+8pe/RHV1dZxwwgkxduzYaGxsjHXr1u306Yty6Ny5c8uft39921+PAVSORyCgQqqqquL000+PqVOnRlNTU3Tp0iX+9Kc/xZe//OVYunRpDBo0qNXbgAEDWp3/+uuvt/x569at8dZbb7U8CvDqq6/G6NGjY+LEiTFy5MgYNGjQFx7ByNj+Ooh77703xo4dG1VVVTF27NhoaGjY5esfIiKGDh3aatbPzx4R0aVLl2hubi55PqD9eQQCKuCNN96IP/7xj3HOOefEkUceGW+88UZ8/PHHMXTo0Lj99tvjyiuvjF69esW5554bmzdvjgULFsS6devi2muvbfkY999/fxx33HExdOjQuOeee2LdunVx8cUXR0TEoEGD4vHHH4+XX345BgwYEE888US8+eabX4iQPVVbWxsnn3xyPPnkky0/zTFmzJi48MILY8uWLXHmmWfu9NyrrroqJkyYEKNGjYozzjgjnnrqqVi8eHEMHDiw5Zj+/fvHyy+/HO+9914cdthhUVtbW9KcQPsREFABvXr1innz5sW9994bGzZsiH79+sXdd98d5557bkRE9OjRI+6888644YYb4ktf+lKcdNJJcfXVV7f6GDNnzow77rgjmpqa4thjj40XXnghDj/88IiIuOyyy2LhwoVx0UUXRVVVVYwfPz4mTpwYL730Uskzn3XWWfH222+3xMIhhxwSJ5xwQqxatSqGDh260/Muuuii+OCDD+LGG2+MTZs2xQUXXBCXX355vPzyyy3H/PjHP46GhoYYNWpU/Pvf/465c+dG//79S54VaHtVRVEUlR4C2HPLly+PAQMGRFNT027/OWiAtuI1EABAmoCAA9yKFSta/cjo599K/dFPYP/mKQw4wG3dujWWL1++0/v79+8fNTVeLgW0JiAAgDRPYQAAaQICAEgTEABAmoAAANIEBACQJiAAgDQBAQCkCQgAIO3/AXknJ8KsAlecAAAAAElFTkSuQmCC",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.boxplot(x=iris['sepal_width'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "b4ac88be-40c8-4c3d-8ae5-0ae738b264e9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       sepal_width\n",
      "count   150.000000\n",
      "mean      3.057333\n",
      "std       0.435866\n",
      "min       2.000000\n",
      "25%       2.800000\n",
      "50%       3.000000\n",
      "75%       3.300000\n",
      "max       4.400000\n"
     ]
    }
   ],
   "source": [
    "stats=pd.DataFrame(iris['sepal_width'].describe())\n",
    "print(stats)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "id": "4672f864-7ede-43a8-abab-3885a067ba4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.read_csv('c:/data/fish.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "id": "59421180-55cc-49d0-9886-316bf2bc5607",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 159 entries, 0 to 158\n",
      "Data columns (total 6 columns):\n",
      " #   Column    Non-Null Count  Dtype  \n",
      "---  ------    --------------  -----  \n",
      " 0   Species   159 non-null    object \n",
      " 1   Weight    159 non-null    float64\n",
      " 2   Length    159 non-null    float64\n",
      " 3   Diagonal  159 non-null    float64\n",
      " 4   Height    159 non-null    float64\n",
      " 5   Width     159 non-null    float64\n",
      "dtypes: float64(5), object(1)\n",
      "memory usage: 7.6+ KB\n"
     ]
    }
   ],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "id": "dca76f0b-b1e5-488d-9abc-dbc01e0c8a7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "Q1=df['Weight'].quantile(0.25) # 1사분위수 \n",
    "Q3=df['Weight'].quantile(0.75) # 3사분위수\n",
    "IQR=Q3 - Q1  # 사분위수 범위"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "03c7f716-8ccf-4d33-8f7a-66345b08440c",
   "metadata": {},
   "outputs": [],
   "source": [
    "lower_bound=Q1 - 1.5 * IQR\n",
    "upper_bound=Q3 + 1.5 * IQR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "c7309dea-2656-4aa0-9dd5-a4888acc9f0e",
   "metadata": {},
   "outputs": [],
   "source": [
    " outliers=df[(df['Weight']< lower_bound)|\n",
    "             (df['Weight'] > upper_bound)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "id": "41f0f42a-4a8f-4b88-a5ad-acccdb614466",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Species  Weight  Length  Diagonal  Height  Width\n",
      "142    Pike  1600.0    60.0      64.0   9.600  6.144\n",
      "143    Pike  1550.0    60.0      64.0   9.600  6.144\n",
      "144    Pike  1650.0    63.4      68.0  10.812  7.480\n"
     ]
    }
   ],
   "source": [
    "print(outliers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58a33776-98ae-4f7a-962e-d008b688a655",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 02 Z score 이상치 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "id": "24b85e24-a57f-4d53-b454-625396191902",
   "metadata": {},
   "outputs": [],
   "source": [
    "# sepal_width의 평균과 표준편차 계산\n",
    "mean = df['Weight'].mean()\n",
    "std = df['Weight'].std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "id": "47f2e5c2-635f-48bd-be4b-7a1a090f445b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# z-score 계산\n",
    "df['z_score'] = (df['Weight'] - mean) / std\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "43503bb8-7bed-4544-9f66-d3527a9d1164",
   "metadata": {},
   "outputs": [],
   "source": [
    "outliers = df[abs(df['z_score']) > 1.96]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b967c524-334f-4a10-8b9d-c4cc4525b09f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# z_score < -1.96 또는 z_score > 1.96"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "id": "de6bf549-6986-46df-bf24-8cbda06ade48",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Species  Weight  Length  Diagonal   Height   Width   z_score\n",
      "123   Perch  1100.0    42.0      44.6  12.8002  6.8684  1.960101\n",
      "125   Perch  1100.0    43.0      45.5  12.5125  7.4165  1.960101\n",
      "141    Pike  1250.0    56.0      59.7  10.6863  6.9849  2.379121\n",
      "142    Pike  1600.0    60.0      64.0   9.6000  6.1440  3.356833\n",
      "143    Pike  1550.0    60.0      64.0   9.6000  6.1440  3.217160\n",
      "144    Pike  1650.0    63.4      68.0  10.8120  7.4800  3.496507\n"
     ]
    }
   ],
   "source": [
    "print(outliers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9e69ac8-de98-47eb-9f86-4fa055e771a9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0ee4c82e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3장 scikit-learn \n",
    "# 머신러닝을 위한 파이썬 패키지다.\n",
    "# scikit-learn 패키지의 장점은 다양한 머신러닝 모형을 하나의 패키지에서 모두 제공\n",
    "# 내장 데이터셋 생성\n",
    "# 전처리(스케일링)\n",
    "# 지도학습(Supervised Learning):작업형 2유형에 해당\n",
    "# 학습데이터를 바탕으로 일반화된 모델을 만들어 의사결정 프로세스 생성\n",
    "# 분류(Classification) : 입력받은 데이터를 특정 카테고리 중 하나로 분류해내는 문제,binary/multi class\n",
    "# 회귀(Regression) : 입력받은 데이터에 따라 특정 필드의 수치를 맞히는 문제\n",
    "# 비지도학습\n",
    "# 하이퍼파라미터 최적화 등을 제공"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "bb5c477a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (1) 분류 모형 분석 프로세스 순서\n",
    "# 1) 데이터 불러오기 \n",
    "# 2) 데이터 전처리 과정(스케일링,박스콕스변환,결측치 처리,파생변수생성)\n",
    "# 3) 데이터 분할: 학습데이터와 평가데이터 분할\n",
    "# 4) 머신러닝 모델 적용 및 예측\n",
    "# 5) 모델 평가(roc_auc,macro-f1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "e1a16e53",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1) 데이터 불러오기\n",
    "import sklearn\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.datasets import load_iris\n",
    "iris=load_iris()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "c86f3311",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 분석 데이터셋 소개\n",
    "# 아이리스(붓꽃) 데이터에 대한 데이터이다. \n",
    "# 꽃잎의 각 부분의 너비와 길이등을 측정한 데이터이며 150개의 레코드로 구성\n",
    "# Sepal Length : 꽃받침의 길이\n",
    "# Sepal Width : 꽃받침의 너비\n",
    "# Petal Length : 꽃잎의 길이\n",
    "# Petal Width : 꽃잎의 너비\n",
    "# Species : 꽃의 종류,setosa(0) / versicolor(1) / virginica(2) 의 3종류\n",
    "# 분류모형에서 multi class(다범주 분류) 해당됨"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "27a45328",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['DESCR',\n",
       " 'data',\n",
       " 'data_module',\n",
       " 'feature_names',\n",
       " 'filename',\n",
       " 'frame',\n",
       " 'target',\n",
       " 'target_names']"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# dir()은 파이썬에 내장되어 있는 함수로 객체의 속성 목록 확인\n",
    "dir(iris)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "51d701c6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['sepal length (cm)',\n",
       " 'sepal width (cm)',\n",
       " 'petal length (cm)',\n",
       " 'petal width (cm)']"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 독립변수명 확인\n",
    "iris.feature_names"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "54a3a551",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 독립변수의 데이터 값 확인\n",
    "#iris.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "25f7482d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['setosa', 'versicolor', 'virginica'], dtype='<U10')"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 종속변수(목표)명 확인\n",
    "iris.target_names"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "3fa9a7ec",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n",
       "       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n",
       "       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 종속변수(목표)명 데이터 값 확인\n",
    "iris.target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "96cc1a3f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>sepal length (cm)</th>\n",
       "      <th>sepal width (cm)</th>\n",
       "      <th>petal length (cm)</th>\n",
       "      <th>petal width (cm)</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5.1</td>\n",
       "      <td>3.5</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.9</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.7</td>\n",
       "      <td>3.2</td>\n",
       "      <td>1.3</td>\n",
       "      <td>0.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4.6</td>\n",
       "      <td>3.1</td>\n",
       "      <td>1.5</td>\n",
       "      <td>0.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5.0</td>\n",
       "      <td>3.6</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)\n",
       "0                5.1               3.5                1.4               0.2\n",
       "1                4.9               3.0                1.4               0.2\n",
       "2                4.7               3.2                1.3               0.2\n",
       "3                4.6               3.1                1.5               0.2\n",
       "4                5.0               3.6                1.4               0.2"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 데이터프레임 생성(독립변수)\n",
    "iris_df=pd.DataFrame(data=iris.data,columns=iris.feature_names)\n",
    "iris_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "755db3e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# iris_df에 종속변수(목표) 추가\n",
    "iris_df['species']=iris.target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "10a44b5a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>sepal length (cm)</th>\n",
       "      <th>sepal width (cm)</th>\n",
       "      <th>petal length (cm)</th>\n",
       "      <th>petal width (cm)</th>\n",
       "      <th>species</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5.1</td>\n",
       "      <td>3.5</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.9</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.7</td>\n",
       "      <td>3.2</td>\n",
       "      <td>1.3</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \\\n",
       "0                5.1               3.5                1.4               0.2   \n",
       "1                4.9               3.0                1.4               0.2   \n",
       "2                4.7               3.2                1.3               0.2   \n",
       "\n",
       "   species  \n",
       "0        0  \n",
       "1        0  \n",
       "2        0  "
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 분석 데이터셋 확인\n",
    "iris_df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "id": "8b2daa0c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 독립변수명에서 cm 수정\n",
    "iris_df=iris_df.rename(columns={'sepal length (cm)':'sepal length',\n",
    "                        'sepal width (cm)':'sepal width',\n",
    "                        'petal length (cm)':'petal length',\n",
    "                        'petal width (cm)':'petal width '})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "25f612eb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>sepal length</th>\n",
       "      <th>sepal width</th>\n",
       "      <th>petal length</th>\n",
       "      <th>petal width</th>\n",
       "      <th>species</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5.1</td>\n",
       "      <td>3.5</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.9</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.7</td>\n",
       "      <td>3.2</td>\n",
       "      <td>1.3</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   sepal length  sepal width  petal length  petal width   species\n",
       "0           5.1          3.5           1.4           0.2        0\n",
       "1           4.9          3.0           1.4           0.2        0\n",
       "2           4.7          3.2           1.3           0.2        0"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "iris_df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "8ce25ca7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2) 데이터 분할(학습데이터:평가데이터)\n",
    "# 사이킷런에서 지원하는 model_selection에서 train,test 함수 제공\n",
    "# 빅데이터 분석기사 실기시험에서는 train/test 분리 되어 있음\n",
    "# 학습데이터와 평가데이터 분할 비율은 7:3 or 6:4 일반적인 비율로 분할\n",
    "# x_train(학습데이터),x_test(평가데이터),y_train(목표변수 학습데이터),\n",
    "# y_test(목표변수 평가데이터)\n",
    "# 빅데이터 분석기사 실기시험에서는 y_test 값을 제출하는 유형\n",
    "# train_test_split() 함수는 3개 정보만 입력한다.\n",
    "# 독립변수 데이터(X)와 종속변수 레이블(Y),평가 데이터로 분리할 비율\n",
    "# 분석결과 동일하게 하기 위한 random_state=(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "67e33674",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>sepal length</th>\n",
       "      <th>sepal width</th>\n",
       "      <th>petal length</th>\n",
       "      <th>petal width</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5.1</td>\n",
       "      <td>3.5</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.9</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.7</td>\n",
       "      <td>3.2</td>\n",
       "      <td>1.3</td>\n",
       "      <td>0.2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   sepal length  sepal width  petal length  petal width \n",
       "0           5.1          3.5           1.4           0.2\n",
       "1           4.9          3.0           1.4           0.2\n",
       "2           4.7          3.2           1.3           0.2"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 독립변수와 종속변수(목표) 데이터 셋을 분리\n",
    "X=iris_df.iloc[:,0:4]\n",
    "X.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "e2e9b260",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>species</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   species\n",
       "0        0\n",
       "1        0\n",
       "2        0"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Y=iris_df[[\"species\"]]\n",
    "Y.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "id": "4f4b0512",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 데이터 분할 train(70):test(30)\n",
    "from sklearn.model_selection import train_test_split\n",
    "x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.3,random_state=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "304b4aa6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     sepal length  sepal width  petal length  petal width \n",
      "126           6.2          2.8           4.8           1.8\n",
      "61            5.9          3.0           4.2           1.5\n",
      "124           6.7          3.3           5.7           2.1\n"
     ]
    }
   ],
   "source": [
    "# x_train,y_train,x_test,y_test 확인\n",
    "# 학습 데이터 독립변수\n",
    "print(x_train.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "5dd69e11",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     species\n",
      "126        2\n",
      "61         1\n",
      "124        2\n"
     ]
    }
   ],
   "source": [
    "# 학습 데이터 종속변수\n",
    "print(y_train.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "912c27ab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     sepal length  sepal width  petal length  petal width \n",
      "82            5.8          2.7           3.9           1.2\n",
      "134           6.1          2.6           5.6           1.4\n",
      "114           5.8          2.8           5.1           2.4\n"
     ]
    }
   ],
   "source": [
    "# 평가 데이터 독립변수\n",
    "print(x_test.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "0370a17c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     species\n",
      "82         1\n",
      "134        2\n",
      "114        2\n"
     ]
    }
   ],
   "source": [
    "# 평가 데이터 종속변수\n",
    "print(y_test.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "51c8fd88",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(105, 4) (105, 1)\n",
      "(45, 4) (45, 1)\n"
     ]
    }
   ],
   "source": [
    "# 학습데이터(70%),평가데이터(30%) 분할 확인\n",
    "print(x_train.shape,y_train.shape)\n",
    "print(x_test.shape,y_test.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "5eaddac3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3) 머신러닝 모델 적용 \n",
    "# 분류모형 구축\n",
    "# from sklearn.모듈 import 모델함수\n",
    "# 모듈(module)이란 하나의 파이썬 파일(.py 파일)을 의미\n",
    "# 패키지(package)란 이러한 모듈들이 여러 개 모여있는 것을 의미"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "9ccc7ed4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 의사결정나무(decsion tree) 모형 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "id": "9827b96c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#① tree 모듈에서 제공하는 DecisionTreeClassfier 함수를 가져온다.\n",
    "from sklearn.tree import DecisionTreeClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "id": "8a4d67f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "#② 의사결정나무 분류분석을 수행할 모델(model) 만든다.\n",
    "model=DecisionTreeClassifier()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "id": "ea073690",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-1 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-1 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-1 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-1 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-1 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-1 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>DecisionTreeClassifier()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;DecisionTreeClassifier<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.tree.DecisionTreeClassifier.html\">?<span>Documentation for DecisionTreeClassifier</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>DecisionTreeClassifier()</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "DecisionTreeClassifier()"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#③ 생성할 모델에 x_train,y_train에 의사결정나무 분류 모형을 학습\n",
    "model.fit(x_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "id": "e9928df0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 2, 0, 2, 2, 0, 2, 0, 1, 1, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 2,\n",
       "       0, 1, 1, 2, 1, 1, 1, 2, 0, 1, 1, 0, 1, 0, 0, 2, 0, 2, 2, 1, 0, 0,\n",
       "       1])"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#④ 학습한 모델에 x_test를 전달하여 y_test 예측한다.\n",
    "y_test_predicted=model.predict(x_test)\n",
    "y_test_predicted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "id": "e917e79d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4) 모델 평가\n",
    "# 분류 모델의 평가지표 ROC_AUC(roc_auc_score),정확도(accuracy_score)\n",
    "# 정밀도(precision_score),재현율(recall_score)\n",
    "# 분류모형 평가지표를 계산하기 위해 metrics 모듈의 함수를 가져온다.\n",
    "from sklearn.metrics import roc_auc_score\n",
    "from sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "id": "cf74de09",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9555555555555556\n"
     ]
    }
   ],
   "source": [
    "print(accuracy_score(y_test,y_test_predicted))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "id": "43b4d88d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "id": "c26eef19",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[15,  0,  0],\n",
       "       [ 0, 14,  2],\n",
       "       [ 0,  0, 14]], dtype=int64)"
      ]
     },
     "execution_count": 119,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "confusion_matrix(y_test,y_test_predicted)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "id": "badaa217",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) 회귀 모형 분석 프로세스 순서\n",
    "# 1) 데이터 불러오기 \n",
    "# 2) 데이터 전처리 과정(스케일링,결측치 처리)\n",
    "# 3) 데이터 분할: 학습데이터와 평가데이터 분할\n",
    "# 4) 머신러닝 모델 적용 및 예측\n",
    "# 5) 모델 평가"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "id": "3d790586",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 데이터 소개\n",
    "# 데이터명 : Boston Housing Price (보스턴 주택 가격 데이터)\n",
    "# 레코드수 : 506 개\n",
    "# 필드개수 : 14 개\n",
    "# 주택의 가격에 영향을 미치는 요소를 분석하고자 하는 목적으로 사용\n",
    "# 목표변수 : MEDV(본인 소유의 주택가격)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "id": "6195c92b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1) 데이터 불러오기 \n",
    "import pandas as pd\n",
    "boston=pd.read_csv(\"c:/data/boston.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "id": "c583ca90",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 506 entries, 0 to 505\n",
      "Data columns (total 14 columns):\n",
      " #   Column   Non-Null Count  Dtype  \n",
      "---  ------   --------------  -----  \n",
      " 0   CRIM     506 non-null    float64\n",
      " 1   ZN       506 non-null    float64\n",
      " 2   INDUS    506 non-null    float64\n",
      " 3   CHAS     506 non-null    int64  \n",
      " 4   NOX      506 non-null    float64\n",
      " 5   RM       491 non-null    float64\n",
      " 6   AGE      506 non-null    float64\n",
      " 7   DIS      506 non-null    float64\n",
      " 8   RAD      506 non-null    int64  \n",
      " 9   TAX      506 non-null    int64  \n",
      " 10  PTRATIO  506 non-null    float64\n",
      " 11  B        506 non-null    float64\n",
      " 12  LSTAT    506 non-null    float64\n",
      " 13  MEDV     506 non-null    float64\n",
      "dtypes: float64(11), int64(3)\n",
      "memory usage: 55.5 KB\n"
     ]
    }
   ],
   "source": [
    "# 종속변수(목표): MEDV(price)\n",
    "boston.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "id": "77ab0934",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "CRIM        0\n",
       "ZN          0\n",
       "INDUS       0\n",
       "CHAS        0\n",
       "NOX         0\n",
       "RM         15\n",
       "AGE         0\n",
       "DIS         0\n",
       "RAD         0\n",
       "TAX         0\n",
       "PTRATIO     0\n",
       "B           0\n",
       "LSTAT       0\n",
       "MEDV        0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 129,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2) 데이터 전처리(결측치 처리)\n",
    "boston.isna().sum() # RM 15개 결측치 확인"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "id": "d6c94be7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 결측치 제거\n",
    "boston=boston.dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "id": "1d1e9500",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "CRIM       0\n",
       "ZN         0\n",
       "INDUS      0\n",
       "CHAS       0\n",
       "NOX        0\n",
       "RM         0\n",
       "AGE        0\n",
       "DIS        0\n",
       "RAD        0\n",
       "TAX        0\n",
       "PTRATIO    0\n",
       "B          0\n",
       "LSTAT      0\n",
       "MEDV       0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 133,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 결측치 제거 확인\n",
    "boston.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "id": "21132dd1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>CRIM</th>\n",
       "      <th>ZN</th>\n",
       "      <th>INDUS</th>\n",
       "      <th>CHAS</th>\n",
       "      <th>NOX</th>\n",
       "      <th>RM</th>\n",
       "      <th>AGE</th>\n",
       "      <th>DIS</th>\n",
       "      <th>RAD</th>\n",
       "      <th>TAX</th>\n",
       "      <th>PTRATIO</th>\n",
       "      <th>B</th>\n",
       "      <th>LSTAT</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.00632</td>\n",
       "      <td>18.0</td>\n",
       "      <td>2.31</td>\n",
       "      <td>0</td>\n",
       "      <td>0.538</td>\n",
       "      <td>6.575</td>\n",
       "      <td>65.2</td>\n",
       "      <td>4.0900</td>\n",
       "      <td>1</td>\n",
       "      <td>296</td>\n",
       "      <td>15.3</td>\n",
       "      <td>396.90</td>\n",
       "      <td>4.98</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.02731</td>\n",
       "      <td>0.0</td>\n",
       "      <td>7.07</td>\n",
       "      <td>0</td>\n",
       "      <td>0.469</td>\n",
       "      <td>6.421</td>\n",
       "      <td>78.9</td>\n",
       "      <td>4.9671</td>\n",
       "      <td>2</td>\n",
       "      <td>242</td>\n",
       "      <td>17.8</td>\n",
       "      <td>396.90</td>\n",
       "      <td>9.14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.02729</td>\n",
       "      <td>0.0</td>\n",
       "      <td>7.07</td>\n",
       "      <td>0</td>\n",
       "      <td>0.469</td>\n",
       "      <td>7.185</td>\n",
       "      <td>61.1</td>\n",
       "      <td>4.9671</td>\n",
       "      <td>2</td>\n",
       "      <td>242</td>\n",
       "      <td>17.8</td>\n",
       "      <td>392.83</td>\n",
       "      <td>4.03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.03237</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2.18</td>\n",
       "      <td>0</td>\n",
       "      <td>0.458</td>\n",
       "      <td>6.998</td>\n",
       "      <td>45.8</td>\n",
       "      <td>6.0622</td>\n",
       "      <td>3</td>\n",
       "      <td>222</td>\n",
       "      <td>18.7</td>\n",
       "      <td>394.63</td>\n",
       "      <td>2.94</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.06905</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2.18</td>\n",
       "      <td>0</td>\n",
       "      <td>0.458</td>\n",
       "      <td>7.147</td>\n",
       "      <td>54.2</td>\n",
       "      <td>6.0622</td>\n",
       "      <td>3</td>\n",
       "      <td>222</td>\n",
       "      <td>18.7</td>\n",
       "      <td>396.90</td>\n",
       "      <td>5.33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>500</th>\n",
       "      <td>0.22438</td>\n",
       "      <td>0.0</td>\n",
       "      <td>9.69</td>\n",
       "      <td>0</td>\n",
       "      <td>0.585</td>\n",
       "      <td>6.027</td>\n",
       "      <td>79.7</td>\n",
       "      <td>2.4982</td>\n",
       "      <td>6</td>\n",
       "      <td>391</td>\n",
       "      <td>19.2</td>\n",
       "      <td>396.90</td>\n",
       "      <td>14.33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>501</th>\n",
       "      <td>0.06263</td>\n",
       "      <td>0.0</td>\n",
       "      <td>11.93</td>\n",
       "      <td>0</td>\n",
       "      <td>0.573</td>\n",
       "      <td>6.593</td>\n",
       "      <td>69.1</td>\n",
       "      <td>2.4786</td>\n",
       "      <td>1</td>\n",
       "      <td>273</td>\n",
       "      <td>21.0</td>\n",
       "      <td>391.99</td>\n",
       "      <td>9.67</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>503</th>\n",
       "      <td>0.06076</td>\n",
       "      <td>0.0</td>\n",
       "      <td>11.93</td>\n",
       "      <td>0</td>\n",
       "      <td>0.573</td>\n",
       "      <td>6.976</td>\n",
       "      <td>91.0</td>\n",
       "      <td>2.1675</td>\n",
       "      <td>1</td>\n",
       "      <td>273</td>\n",
       "      <td>21.0</td>\n",
       "      <td>396.90</td>\n",
       "      <td>5.64</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>504</th>\n",
       "      <td>0.10959</td>\n",
       "      <td>0.0</td>\n",
       "      <td>11.93</td>\n",
       "      <td>0</td>\n",
       "      <td>0.573</td>\n",
       "      <td>6.794</td>\n",
       "      <td>89.3</td>\n",
       "      <td>2.3889</td>\n",
       "      <td>1</td>\n",
       "      <td>273</td>\n",
       "      <td>21.0</td>\n",
       "      <td>393.45</td>\n",
       "      <td>6.48</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>505</th>\n",
       "      <td>0.04741</td>\n",
       "      <td>0.0</td>\n",
       "      <td>11.93</td>\n",
       "      <td>0</td>\n",
       "      <td>0.573</td>\n",
       "      <td>6.030</td>\n",
       "      <td>80.8</td>\n",
       "      <td>2.5050</td>\n",
       "      <td>1</td>\n",
       "      <td>273</td>\n",
       "      <td>21.0</td>\n",
       "      <td>396.90</td>\n",
       "      <td>7.88</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>491 rows × 13 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "        CRIM    ZN  INDUS  CHAS    NOX     RM   AGE     DIS  RAD  TAX  \\\n",
       "0    0.00632  18.0   2.31     0  0.538  6.575  65.2  4.0900    1  296   \n",
       "1    0.02731   0.0   7.07     0  0.469  6.421  78.9  4.9671    2  242   \n",
       "2    0.02729   0.0   7.07     0  0.469  7.185  61.1  4.9671    2  242   \n",
       "3    0.03237   0.0   2.18     0  0.458  6.998  45.8  6.0622    3  222   \n",
       "4    0.06905   0.0   2.18     0  0.458  7.147  54.2  6.0622    3  222   \n",
       "..       ...   ...    ...   ...    ...    ...   ...     ...  ...  ...   \n",
       "500  0.22438   0.0   9.69     0  0.585  6.027  79.7  2.4982    6  391   \n",
       "501  0.06263   0.0  11.93     0  0.573  6.593  69.1  2.4786    1  273   \n",
       "503  0.06076   0.0  11.93     0  0.573  6.976  91.0  2.1675    1  273   \n",
       "504  0.10959   0.0  11.93     0  0.573  6.794  89.3  2.3889    1  273   \n",
       "505  0.04741   0.0  11.93     0  0.573  6.030  80.8  2.5050    1  273   \n",
       "\n",
       "     PTRATIO       B  LSTAT  \n",
       "0       15.3  396.90   4.98  \n",
       "1       17.8  396.90   9.14  \n",
       "2       17.8  392.83   4.03  \n",
       "3       18.7  394.63   2.94  \n",
       "4       18.7  396.90   5.33  \n",
       "..       ...     ...    ...  \n",
       "500     19.2  396.90  14.33  \n",
       "501     21.0  391.99   9.67  \n",
       "503     21.0  396.90   5.64  \n",
       "504     21.0  393.45   6.48  \n",
       "505     21.0  396.90   7.88  \n",
       "\n",
       "[491 rows x 13 columns]"
      ]
     },
     "execution_count": 135,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 3) 데이터 분할: 학습데이터와 평가데이터 분할\n",
    "# 독립변수와 종속변수(목표) 데이터 셋을 분리\n",
    "X=boston.iloc[:,0:13]\n",
    "X"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "7bbdfbeb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>MEDV</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>24.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>21.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>34.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>33.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>36.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>500</th>\n",
       "      <td>16.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>501</th>\n",
       "      <td>22.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>503</th>\n",
       "      <td>23.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>504</th>\n",
       "      <td>22.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>505</th>\n",
       "      <td>11.9</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>491 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     MEDV\n",
       "0    24.0\n",
       "1    21.6\n",
       "2    34.7\n",
       "3    33.4\n",
       "4    36.2\n",
       "..    ...\n",
       "500  16.8\n",
       "501  22.4\n",
       "503  23.9\n",
       "504  22.0\n",
       "505  11.9\n",
       "\n",
       "[491 rows x 1 columns]"
      ]
     },
     "execution_count": 137,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Y=boston[[\"MEDV\"]]\n",
    "Y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "66bda1dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 학습데이터와 평가데이터 분할\n",
    "import sklearn\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.3,random_state=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "id": "6f390e4e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>CRIM</th>\n",
       "      <th>ZN</th>\n",
       "      <th>INDUS</th>\n",
       "      <th>CHAS</th>\n",
       "      <th>NOX</th>\n",
       "      <th>RM</th>\n",
       "      <th>AGE</th>\n",
       "      <th>DIS</th>\n",
       "      <th>RAD</th>\n",
       "      <th>TAX</th>\n",
       "      <th>PTRATIO</th>\n",
       "      <th>B</th>\n",
       "      <th>LSTAT</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.03237</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2.18</td>\n",
       "      <td>0</td>\n",
       "      <td>0.458</td>\n",
       "      <td>6.998</td>\n",
       "      <td>45.8</td>\n",
       "      <td>6.0622</td>\n",
       "      <td>3</td>\n",
       "      <td>222</td>\n",
       "      <td>18.7</td>\n",
       "      <td>394.63</td>\n",
       "      <td>2.94</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>220</th>\n",
       "      <td>0.35809</td>\n",
       "      <td>0.0</td>\n",
       "      <td>6.20</td>\n",
       "      <td>1</td>\n",
       "      <td>0.507</td>\n",
       "      <td>6.951</td>\n",
       "      <td>88.5</td>\n",
       "      <td>2.8617</td>\n",
       "      <td>8</td>\n",
       "      <td>307</td>\n",
       "      <td>17.4</td>\n",
       "      <td>391.70</td>\n",
       "      <td>9.71</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>445</th>\n",
       "      <td>10.67180</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.10</td>\n",
       "      <td>0</td>\n",
       "      <td>0.740</td>\n",
       "      <td>6.459</td>\n",
       "      <td>94.8</td>\n",
       "      <td>1.9879</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>43.06</td>\n",
       "      <td>23.98</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         CRIM   ZN  INDUS  CHAS    NOX     RM   AGE     DIS  RAD  TAX  \\\n",
       "3     0.03237  0.0   2.18     0  0.458  6.998  45.8  6.0622    3  222   \n",
       "220   0.35809  0.0   6.20     1  0.507  6.951  88.5  2.8617    8  307   \n",
       "445  10.67180  0.0  18.10     0  0.740  6.459  94.8  1.9879   24  666   \n",
       "\n",
       "     PTRATIO       B  LSTAT  \n",
       "3       18.7  394.63   2.94  \n",
       "220     17.4  391.70   9.71  \n",
       "445     20.2   43.06  23.98  "
      ]
     },
     "execution_count": 141,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_train.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "id": "00568f05",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>MEDV</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>33.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>220</th>\n",
       "      <td>26.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>445</th>\n",
       "      <td>11.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     MEDV\n",
       "3    33.4\n",
       "220  26.7\n",
       "445  11.8"
      ]
     },
     "execution_count": 143,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_train.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "id": "4fd195df",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>CRIM</th>\n",
       "      <th>ZN</th>\n",
       "      <th>INDUS</th>\n",
       "      <th>CHAS</th>\n",
       "      <th>NOX</th>\n",
       "      <th>RM</th>\n",
       "      <th>AGE</th>\n",
       "      <th>DIS</th>\n",
       "      <th>RAD</th>\n",
       "      <th>TAX</th>\n",
       "      <th>PTRATIO</th>\n",
       "      <th>B</th>\n",
       "      <th>LSTAT</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>247</th>\n",
       "      <td>0.19657</td>\n",
       "      <td>22.0</td>\n",
       "      <td>5.86</td>\n",
       "      <td>0</td>\n",
       "      <td>0.431</td>\n",
       "      <td>6.226</td>\n",
       "      <td>79.2</td>\n",
       "      <td>8.0555</td>\n",
       "      <td>7</td>\n",
       "      <td>330</td>\n",
       "      <td>19.1</td>\n",
       "      <td>376.14</td>\n",
       "      <td>10.15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>454</th>\n",
       "      <td>9.51363</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.10</td>\n",
       "      <td>0</td>\n",
       "      <td>0.713</td>\n",
       "      <td>6.728</td>\n",
       "      <td>94.1</td>\n",
       "      <td>2.4961</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>6.68</td>\n",
       "      <td>18.71</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>80</th>\n",
       "      <td>0.04113</td>\n",
       "      <td>25.0</td>\n",
       "      <td>4.86</td>\n",
       "      <td>0</td>\n",
       "      <td>0.426</td>\n",
       "      <td>6.727</td>\n",
       "      <td>33.5</td>\n",
       "      <td>5.4007</td>\n",
       "      <td>4</td>\n",
       "      <td>281</td>\n",
       "      <td>19.0</td>\n",
       "      <td>396.90</td>\n",
       "      <td>5.29</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        CRIM    ZN  INDUS  CHAS    NOX     RM   AGE     DIS  RAD  TAX  \\\n",
       "247  0.19657  22.0   5.86     0  0.431  6.226  79.2  8.0555    7  330   \n",
       "454  9.51363   0.0  18.10     0  0.713  6.728  94.1  2.4961   24  666   \n",
       "80   0.04113  25.0   4.86     0  0.426  6.727  33.5  5.4007    4  281   \n",
       "\n",
       "     PTRATIO       B  LSTAT  \n",
       "247     19.1  376.14  10.15  \n",
       "454     20.2    6.68  18.71  \n",
       "80      19.0  396.90   5.29  "
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_test.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "b2d3acec",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>MEDV</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>247</th>\n",
       "      <td>20.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>454</th>\n",
       "      <td>14.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>80</th>\n",
       "      <td>28.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     MEDV\n",
       "247  20.5\n",
       "454  14.9\n",
       "80   28.0"
      ]
     },
     "execution_count": 147,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_test.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "id": "fa4e0662",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 선형회귀 모형 생성 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "id": "9ec962ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ① linear_model 모듈에서 제공하는 LinearRegression 함수를 가져온다.\n",
    "from sklearn.linear_model import LinearRegression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "id": "4d7e30e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "#② 선형회귀분석을 수행할 모델(model) 만든다.\n",
    "model = LinearRegression()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "id": "65b815a2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-2 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-2 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-2 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-2 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-2 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-2 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-2 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-2 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-2 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>LinearRegression()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" checked><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;LinearRegression<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.linear_model.LinearRegression.html\">?<span>Documentation for LinearRegression</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>LinearRegression()</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "LinearRegression()"
      ]
     },
     "execution_count": 155,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#③ 생성할 모델에 x_train,y_train에 의사결정나무 분류 모형을 학습\n",
    "model.fit(x_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "44599a81",
   "metadata": {},
   "outputs": [],
   "source": [
    "#④ 학습한 모델에 x_test를 전달하여 y_test 예측한다.\n",
    "y_test_predicted=model.predict(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "67123a56",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4) 모델 평가\n",
    "# 회귀 모델의 평가지표 결정계수,MSE,RMSE,MAE\n",
    "# 회귀모형 평가지표를 계산하기 위해 metrics 모듈의 함수를 가져온다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 161,
   "id": "f6f0894f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import mean_squared_error,r2_score,mean_absolute_error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 163,
   "id": "44fa8beb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "22.046856922325155"
      ]
     },
     "execution_count": 163,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# MSE 구하기\n",
    "mse=mean_squared_error(y_test,y_test_predicted)\n",
    "mse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 165,
   "id": "8e4bc8fa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.695408067710958"
      ]
     },
     "execution_count": 165,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# RMSE 구하기\n",
    "rmse = np.sqrt(mse)\n",
    "rmse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 167,
   "id": "ebff9759",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6949716436113118"
      ]
     },
     "execution_count": 167,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 평가 데이터의 결정계수\n",
    "r2_score(y_test,y_test_predicted)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 169,
   "id": "f77358fa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.380161457858375"
      ]
     },
     "execution_count": 169,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# MAE 구하기\n",
    "mae=mean_absolute_error(y_test,y_test_predicted)\n",
    "mae"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7fcf5366-3e8b-4be8-98de-625b39fdab6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 6장 데이터 인코딩(Encoding)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7daf65f-4372-4dd5-98d9-9695eaddbe31",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 레이블 인코딩(Label Encoding)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 171,
   "id": "330ccc81-f19e-40e3-930a-a4ac8c031123",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Gender  Gender_encoded\n",
      "0    male               1\n",
      "1  female               0\n",
      "2  female               0\n",
      "3  female               0\n",
      "4    male               1\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "titanic_data = pd.read_csv('c:/data/titanic.csv')\n",
    "label_encoder = LabelEncoder()\n",
    "titanic_data['Gender_encoded'] = label_encoder.fit_transform(titanic_data['Gender'])\n",
    "print(titanic_data[['Gender', 'Gender_encoded']].head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 173,
   "id": "98879974-bc0e-4867-bb47-1332619a9849",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     PassengerId  Survived  Pclass  \\\n",
      "0              1         0       3   \n",
      "1              2         1       1   \n",
      "2              3         1       3   \n",
      "3              4         1       1   \n",
      "4              5         0       3   \n",
      "..           ...       ...     ...   \n",
      "886          887         0       2   \n",
      "887          888         1       1   \n",
      "888          889         0       3   \n",
      "889          890         1       1   \n",
      "890          891         0       3   \n",
      "\n",
      "                                                  Name   Age  SibSp  Parch  \\\n",
      "0                              Braund, Mr. Owen Harris  22.0      1      0   \n",
      "1    Cumings, Mrs. John Bradley (Florence Briggs Th...  38.0      1      0   \n",
      "2                               Heikkinen, Miss. Laina  26.0      0      0   \n",
      "3         Futrelle, Mrs. Jacques Heath (Lily May Peel)  35.0      1      0   \n",
      "4                             Allen, Mr. William Henry  35.0      0      0   \n",
      "..                                                 ...   ...    ...    ...   \n",
      "886                              Montvila, Rev. Juozas  27.0      0      0   \n",
      "887                       Graham, Miss. Margaret Edith  19.0      0      0   \n",
      "888           Johnston, Miss. Catherine Helen \"Carrie\"   NaN      1      2   \n",
      "889                              Behr, Mr. Karl Howell  26.0      0      0   \n",
      "890                                Dooley, Mr. Patrick  32.0      0      0   \n",
      "\n",
      "               Ticket     Fare Cabin Embarked  Gender_male  \n",
      "0           A/5 21171   7.2500   NaN        S         True  \n",
      "1            PC 17599  71.2833   C85        C        False  \n",
      "2    STON/O2. 3101282   7.9250   NaN        S        False  \n",
      "3              113803  53.1000  C123        S        False  \n",
      "4              373450   8.0500   NaN        S         True  \n",
      "..                ...      ...   ...      ...          ...  \n",
      "886            211536  13.0000   NaN        S         True  \n",
      "887            112053  30.0000   B42        S        False  \n",
      "888        W./C. 6607  23.4500   NaN        S        False  \n",
      "889            111369  30.0000  C148        C         True  \n",
      "890            370376   7.7500   NaN        Q         True  \n",
      "\n",
      "[891 rows x 12 columns]\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "titanic_data = pd.read_csv('c:/data/titanic.csv')\n",
    "categorical_columns = ['Gender']\n",
    "encoded_data = pd.get_dummies(titanic_data, columns=categorical_columns,drop_first=True)\n",
    "print(encoded_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f610892-c58d-43ab-aa7b-793b584d8893",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 7장 연습문제 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "225647a6-2977-4c72-8e44-c1dbf8a3d49e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 01 hflights 데이터에서 Dest 변수는 항공편의 도착지 공항을 나타낸다. 가장 적은 도착지 공항과 \n",
    "# 가장 많은 도착지 공항을 찾고, 각각의 운항 횟수를 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8e098d00-51f1-4319-a5a3-8f3e1d820ef4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "hflights=pd.read_csv(\"c:/data/hflights.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66577380-260a-4040-b918-45b9d7fa5bbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 학습 포인트(Learning Points)를 3가지\n",
    "# 1) 범주형 데이터의 빈도수 계산: value_counts()\n",
    "# 기본적으로 빈도수가 높은 것부터 내림차순으로 정렬\n",
    "# 2) 최댓값과 최솟값 '수치' 찾기: max(), min()\n",
    "# 3) 최댓값과 최솟값의 '이름(인덱스)' 찾기: idxmax(), idxmin()\n",
    "# Series나 DataFrame에서 최대/최솟값이 위치한 인덱스 라벨(Index Label)을 반환"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f950dace-0f32-4828-a521-5667adaef522",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Dest\n",
       "DAL    9820\n",
       "ATL    7886\n",
       "MSY    6823\n",
       "DFW    6653\n",
       "LAX    6064\n",
       "       ... \n",
       "PSP     106\n",
       "GUC      86\n",
       "GRK      42\n",
       "BPT       3\n",
       "AGS       1\n",
       "Name: count, Length: 116, dtype: int64"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hflights['Dest'].value_counts()\n",
    "counts=hflights['Dest'].value_counts()\n",
    "counts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f4a58c40-0285-429c-9aea-c8bd4e283373",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9820"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " counts.max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "15419cd6-3977-4ff7-910d-604261a66308",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'DAL'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " counts.idxmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "e15493fe-472f-4bad-8503-665b3324fad2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " counts.min()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4aae3859-ef8b-4905-994c-158014c5ed38",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'AGS'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " counts.idxmin()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3caaefb-7221-40da-914d-c993b1ccb207",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 02 hflights 데이터에서 'DepTime' 변수의 결측치 개수를 구하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7ffe402-6d20-4bc1-bc1b-091cf21fcd12",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 빅데이터 분석기사 실기 시험(작업형 1, 2유형 모두)에서 무조건 출제된다고 보아도 무방한 '결측치(Missing Value) 탐색' 기법\n",
    "# 결측치 개수를 구하는 것은 보통 문제의 전반부입니다. 실기 시험에서는 결측치를 확인한 후, 이를 어떻게 처리할 것인가를 연계해서 출제\n",
    "# 데이터를 불러온 직후에는 습관적으로 데이터.isna().sum()을 입력하여 어떤 변수에  결측치가 있는지부터 파악하는 것이 데이터 분석의 기본 원칙"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "93bf4d39-5a07-4afd-9757-f1bcfb8ca398",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2905"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "hflights=pd.read_csv(\"c:/data/hflights.csv\")\n",
    "hflights['DepTime'].isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3407bf4a-318b-4b75-8819-8a101f7fd986",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 03 airquality 데이터셋에 대한 문제이다. Ozone 변수에서 결측치를 제외한 데이터들의 \n",
    "# 중위수를 구하고, 그리고 그 중위수를 Ozone 변수의 결측치에 입력한 후에 Ozone의 평균을 구하라"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d0705629-8028-48ee-b577-10729be50c7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "airquality=pd.read_csv(\"c:/data/airquality.csv\")\n",
    "ozone_median=airquality['Ozone'].dropna().median()\n",
    "# airquality['Ozone'].median() 동일한 결과 \n",
    "# Pandas는 데이터에 빈칸이 섞여 있어도 알아서 무시하고 남은 유효한 숫자들로만 계산"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "76066952-279c-4aca-9433-38c8612d7d0f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "31.5"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airquality['Ozone'].median()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "441feef1-e4ba-4a50-861d-eb5555b5d4e1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "31.5"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ozone_median"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "bb7759f5-c347-42e0-ac01-0357e0c83eaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "airquality.loc[:, 'Ozone']=airquality['Ozone'].fillna(ozone_median)\n",
    "# 데이터를 그냥 눈으로 '조회'만 할 때는 airquality['Ozone']이라고 짧게 써도 아무 문제가 없음\n",
    "# .loc를 쓰면 데이터.loc[행 이름, 열 이름] 형태로 가로세로 좌표를 한 번에 명확하게 지정 할 수 있음\n",
    "# airquality['Ozone'] = airquality['Ozone'].fillna(ozone_median)  동일한 기능"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "7e3f8c9c-f0cb-4a9c-878b-123ccabec949",
   "metadata": {},
   "outputs": [],
   "source": [
    "ozone_mean=airquality['Ozone'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "e215e55e-09f8-4ad0-bc3b-5047a928d368",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "39.55882352941177"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ozone_mean"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcefb8df-298c-42f2-9cd5-53e7cccb3c31",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 04. diamonds 데이터셋에서 price 변수가 가장 높을 때의 price 값을 구하시오\n",
    "# 핵심 출제 포인트\n",
    "# 1) 데이터프레임에서 특정 변수(열) 추출 능력\n",
    "# 2차원 데이터프레임 구조에서 내가 원하는 특정 컬럼(1차원 Series)만 추출, diamonds['price']\n",
    "# 2) 기초 통계 함수(메서드) 활용 능력\n",
    "# 3) 결과가 데이터프레임이나 시리즈 형태 구분\n",
    "# print(diamonds['price'].max())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "c82fa2eb-c15e-44dc-bebb-12839118c84e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 응용 출제 포인트\n",
    "# 실제 시험에서는 다음과 같이 조건부 색인(Indexing)을 묻는 2단계 문제로 확장될 확률이 매우 높습니다.\n",
    "# \"price가 가장 높은 다이아몬드의 'color(또는 carat)'는 무엇인가?\"\n",
    "#해결 방법 1 (Boolean Indexing):\n",
    "#price가 최댓값과 같은 행을 찾고, 그 행의 color 컬럼을 가져옵니다.\n",
    "max_price = diamonds['price'].max()\n",
    "result = diamonds.loc[diamonds['price'] == max_price, 'color']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "5d8f2403-116a-4bc8-8a26-d15685d28689",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "27749    I\n",
       "Name: color, dtype: object"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6bac92b-9195-4f58-812c-e45c789a36fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 05. diamonds 데이터셋의 cut, color 범주별로 price 평균을 구하고 \n",
    "# price 변수의 내림차순 기준으로 cut의 상위 3개 집단을 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f39b5f36-6d3f-4248-afd7-da60c7258239",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "f863d0f8-5385-41a5-93fb-937ef3731216",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "diamonds = pd.read_csv(\"c:/data/diamonds.csv\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dbccfaa6-dde7-4bd6-adaf-91314300174a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#핵심 출제 포인트 4가지\n",
    "# 1) 다중 변수 그룹화 (Multi-variable Grouping)\n",
    "# groupby() 함수 안에 단일 문자열이 아닌 리스트 형태 ['cut', 'color']로 묶어서 전달\n",
    "# 2) 인덱스 초기화 (reset_index())\n",
    "# groupby를 수행하면 그룹화 기준이 된 변수들('cut', 'color')이 인덱스(행 이름)로 들어가 버리는 '멀티 인덱스(MultiIndex)' 상태가 됩니다. \n",
    "# 이를 다시 일반적인 데이터프레임 열(Column) 변환해야 특정 'price' 기준으로 정렬할 수 있음"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "7c6498f5-4db9-4b21-a3ac-999861656d18",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>cut</th>\n",
       "      <th>color</th>\n",
       "      <th>price</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Fair</td>\n",
       "      <td>D</td>\n",
       "      <td>4291.061350</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Fair</td>\n",
       "      <td>E</td>\n",
       "      <td>3682.312500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Fair</td>\n",
       "      <td>F</td>\n",
       "      <td>3827.003205</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    cut color        price\n",
       "0  Fair     D  4291.061350\n",
       "1  Fair     E  3682.312500\n",
       "2  Fair     F  3827.003205"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " diamonds.groupby(['cut', 'color'])['price'].mean().reset_index().head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "5c8d7e4f-e4bb-44e5-bcf5-44bf01629a7e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>cut</th>\n",
       "      <th>color</th>\n",
       "      <th>price</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>27</th>\n",
       "      <td>Premium</td>\n",
       "      <td>J</td>\n",
       "      <td>6294.591584</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>26</th>\n",
       "      <td>Premium</td>\n",
       "      <td>I</td>\n",
       "      <td>5946.180672</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>33</th>\n",
       "      <td>Very Good</td>\n",
       "      <td>I</td>\n",
       "      <td>5255.879568</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          cut color        price\n",
       "27    Premium     J  6294.591584\n",
       "26    Premium     I  5946.180672\n",
       "33  Very Good     I  5255.879568"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grouped = diamonds.groupby(['cut', 'color'])['price'].mean().reset_index()\n",
    "grouped.sort_values(by='price',ascending=False).head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e66be7f3-e97d-4115-ae3e-c1b70f7352d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 06. diamonds에서 cut의 범주별 빈도와 비율 중 'Ideal' 백분율을 구하시오\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "b8d5a8a2-4c96-42ac-9639-5d739f45bae2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "cut\n",
       "Ideal        21551\n",
       "Premium      13791\n",
       "Very Good    12082\n",
       "Good          4906\n",
       "Fair          1610\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "diamonds=pd.read_csv(\"c:/data/diamonds.csv\")\n",
    "cut_counts=diamonds['cut'].value_counts()\n",
    "cut_counts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2088999e-04ca-41f5-bfac-8c83f6294eee",
   "metadata": {},
   "outputs": [],
   "source": [
    "cut_percentages=cut_counts / len(diamonds) * 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "c4dedca9-ca26-4dfa-841a-c67c98dd8659",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "cut\n",
       "Ideal        39.953652\n",
       "Premium      25.567297\n",
       "Very Good    22.398962\n",
       "Good          9.095291\n",
       "Fair          2.984798\n",
       "Name: count, dtype: float64"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cut_percentages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "f50165f7-584d-4039-9238-a3ff8b4d9cd9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "39.953652206154985"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cut_percentages['Ideal']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "3a32afbf-c792-4190-94ee-cf87a8ee5bc2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "39.953652206154985"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# diamonds['cut'].value_counts(normalize=True)['Ideal'] * 100\n",
    "# value_counts(normalize=True): 비율을 구해줌\n",
    "# 시험 문제에서 '비율(Ratio)'이나 '백분율(Percentage)'을 구하라는 단어가 나오면 무조건 normalize=True를 떠올리시면\n",
    "# 쉽게 정답을 출력할 수 있음 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24b93927-c3ef-4946-a3e7-6d4a342d66d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 07 gapminder dataset에서 Europe과 Africa 대륙 중 가장 많은 인구(pop)를 가졌던 \n",
    "# 국가와 연도를 구하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "160975d8-945f-441b-ae6c-095cfc1bc16b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 핵심 출제 포인트 3가지\n",
    "# 1) 다중 조건 필터링 (isin() 메서드 활용)\n",
    "# 데이터[데이터['조건 열'].isin(['조건1', '조건2'])]\n",
    "# 리스트 안에 있는 값들 중 \"조건1을 만족하거나(OR) 조건2를 만족하는 데이터\"를 모두 가져오라는 의미"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "c7c5bdc6-210a-4dd2-afe8-8aa1d61d35cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "gapminder = pd.read_csv(\"c:/data/gapminder.csv\")\n",
    "# Europe과 Africa 필터링\n",
    "filtered = gapminder[gapminder['continent'].isin(['Europe', 'Africa'])]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "9c3cfb76-8b8b-4e9d-ba23-fa3cb8e8fdbf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>country</th>\n",
       "      <th>continent</th>\n",
       "      <th>year</th>\n",
       "      <th>lifeExp</th>\n",
       "      <th>pop</th>\n",
       "      <th>gdpPercap</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>Albania</td>\n",
       "      <td>Europe</td>\n",
       "      <td>1952</td>\n",
       "      <td>55.230</td>\n",
       "      <td>1282697</td>\n",
       "      <td>1601.056136</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>Albania</td>\n",
       "      <td>Europe</td>\n",
       "      <td>1957</td>\n",
       "      <td>59.280</td>\n",
       "      <td>1476505</td>\n",
       "      <td>1942.284244</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>Albania</td>\n",
       "      <td>Europe</td>\n",
       "      <td>1962</td>\n",
       "      <td>64.820</td>\n",
       "      <td>1728137</td>\n",
       "      <td>2312.888958</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>Albania</td>\n",
       "      <td>Europe</td>\n",
       "      <td>1967</td>\n",
       "      <td>66.220</td>\n",
       "      <td>1984060</td>\n",
       "      <td>2760.196931</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>Albania</td>\n",
       "      <td>Europe</td>\n",
       "      <td>1972</td>\n",
       "      <td>67.690</td>\n",
       "      <td>2263554</td>\n",
       "      <td>3313.422188</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1699</th>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>Africa</td>\n",
       "      <td>1987</td>\n",
       "      <td>62.351</td>\n",
       "      <td>9216418</td>\n",
       "      <td>706.157306</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1700</th>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>Africa</td>\n",
       "      <td>1992</td>\n",
       "      <td>60.377</td>\n",
       "      <td>10704340</td>\n",
       "      <td>693.420786</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1701</th>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>Africa</td>\n",
       "      <td>1997</td>\n",
       "      <td>46.809</td>\n",
       "      <td>11404948</td>\n",
       "      <td>792.449960</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1702</th>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>Africa</td>\n",
       "      <td>2002</td>\n",
       "      <td>39.989</td>\n",
       "      <td>11926563</td>\n",
       "      <td>672.038623</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1703</th>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>Africa</td>\n",
       "      <td>2007</td>\n",
       "      <td>43.487</td>\n",
       "      <td>12311143</td>\n",
       "      <td>469.709298</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>984 rows × 6 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "       country continent  year  lifeExp       pop    gdpPercap\n",
       "12     Albania    Europe  1952   55.230   1282697  1601.056136\n",
       "13     Albania    Europe  1957   59.280   1476505  1942.284244\n",
       "14     Albania    Europe  1962   64.820   1728137  2312.888958\n",
       "15     Albania    Europe  1967   66.220   1984060  2760.196931\n",
       "16     Albania    Europe  1972   67.690   2263554  3313.422188\n",
       "...        ...       ...   ...      ...       ...          ...\n",
       "1699  Zimbabwe    Africa  1987   62.351   9216418   706.157306\n",
       "1700  Zimbabwe    Africa  1992   60.377  10704340   693.420786\n",
       "1701  Zimbabwe    Africa  1997   46.809  11404948   792.449960\n",
       "1702  Zimbabwe    Africa  2002   39.989  11926563   672.038623\n",
       "1703  Zimbabwe    Africa  2007   43.487  12311143   469.709298\n",
       "\n",
       "[984 rows x 6 columns]"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "filtered "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "bc1aa154-e932-4aa6-bf27-b1ea88aa096b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1139"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "filtered['pop'].idxmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "e7bc040c-d1a5-438a-91ba-7ed1e8718cf7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "country      Nigeria\n",
       "year            2007\n",
       "pop        135031164\n",
       "Name: 1139, dtype: object"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max_idx = filtered['pop'].idxmax()\n",
    "filtered.loc[max_idx, ['country', 'year', 'pop']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "57ec0c54-49a3-408a-95ce-68dfa909a960",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 8장 실전문제"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adc96a2d-68d1-466a-97be-69ce5fe7bd6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#01 서울특별시 대기환경정보 데이터를 이용해서 서울시의 미세먼지, 초미세먼지를 분석한다.\n",
    "# 예제파일 period1.xlsx는 서울시 2022.02~03까지 구별 미세먼지, 초미세먼지, 오존, \n",
    "# 이산화질소, 일산화탄소, 아황산가스 데이터를 포함하고 있다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "9b3897ac-6433-443e-be7c-909b04843bbe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1535 entries, 0 to 1534\n",
      "Data columns (total 8 columns):\n",
      " #   Column              Non-Null Count  Dtype  \n",
      "---  ------              --------------  -----  \n",
      " 0   날짜                  1535 non-null   object \n",
      " 1   측정소명                1535 non-null   object \n",
      " 2   미세먼지 PM10\n",
      "(㎍/m3)    1528 non-null   float64\n",
      " 3   초미세먼지\n",
      "PM2.5 (㎍/m3)  1532 non-null   float64\n",
      " 4   오존\n",
      "O3 (ppm)         1533 non-null   float64\n",
      " 5   이산화질소\n",
      "NO2 (ppm)     1531 non-null   float64\n",
      " 6   일산화탄소\n",
      "CO (ppm)      1525 non-null   float64\n",
      " 7   아황산가스\n",
      "SO2(ppm)      1521 non-null   float64\n",
      "dtypes: float64(6), object(2)\n",
      "memory usage: 96.1+ KB\n"
     ]
    }
   ],
   "source": [
    "# 1) 분석 데이터 구조를 파악한다\n",
    "import pandas as pd\n",
    "airseoul=pd.read_excel(\"c:/data/period1.xlsx\")\n",
    "airseoul.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80cb5fc3-ffbd-46d5-b972-8963b5537d93",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2)결측치와 이상치를 확인한다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "5b17424a-fe52-4643-88f4-044912cdf214",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['날짜', '측정소명', '미세먼지 PM10\\n(㎍/m3)', '초미세먼지\\nPM2.5 (㎍/m3)',\n",
       "       '오존\\nO3 (ppm)', '이산화질소\\nNO2 (ppm)', '일산화탄소\\nCO (ppm)',\n",
       "       '아황산가스\\nSO2(ppm)'],\n",
       "      dtype='object')"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airseoul.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "6036a368-35f3-4abd-984f-10190c1c1e6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "airseoul1=airseoul.rename(columns={\n",
    "    '날짜': 'date',\n",
    "    '측정소명': 'region',\n",
    "    '미세먼지 PM10\\n(㎍/m3)': 'pm10',\n",
    "    '초미세먼지\\nPM2.5 (㎍/m3)': 'pm2.5'\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "132af5c1-a27f-4c67-adef-c0aafc57b564",
   "metadata": {},
   "outputs": [],
   "source": [
    "airseoul1 = airseoul1[['date', 'region', 'pm10', 'pm2.5']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "8ac7c26d-eaaa-47ed-94a4-ea40e5138960",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "region\n",
       "평균      60\n",
       "강남구     59\n",
       "중구      59\n",
       "종로구     59\n",
       "은평구     59\n",
       "용산구     59\n",
       "영등포구    59\n",
       "양천구     59\n",
       "송파구     59\n",
       "성북구     59\n",
       "성동구     59\n",
       "서초구     59\n",
       "서대문구    59\n",
       "마포구     59\n",
       "동작구     59\n",
       "동대문구    59\n",
       "도봉구     59\n",
       "노원구     59\n",
       "금천구     59\n",
       "구로구     59\n",
       "광진구     59\n",
       "관악구     59\n",
       "강서구     59\n",
       "강북구     59\n",
       "강동구     59\n",
       "중랑구     59\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airseoul1['region'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "c6de3399-c1cc-4a8e-b596-79e044223eba",
   "metadata": {},
   "outputs": [],
   "source": [
    "airseoul1=airseoul1[~((airseoul1['date']=='전체')|\n",
    "                     (airseoul1['region']=='평균'))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "154baccb-1883-4dcd-84eb-666292e7ad05",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "date      0\n",
       "region    0\n",
       "pm10      7\n",
       "pm2.5     3\n",
       "dtype: int64"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " airseoul1.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "d9432c03-c9f1-4ff1-a63a-a15c3d10b5ec",
   "metadata": {},
   "outputs": [],
   "source": [
    " airseoul2=airseoul1.dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c80cfbf7-cc86-48d9-a43d-7ec1e8f031c9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (1) 미세먼지가 가장 심했던 날짜, 지역, 미세먼지 수치(pm10)는?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "37365891-50cb-4600-8847-2bdc66b98282",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>date</th>\n",
       "      <th>region</th>\n",
       "      <th>pm10</th>\n",
       "      <th>pm2.5</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>684</th>\n",
       "      <td>2022-03-05</td>\n",
       "      <td>구로구</td>\n",
       "      <td>112.0</td>\n",
       "      <td>15.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           date region   pm10  pm2.5\n",
       "684  2022-03-05    구로구  112.0   15.0"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " airseoul2[airseoul2['pm10']==airseoul2['pm10'].max()]\n",
    "# 조건부 색인 (Boolean Indexing)\n",
    "# 데이터[ 데이터['열'] == 조건 ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "542ccb47-a679-4166-a5c8-823cd6ad3d03",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) 서울시의 2022년 2월부터 3월까지 미세먼지 평균을 구하고 평균을 기준으로 상위 5개 구는?\n",
    "# \"그룹으로 묶어서 요약 ➔ 정상적인 표로 되돌림 ➔ 내림차순 정렬 ➔ 위에서 5개 자르기\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "id": "05518742-9d82-4622-8bcd-dcdf2c8ffbc1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>region</th>\n",
       "      <th>pm10</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>강남구</td>\n",
       "      <td>38.915254</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>강동구</td>\n",
       "      <td>43.576271</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>강북구</td>\n",
       "      <td>44.155172</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>강서구</td>\n",
       "      <td>43.796610</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>관악구</td>\n",
       "      <td>38.728814</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>광진구</td>\n",
       "      <td>38.389831</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>구로구</td>\n",
       "      <td>41.796610</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>금천구</td>\n",
       "      <td>39.898305</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>노원구</td>\n",
       "      <td>43.677966</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>도봉구</td>\n",
       "      <td>38.551724</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>동대문구</td>\n",
       "      <td>41.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>동작구</td>\n",
       "      <td>43.482759</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>마포구</td>\n",
       "      <td>36.881356</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>서대문구</td>\n",
       "      <td>39.224138</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>서초구</td>\n",
       "      <td>38.830508</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>성동구</td>\n",
       "      <td>41.084746</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>성북구</td>\n",
       "      <td>42.915254</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>송파구</td>\n",
       "      <td>41.016949</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>양천구</td>\n",
       "      <td>44.448276</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>19</th>\n",
       "      <td>영등포구</td>\n",
       "      <td>39.406780</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>용산구</td>\n",
       "      <td>39.508475</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>은평구</td>\n",
       "      <td>39.684211</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>22</th>\n",
       "      <td>종로구</td>\n",
       "      <td>38.844828</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>23</th>\n",
       "      <td>중구</td>\n",
       "      <td>35.644068</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>24</th>\n",
       "      <td>중랑구</td>\n",
       "      <td>40.050847</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   region       pm10\n",
       "0     강남구  38.915254\n",
       "1     강동구  43.576271\n",
       "2     강북구  44.155172\n",
       "3     강서구  43.796610\n",
       "4     관악구  38.728814\n",
       "5     광진구  38.389831\n",
       "6     구로구  41.796610\n",
       "7     금천구  39.898305\n",
       "8     노원구  43.677966\n",
       "9     도봉구  38.551724\n",
       "10   동대문구  41.000000\n",
       "11    동작구  43.482759\n",
       "12    마포구  36.881356\n",
       "13   서대문구  39.224138\n",
       "14    서초구  38.830508\n",
       "15    성동구  41.084746\n",
       "16    성북구  42.915254\n",
       "17    송파구  41.016949\n",
       "18    양천구  44.448276\n",
       "19   영등포구  39.406780\n",
       "20    용산구  39.508475\n",
       "21    은평구  39.684211\n",
       "22    종로구  38.844828\n",
       "23     중구  35.644068\n",
       "24    중랑구  40.050847"
      ]
     },
     "execution_count": 79,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airseoul2.groupby('region')['pm10'].mean().reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "81c3a301-eca1-46ba-8a79-0d70843a3bf2",
   "metadata": {},
   "outputs": [],
   "source": [
    " grouped_mean=airseoul2.groupby('region')['pm10'].mean().reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "77bd0647-c84f-4d0f-bebb-2ef4d2643470",
   "metadata": {},
   "outputs": [],
   "source": [
    " sorted_mean=grouped_mean.sort_values(by='pm10', ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "d340a581-e80e-4ad8-8c40-ea1766813d78",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>region</th>\n",
       "      <th>pm10</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>양천구</td>\n",
       "      <td>44.448276</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>강북구</td>\n",
       "      <td>44.155172</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>강서구</td>\n",
       "      <td>43.796610</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>노원구</td>\n",
       "      <td>43.677966</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>강동구</td>\n",
       "      <td>43.576271</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   region       pm10\n",
       "18    양천구  44.448276\n",
       "2     강북구  44.155172\n",
       "3     강서구  43.796610\n",
       "8     노원구  43.677966\n",
       "1     강동구  43.576271"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sorted_mean.head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "661bbc7f-1ab2-4b37-8cf5-7e675509f9e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (3)하루의 미세먼지(pm10) 상황은 1일 수치가 0~30이면 ‘good’, 31~80이면 ‘normal’, \n",
    "# 81~150이면 ‘bad’, 151이상이면 ‘worse’로 구분한다. 이 기준에 따라 미세먼지 \n",
    "# 등급 변수(파생변수)를 생성하고 이때 ‘good’의 빈도수와 백분율을 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d530d6ed-61ba-4bd8-bb00-0a6a262bfe47",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1) 연속형 데이터의 범주화 (파생변수 생성: pd.cut)\n",
    "# 2) 경계값(이상/이하/미만/초과)의 정확한 처리 (right=False), 오른쪽 숫자를 포함하지 않음(미만)\n",
    "# 3) 범주별 빈도수와 백분율 계산"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "7f03ca63-89fd-4378-a6e3-91a6d8f86597",
   "metadata": {},
   "outputs": [],
   "source": [
    " airseoul2=airseoul2.copy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "11719c48-0999-427f-969b-257282950016",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 조건에 따라 데이터를 자를 때는 무조건 pd.cut(데이터, bins=[구간], labels=[이름])\n",
    "airseoul2.loc[:, 'pm_grade']=pd.cut(\n",
    "airseoul2['pm10'], \n",
    "bins=[-float('inf'), 31, 81, 151, float('inf')],\n",
    "labels=['good', 'normal', 'bad', 'worse'], \n",
    "right=False\n",
    ")\n",
    "# -float('inf') ~ 31 미만:\n",
    "#  31 이상 ~ 81 미만\n",
    "#  81 이상 ~ 151 미만\n",
    "# 151 이상 ~ float('inf') 미만"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "8b75a866-26e3-4c09-9bdb-bea143a71c7e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<pandas.core.groupby.generic.DataFrameGroupBy object at 0x000001B484979340>"
      ]
     },
     "execution_count": 93,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airseoul2.groupby('pm_grade', observed=False)\n",
    "# observed=False\n",
    "# 데이터에 한 번도 등장하지 않은(빈도수가 0인) 카테고리를 결과 표에 보여줄 것인가\n",
    "# # 출력 결과 (F가 0으로 살아남음)\n",
    "# pm_grade\n",
    "# A    3명\n",
    "# B    4명\n",
    "# C    2명\n",
    "# D    1명\n",
    "# F    0명   <-- 핵심 포인트!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "30a4179a-7e16-40e5-a653-d49f698d08d0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pm_grade\n",
       "good      538\n",
       "normal    855\n",
       "bad        74\n",
       "worse       0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airseoul2.groupby('pm_grade', observed=False).size()\n",
    "# .size()는 묶여진 그룹 안에 \"데이터(행)가 총 몇 줄씩 들어있는지(빈도수)를 단순히 세는 역할"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "865a2ef1-f1d4-49d7-970a-9c28f5678e24",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>pm_grade</th>\n",
       "      <th>0</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>good</td>\n",
       "      <td>538</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>normal</td>\n",
       "      <td>855</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>bad</td>\n",
       "      <td>74</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>worse</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  pm_grade    0\n",
       "0     good  538\n",
       "1   normal  855\n",
       "2      bad   74\n",
       "3    worse    0"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airseoul2.groupby('pm_grade', observed=False).size().reset_index()\n",
    "# Pandas의 자동 넘버링 규칙 0으로 생성"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "8f706d83-eed1-4162-a3b1-1c2f18344cad",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>pm_grade</th>\n",
       "      <th>n</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>good</td>\n",
       "      <td>538</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>normal</td>\n",
       "      <td>855</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>bad</td>\n",
       "      <td>74</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>worse</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  pm_grade    n\n",
       "0     good  538\n",
       "1   normal  855\n",
       "2      bad   74\n",
       "3    worse    0"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airseoul2.groupby('pm_grade',observed=False).size().reset_index().rename(columns={0: 'n'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "a1804fbd-9f96-4714-b82c-47d7776899f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "grouped=airseoul2.groupby('pm_grade',observed=False).size().reset_index().rename(columns={0: 'n'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "07560f16-acb5-4eb6-8b8b-181bd35d5865",
   "metadata": {},
   "outputs": [],
   "source": [
    " grouped['total']=grouped['n'].sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "id": "8d886571-b42c-4109-a940-e9791cc8db44",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  pm_grade    n  total        pct\n",
      "0     good  538   1467  36.673483\n",
      "1   normal  855   1467  58.282209\n",
      "2      bad   74   1467   5.044308\n",
      "3    worse    0   1467   0.000000\n"
     ]
    }
   ],
   "source": [
    "grouped['pct']=grouped['n'] / grouped['total'] * 100\n",
    "print(grouped)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70a7132c-5344-4faf-8fae-c5bfcc24e9a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4. (4) 초미세먼지(pm2.5)가 최소인 날짜 중에서 미세먼지(pm10)가 최대인 지역은?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "id": "a2f9e915-b57e-40b5-a4f3-9d690a555127",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>date</th>\n",
       "      <th>region</th>\n",
       "      <th>pm10</th>\n",
       "      <th>pm2.5</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>355</th>\n",
       "      <td>2022-03-18</td>\n",
       "      <td>성동구</td>\n",
       "      <td>7.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>346</th>\n",
       "      <td>2022-03-18</td>\n",
       "      <td>구로구</td>\n",
       "      <td>6.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>354</th>\n",
       "      <td>2022-03-18</td>\n",
       "      <td>서초구</td>\n",
       "      <td>6.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>320</th>\n",
       "      <td>2022-03-19</td>\n",
       "      <td>구로구</td>\n",
       "      <td>5.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>353</th>\n",
       "      <td>2022-03-18</td>\n",
       "      <td>서대문구</td>\n",
       "      <td>5.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>336</th>\n",
       "      <td>2022-03-19</td>\n",
       "      <td>종로구</td>\n",
       "      <td>4.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           date region  pm10  pm2.5\n",
       "355  2022-03-18    성동구   7.0    1.0\n",
       "346  2022-03-18    구로구   6.0    1.0\n",
       "354  2022-03-18    서초구   6.0    1.0\n",
       "320  2022-03-19    구로구   5.0    1.0\n",
       "353  2022-03-18   서대문구   5.0    1.0\n",
       "336  2022-03-19    종로구   4.0    1.0"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "airseoul1[airseoul1['pm2.5'] == airseoul1['pm2.5'].min()].sort_values(by='pm10', ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e36c423-9eb0-4a48-871e-cf96624f6b78",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 02공공데이터 포털(https://www.data.go.kr/)의 수도권 지하철의 노선, 역별,\n",
    "# 이용인원을 분석한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "id": "b40547fa-e8d9-4ab4-ad60-ddc8694f1125",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1)분석 데이터 구조를 파악한다.\n",
    "import pandas as pd\n",
    "subway_202203=pd.read_csv(\"c:/data/CARD_SUBWAY_MONTH_202203.csv\",encoding='cp949')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "id": "9fac8e42-604a-42da-9cb8-08b358a10fd1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 18467 entries, 0 to 18466\n",
      "Data columns (total 6 columns):\n",
      " #   Column  Non-Null Count  Dtype \n",
      "---  ------  --------------  ----- \n",
      " 0   사용일자    18467 non-null  int64 \n",
      " 1   노선명     18467 non-null  object\n",
      " 2   역명      18467 non-null  object\n",
      " 3   승차총승객수  18467 non-null  int64 \n",
      " 4   하차총승객수  18467 non-null  int64 \n",
      " 5   등록일자    18467 non-null  int64 \n",
      "dtypes: int64(4), object(2)\n",
      "memory usage: 865.8+ KB\n"
     ]
    }
   ],
   "source": [
    " subway_202203.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "id": "60922a95-f703-47a9-8e5e-f9ed09b481a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "subway_202203=subway_202203.rename(columns={\n",
    "  '사용일자': 'date',\n",
    "  '노선명': 'line',\n",
    "  '역명': 'station',\n",
    "  '승차총승객수': 'on_pass',\n",
    "  '하차총승객수': 'off_pass'\n",
    "}).drop(columns=['등록일자'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea509805-dfd0-4dee-9cfc-edc13a6ffb5d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2) 결측치와 이상치를 파악한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "id": "c729da72-633f-4071-9017-2263fbe403ea",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "date        0\n",
       "line        0\n",
       "station     0\n",
       "on_pass     0\n",
       "off_pass    0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "subway_202203.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "id": "2824ed73-e37c-4f99-9670-8f3c83c5c086",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "on_pass     8851.885688\n",
       "off_pass    8822.759463\n",
       "dtype: float64"
      ]
     },
     "execution_count": 117,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# (1) 역의 하루 평균 승차 고객수와 하차 승객수는?\n",
    "import pandas as pd\n",
    "subway_202203.agg({'on_pass': 'mean', 'off_pass': 'mean'})\n",
    "# agg() (집계 함수)\n",
    "# 구조는 {'열 이름' : '할 계산'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "288323c9-4320-40a4-80d5-282a8cf3f8ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) 승차 승객수가 가장 많은 노선과 승차승객수는?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "id": "ffb06915-14c8-4bb4-9549-345635326bf8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>date</th>\n",
       "      <th>line</th>\n",
       "      <th>station</th>\n",
       "      <th>on_pass</th>\n",
       "      <th>off_pass</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>14526</th>\n",
       "      <td>20220325</td>\n",
       "      <td>2호선</td>\n",
       "      <td>강남</td>\n",
       "      <td>80279</td>\n",
       "      <td>78816</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           date line station  on_pass  off_pass\n",
       "14526  20220325  2호선      강남    80279     78816"
      ]
     },
     "execution_count": 119,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " subway_202203[subway_202203['on_pass']== subway_202203['on_pass'].max()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f689166c-2090-49aa-ab2f-b8a958ca7776",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (3) 전체 승객수는 승차 총 승객수＋하차 총 승객수로 정의한다. \n",
    "# 역별로 평균 전체승객수 상위 3개 역은?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "id": "96893bfd-a22a-4334-b89e-06f373279699",
   "metadata": {},
   "outputs": [],
   "source": [
    "subway_202203['total_pass']=subway_202203['on_pass']+ subway_202203['off_pass']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "id": "4ecd0de8-7323-434d-9bc7-d4da29700bb9",
   "metadata": {},
   "outputs": [],
   "source": [
    " result = subway_202203.groupby('station').agg({'total_pass': 'mean'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "id": "f7d46dc6-1340-4440-b576-d4e2422e16b7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>total_pass</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>station</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>강남</th>\n",
       "      <td>125027.064516</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>신림</th>\n",
       "      <td>101544.548387</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>구로디지털단지</th>\n",
       "      <td>88651.774194</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            total_pass\n",
       "station               \n",
       "강남       125027.064516\n",
       "신림       101544.548387\n",
       "구로디지털단지   88651.774194"
      ]
     },
     "execution_count": 125,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " result.sort_values(by='total_pass', ascending=False).head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "abb139e3-2a16-4daf-9984-d2d9033efca0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (4) 지하철 1호선에서 평균 전체 승객이 가장 많았던 역과 날짜는?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f99b71f9-de7b-49c4-8cdd-d4fc44382384",
   "metadata": {},
   "outputs": [],
   "source": [
    " subway_202203['total_pass']=subway_202203['on_pass'] +subway_202203['off_pass']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "id": "b501c24e-3d08-4b07-b6a2-fb26c815ce6b",
   "metadata": {},
   "outputs": [],
   "source": [
    " df=subway_202203[subway_202203['line'] == '1호선']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "id": "536fe6a0-8f1c-45db-b214-bda6639e9104",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>date</th>\n",
       "      <th>line</th>\n",
       "      <th>station</th>\n",
       "      <th>on_pass</th>\n",
       "      <th>off_pass</th>\n",
       "      <th>total_pass</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>14495</th>\n",
       "      <td>20220325</td>\n",
       "      <td>1호선</td>\n",
       "      <td>서울역</td>\n",
       "      <td>41104</td>\n",
       "      <td>41346</td>\n",
       "      <td>82450</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           date line station  on_pass  off_pass  total_pass\n",
       "14495  20220325  1호선     서울역    41104     41346       82450"
      ]
     },
     "execution_count": 131,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[df['total_pass'] == df['total_pass'].max()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "id": "6379fcf3-17dc-409f-80ac-42621faed736",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>date</th>\n",
       "      <th>line</th>\n",
       "      <th>station</th>\n",
       "      <th>on_pass</th>\n",
       "      <th>off_pass</th>\n",
       "      <th>total_pass</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>14495</th>\n",
       "      <td>20220325</td>\n",
       "      <td>1호선</td>\n",
       "      <td>서울역</td>\n",
       "      <td>41104</td>\n",
       "      <td>41346</td>\n",
       "      <td>82450</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           date line station  on_pass  off_pass  total_pass\n",
       "14495  20220325  1호선     서울역    41104     41346       82450"
      ]
     },
     "execution_count": 133,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "subway_202203[subway_202203['line'] == '1호선'].sort_values('total_pass', ascending=False).head(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0144175-58c2-4a6a-986c-b521d5edd106",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 03한국복지패널에서 제공하는 2021년 급여 실태에 관한 데이터이다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2812b062-4021-407f-ad8f-120548eb2800",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1)분석 데이터 구조 확인하기"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "id": "51fbf213-21ff-4ceb-947e-d69c18706df8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "koweps=pd.read_csv(\"c:/data/koweps.csv\")\n",
    "house = koweps[['h1601_4', 'h1601_5', 'h1601_6', 'h16_reg5', 'h1608_114', 'h1608_122']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "88aa3a8c-6b5f-4f12-aaab-7f57687815ed",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 5996 entries, 0 to 5995\n",
      "Data columns (total 6 columns):\n",
      " #   Column     Non-Null Count  Dtype  \n",
      "---  ------     --------------  -----  \n",
      " 0   h1601_4    5996 non-null   int64  \n",
      " 1   h1601_5    5996 non-null   int64  \n",
      " 2   h1601_6    5996 non-null   int64  \n",
      " 3   h16_reg5   5996 non-null   int64  \n",
      " 4   h1608_114  1430 non-null   float64\n",
      " 5   h1608_122  1612 non-null   float64\n",
      "dtypes: float64(2), int64(4)\n",
      "memory usage: 281.2 KB\n"
     ]
    }
   ],
   "source": [
    "house.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "ca224936-01f2-475a-84f1-4f178c3dba6d",
   "metadata": {},
   "outputs": [],
   "source": [
    " house1=house.rename(columns={'h1601_4': 'gender',\n",
    "'h1601_5': 'birth',\n",
    "'h1601_6': 'edu',\n",
    "'h16_reg5': 'region',\n",
    "'h1608_114': 'r_salary',\n",
    "'h1608_122': 't_salary'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "id": "aceef447-e84f-4d1b-8be2-bb901509126a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>gender</th>\n",
       "      <th>birth</th>\n",
       "      <th>edu</th>\n",
       "      <th>region</th>\n",
       "      <th>r_salary</th>\n",
       "      <th>t_salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>5996.000000</td>\n",
       "      <td>5996.000000</td>\n",
       "      <td>5996.000000</td>\n",
       "      <td>5996.000000</td>\n",
       "      <td>1430.000000</td>\n",
       "      <td>1612.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>1.357238</td>\n",
       "      <td>1956.587558</td>\n",
       "      <td>4.635257</td>\n",
       "      <td>2.701968</td>\n",
       "      <td>5250.285315</td>\n",
       "      <td>1552.403226</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.479226</td>\n",
       "      <td>16.654058</td>\n",
       "      <td>1.675378</td>\n",
       "      <td>1.000452</td>\n",
       "      <td>3599.608702</td>\n",
       "      <td>1603.362143</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>1922.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>1942.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>3280.000000</td>\n",
       "      <td>297.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>1955.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>4620.000000</td>\n",
       "      <td>1040.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>2.000000</td>\n",
       "      <td>1970.000000</td>\n",
       "      <td>6.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>6620.000000</td>\n",
       "      <td>2340.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>2.000000</td>\n",
       "      <td>2001.000000</td>\n",
       "      <td>9.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>85860.000000</td>\n",
       "      <td>14580.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            gender        birth          edu       region      r_salary  \\\n",
       "count  5996.000000  5996.000000  5996.000000  5996.000000   1430.000000   \n",
       "mean      1.357238  1956.587558     4.635257     2.701968   5250.285315   \n",
       "std       0.479226    16.654058     1.675378     1.000452   3599.608702   \n",
       "min       1.000000  1922.000000     2.000000     1.000000      0.000000   \n",
       "25%       1.000000  1942.000000     3.000000     2.000000   3280.000000   \n",
       "50%       1.000000  1955.000000     5.000000     3.000000   4620.000000   \n",
       "75%       2.000000  1970.000000     6.000000     3.000000   6620.000000   \n",
       "max       2.000000  2001.000000     9.000000     5.000000  85860.000000   \n",
       "\n",
       "           t_salary  \n",
       "count   1612.000000  \n",
       "mean    1552.403226  \n",
       "std     1603.362143  \n",
       "min        0.000000  \n",
       "25%      297.000000  \n",
       "50%     1040.000000  \n",
       "75%     2340.000000  \n",
       "max    14580.000000  "
      ]
     },
     "execution_count": 143,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "house1.describe(include='number')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "id": "92a6d47a-8d28-454c-8fe9-73960e4a1bf1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "gender         0\n",
       "birth          0\n",
       "edu            0\n",
       "region         0\n",
       "r_salary    4566\n",
       "t_salary    4384\n",
       "dtype: int64"
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2)결측치와 이상값 확인하기\n",
    "house1.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "eb8a73e6-e8d3-4532-bd8a-28ea4ed90c62",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "house1['r_salary'] = np.where(house1['r_salary'] == 0, \n",
    "np.nan, house1['r_salary'])\n",
    "house1['t_salary'] = np.where(house1['t_salary'] == 0, \n",
    "np.nan, house1['t_salary'])\n",
    "# np.where(조건식, 참일 때 넣을 값, 거짓일 때 넣을 값) 구조\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "id": "43bf28b5-09b6-4755-baf9-01db6db82e46",
   "metadata": {},
   "outputs": [],
   "source": [
    "house1['age'] = 2021 - house1['birth'] + 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c2335b9-f7d9-42fc-873e-887be15e6881",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2021: 데이터가 수집되었거나, 시험 문제에서 기준으로 삼고 있는 현재 연도\n",
    "# house1['birth']: 기준 연도에서 태어난 연도를 뺍니다.\n",
    "# 만 나이가 아닌 '한국식 나이"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "id": "f5efd1a9-8c1d-453b-967f-87acad021c12",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(21, 100)"
      ]
     },
     "execution_count": 153,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " house1['age'].min(), house1['age'].max()\n",
    "# 쉼표(,)는 파이썬에서 \"두 가지 계산 결과를 한 묶음(튜플, Tuple)으로 만들어서 동시에 보여달라!\"는 \n",
    "# 아주 유용한 단축키 같은 역할"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "id": "784e423a-8c16-4ba5-8705-479d3dd04f9f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3) 범주형 분류 재부호하기\n",
    "house1['edu_grade'] = '대학이상'\n",
    "# edu_grade 파생변수에 초기값 설정 후 조건에 맞지 않은 값은 다른값으로 설정\n",
    "house1.loc[house1['edu'].isin([2, 3, 4]), 'edu_grade'] = '중학이하'\n",
    "# house1.loc[조건, 열이름] = 바꿀값 코드\n",
    "# house1['edu'].isin([2, 3, 4]) (행을 찾는 조건 부분)\n",
    "house1.loc[house1['edu'] == 5, 'edu_grade'] = '고교'\n",
    "house1.loc[house1['edu'] == 6, 'edu_grade'] = '전문대'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "6431878f-0fea-4e0f-959d-16a338636344",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "edu_grade\n",
       "중학이하    2730\n",
       "고교      1635\n",
       "대학이상    1169\n",
       "전문대      462\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 157,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " house1['edu_grade'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1427aeb7-f66e-4a6f-9f33-5725b2c1082c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (1) 상용직 근로자 중 최대 급여 근로자의 성별(gender) 급여액을 구하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "aefbfd77-7592-45cc-8bee-9ecc05430a9a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<pandas.core.groupby.generic.DataFrameGroupBy object at 0x000001B484B1B650>"
      ]
     },
     "execution_count": 159,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "house1.dropna(subset=['r_salary']).groupby('gender')\n",
    "# Pandas에서 .groupby('gender')를 실행하면 컴퓨터 내부에서는 남성 데이터와 여성 데이터를 \n",
    "# 각각 따로 분리해서 '폴더' 두 개(남성 폴더, 여성 폴더)에 \n",
    "# 나누어 담기만 합니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 161,
   "id": "190e5767-dc46-42a4-a03f-b9ab5b561296",
   "metadata": {},
   "outputs": [],
   "source": [
    " filtered_house1=house1.dropna(subset=['r_salary']).groupby('gender')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 169,
   "id": "ddb9fdae-8567-49b6-9d2a-099a842d8c82",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "gender\n",
       "1    1948\n",
       "2    3407\n",
       "Name: r_salary, dtype: int64"
      ]
     },
     "execution_count": 169,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "filtered_house1['r_salary'].idxmax()\n",
    "# .idxmax() (Index of Maximum)\n",
    "#  의미: \"최댓값(max)이 있는 곳의 인덱스\n",
    "#  1948과 3407 행 번호를 의미"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 165,
   "id": "5e63839a-ea82-4977-b2a1-fa84ad0a327f",
   "metadata": {},
   "outputs": [],
   "source": [
    " max_r_salary_indices=filtered_house1['r_salary'].idxmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 167,
   "id": "39643fdb-ed68-46c3-b78d-6b977af77425",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      gender  birth  edu  region  r_salary  t_salary  age edu_grade\n",
      "1948       1   1992    7       2   85860.0       NaN   30      대학이상\n",
      "3407       2   1997    7       3   37260.0       NaN   25      대학이상\n"
     ]
    }
   ],
   "source": [
    "result = house1.loc[max_r_salary_indices]\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "851e6ca2-e24a-4f5e-8f90-1708c5d1b697",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) 연령별 상용직 평균 급여액 중 상위 3개의 연령을 출력하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 171,
   "id": "3096048c-dd5a-46c9-a08a-7227923aedcc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>r_salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>21</td>\n",
       "      <td>3192.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>23</td>\n",
       "      <td>2280.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>24</td>\n",
       "      <td>3359.500000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>25</td>\n",
       "      <td>6557.222222</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>26</td>\n",
       "      <td>2794.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>27</td>\n",
       "      <td>2994.500000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>28</td>\n",
       "      <td>3301.875000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>29</td>\n",
       "      <td>3348.117647</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>30</td>\n",
       "      <td>8108.052632</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>31</td>\n",
       "      <td>3485.875000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>32</td>\n",
       "      <td>3850.142857</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>33</td>\n",
       "      <td>4003.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>34</td>\n",
       "      <td>4605.130435</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>35</td>\n",
       "      <td>4198.857143</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>36</td>\n",
       "      <td>5191.777778</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>37</td>\n",
       "      <td>5276.333333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>38</td>\n",
       "      <td>4882.800000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>39</td>\n",
       "      <td>5249.361111</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>40</td>\n",
       "      <td>5622.634146</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>19</th>\n",
       "      <td>41</td>\n",
       "      <td>5548.800000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>42</td>\n",
       "      <td>5713.102041</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>43</td>\n",
       "      <td>5379.259259</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>22</th>\n",
       "      <td>44</td>\n",
       "      <td>5443.704545</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>23</th>\n",
       "      <td>45</td>\n",
       "      <td>5889.789474</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>24</th>\n",
       "      <td>46</td>\n",
       "      <td>5862.259259</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25</th>\n",
       "      <td>47</td>\n",
       "      <td>5817.924528</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>26</th>\n",
       "      <td>48</td>\n",
       "      <td>6177.316667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>27</th>\n",
       "      <td>49</td>\n",
       "      <td>5320.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>28</th>\n",
       "      <td>50</td>\n",
       "      <td>6361.434783</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>29</th>\n",
       "      <td>51</td>\n",
       "      <td>7000.360000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>30</th>\n",
       "      <td>52</td>\n",
       "      <td>6102.636364</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>31</th>\n",
       "      <td>53</td>\n",
       "      <td>5691.058824</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>32</th>\n",
       "      <td>54</td>\n",
       "      <td>4680.434783</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>33</th>\n",
       "      <td>55</td>\n",
       "      <td>6169.583333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>34</th>\n",
       "      <td>56</td>\n",
       "      <td>6257.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>35</th>\n",
       "      <td>57</td>\n",
       "      <td>5677.280000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>36</th>\n",
       "      <td>58</td>\n",
       "      <td>4509.888889</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>37</th>\n",
       "      <td>59</td>\n",
       "      <td>6175.659091</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>38</th>\n",
       "      <td>60</td>\n",
       "      <td>5862.911765</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>39</th>\n",
       "      <td>61</td>\n",
       "      <td>5535.028571</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>40</th>\n",
       "      <td>62</td>\n",
       "      <td>3941.282051</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>41</th>\n",
       "      <td>63</td>\n",
       "      <td>3809.050000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>42</th>\n",
       "      <td>64</td>\n",
       "      <td>3334.588235</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>43</th>\n",
       "      <td>65</td>\n",
       "      <td>2335.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>44</th>\n",
       "      <td>66</td>\n",
       "      <td>3593.300000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>45</th>\n",
       "      <td>67</td>\n",
       "      <td>3318.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>46</th>\n",
       "      <td>68</td>\n",
       "      <td>2908.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>47</th>\n",
       "      <td>69</td>\n",
       "      <td>2109.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>48</th>\n",
       "      <td>70</td>\n",
       "      <td>3972.727273</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>49</th>\n",
       "      <td>71</td>\n",
       "      <td>1754.500000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50</th>\n",
       "      <td>72</td>\n",
       "      <td>914.333333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>51</th>\n",
       "      <td>73</td>\n",
       "      <td>2269.428571</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>52</th>\n",
       "      <td>74</td>\n",
       "      <td>2016.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>53</th>\n",
       "      <td>75</td>\n",
       "      <td>2590.333333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>54</th>\n",
       "      <td>76</td>\n",
       "      <td>9126.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>55</th>\n",
       "      <td>77</td>\n",
       "      <td>700.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>56</th>\n",
       "      <td>78</td>\n",
       "      <td>1152.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>57</th>\n",
       "      <td>80</td>\n",
       "      <td>1230.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>58</th>\n",
       "      <td>81</td>\n",
       "      <td>1680.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>59</th>\n",
       "      <td>83</td>\n",
       "      <td>1164.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    age     r_salary\n",
       "0    21  3192.000000\n",
       "1    23  2280.000000\n",
       "2    24  3359.500000\n",
       "3    25  6557.222222\n",
       "4    26  2794.200000\n",
       "5    27  2994.500000\n",
       "6    28  3301.875000\n",
       "7    29  3348.117647\n",
       "8    30  8108.052632\n",
       "9    31  3485.875000\n",
       "10   32  3850.142857\n",
       "11   33  4003.000000\n",
       "12   34  4605.130435\n",
       "13   35  4198.857143\n",
       "14   36  5191.777778\n",
       "15   37  5276.333333\n",
       "16   38  4882.800000\n",
       "17   39  5249.361111\n",
       "18   40  5622.634146\n",
       "19   41  5548.800000\n",
       "20   42  5713.102041\n",
       "21   43  5379.259259\n",
       "22   44  5443.704545\n",
       "23   45  5889.789474\n",
       "24   46  5862.259259\n",
       "25   47  5817.924528\n",
       "26   48  6177.316667\n",
       "27   49  5320.200000\n",
       "28   50  6361.434783\n",
       "29   51  7000.360000\n",
       "30   52  6102.636364\n",
       "31   53  5691.058824\n",
       "32   54  4680.434783\n",
       "33   55  6169.583333\n",
       "34   56  6257.666667\n",
       "35   57  5677.280000\n",
       "36   58  4509.888889\n",
       "37   59  6175.659091\n",
       "38   60  5862.911765\n",
       "39   61  5535.028571\n",
       "40   62  3941.282051\n",
       "41   63  3809.050000\n",
       "42   64  3334.588235\n",
       "43   65  2335.200000\n",
       "44   66  3593.300000\n",
       "45   67  3318.200000\n",
       "46   68  2908.000000\n",
       "47   69  2109.666667\n",
       "48   70  3972.727273\n",
       "49   71  1754.500000\n",
       "50   72   914.333333\n",
       "51   73  2269.428571\n",
       "52   74  2016.000000\n",
       "53   75  2590.333333\n",
       "54   76  9126.000000\n",
       "55   77   700.000000\n",
       "56   78  1152.000000\n",
       "57   80  1230.666667\n",
       "58   81  1680.000000\n",
       "59   83  1164.000000"
      ]
     },
     "execution_count": 171,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "house1.dropna(subset=['r_salary']).groupby('age')['r_salary'].mean().reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 173,
   "id": "aee0ba12-51b3-4b7a-b9c1-4e2f2984b887",
   "metadata": {},
   "outputs": [],
   "source": [
    " result =house1.dropna(subset=['r_salary']).groupby('age')['r_salary'].mean().reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 177,
   "id": "7448603a-b620-4a73-8ca0-10b2f812383f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>r_salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>54</th>\n",
       "      <td>76</td>\n",
       "      <td>9126.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>30</td>\n",
       "      <td>8108.052632</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>29</th>\n",
       "      <td>51</td>\n",
       "      <td>7000.360000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    age     r_salary\n",
       "54   76  9126.000000\n",
       "8    30  8108.052632\n",
       "29   51  7000.360000"
      ]
     },
     "execution_count": 177,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.sort_values(by='r_salary', ascending=False).head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1367040a-171e-4695-abe5-47bedfa8a450",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (3) 상용직 근로자의 교육 수준과 성별에 따른 평균 급여 분석을 하고 \n",
    "# 최상위 평균 급여 남성의  교육 수준과 평균 급여, 여성의 교육 수준과 평균 급여를 출력하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 179,
   "id": "80d4ddf8-fb04-48e9-8932-0f502f981ba0",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = house1.dropna(subset=['r_salary']).groupby(['gender', 'edu_grade'])['r_salary'].mean().reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 181,
   "id": "6a2ad17e-537c-4a7f-bc10-d2b074cda2bc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>gender</th>\n",
       "      <th>edu_grade</th>\n",
       "      <th>r_salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>대학이상</td>\n",
       "      <td>6367.245955</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>전문대</td>\n",
       "      <td>4950.893023</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>고교</td>\n",
       "      <td>4840.675978</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2</td>\n",
       "      <td>대학이상</td>\n",
       "      <td>4275.194444</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2</td>\n",
       "      <td>고교</td>\n",
       "      <td>3134.636364</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1</td>\n",
       "      <td>중학이하</td>\n",
       "      <td>2868.162162</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2</td>\n",
       "      <td>전문대</td>\n",
       "      <td>2696.875000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>2</td>\n",
       "      <td>중학이하</td>\n",
       "      <td>1954.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   gender edu_grade     r_salary\n",
       "1       1      대학이상  6367.245955\n",
       "2       1       전문대  4950.893023\n",
       "0       1        고교  4840.675978\n",
       "5       2      대학이상  4275.194444\n",
       "4       2        고교  3134.636364\n",
       "3       1      중학이하  2868.162162\n",
       "6       2       전문대  2696.875000\n",
       "7       2      중학이하  1954.000000"
      ]
     },
     "execution_count": 181,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.sort_values(by='r_salary', ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "id": "6fd4473a-934e-4455-a553-e2785ea0f84e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>gender</th>\n",
       "      <th>edu_grade</th>\n",
       "      <th>r_salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>고교</td>\n",
       "      <td>4840.675978</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2</td>\n",
       "      <td>고교</td>\n",
       "      <td>3134.636364</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   gender edu_grade     r_salary\n",
       "0       1        고교  4840.675978\n",
       "4       2        고교  3134.636364"
      ]
     },
     "execution_count": 183,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.drop_duplicates('gender')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3e9d46b5-9cc8-4226-8f58-aa624fe1d7dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pandas의 drop_duplicates() 함수는 중복된 값을 지울 때 \n",
    "# \"무조건 맨 위에 있는 것(First) 하나만 살려둔다\"는 기본 규칙"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cfc12464-c3e9-48cd-b71f-ff068e1e4f79",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 04 서울의 음식점에 관한 데이터이다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "id": "7d484347-0d2f-465c-8612-231d069bef6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1) 데이터 불러오기\n",
    "import pandas as pd\n",
    "food=pd.read_csv(\"c:/data/6110000_서울특별시_07_24_04_P_일반음식점.csv\",encoding='cp949',\n",
    "na_values=\"\",low_memory=False)\n",
    "# na_values=\"\" (빈칸을 결측치로 통일)\n",
    "# low_memory=False (대용량 파일 경고 끄기)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75210fb2-648a-413f-a755-e241e9aa4612",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2) 변수 이름을 변경하고 필요한 열을 선택한다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 189,
   "id": "ccfb4991-4a6a-48a5-9649-a58714c080ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "food1=food.rename(columns={'인허가일자': 'open_date',\n",
    "'상세영업상태명': 'status',\n",
    "'폐업일자': 'close_date',\n",
    "'사업장명': 'name',\n",
    "'업태구분명': 'type',\n",
    "'소재지전체주소': 'address'})\n",
    "food1=food1[['open_date', 'status', 'name', 'close_date', \n",
    "'type', 'address']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56a2f358-c907-4d48-8551-59dfe8783497",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3)분석 데이터 구조를 파악한다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 191,
   "id": "9599231a-0f83-4641-98c7-910283c4721b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 474140 entries, 0 to 474139\n",
      "Data columns (total 6 columns):\n",
      " #   Column      Non-Null Count   Dtype  \n",
      "---  ------      --------------   -----  \n",
      " 0   open_date   474140 non-null  int64  \n",
      " 1   status      474140 non-null  object \n",
      " 2   name        474139 non-null  object \n",
      " 3   close_date  349716 non-null  float64\n",
      " 4   type        474119 non-null  object \n",
      " 5   address     473903 non-null  object \n",
      "dtypes: float64(1), int64(1), object(4)\n",
      "memory usage: 21.7+ MB\n"
     ]
    }
   ],
   "source": [
    " food1.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 195,
   "id": "3840cacb-4c50-490a-8df2-0f597bd0cc02",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "open_date          0\n",
       "status             0\n",
       "name               1\n",
       "close_date    124424\n",
       "type              21\n",
       "address          237\n",
       "dtype: int64"
      ]
     },
     "execution_count": 195,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 4)분석변수의 결측치를 확인한다.\n",
    "food1.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 197,
   "id": "c222ddea-0284-4f8a-b2bf-1846f044e21f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "type\n",
       "한식                 200172\n",
       "분식                  78766\n",
       "경양식                 47987\n",
       "호프/통닭               34974\n",
       "기타                  33313\n",
       "일식                  17804\n",
       "중국식                 14858\n",
       "정종/대포집/소주방          12757\n",
       "통닭(치킨)               9550\n",
       "까페                   7904\n",
       "패스트푸드                3911\n",
       "뷔페식                  2791\n",
       "외국음식전문점(인도,태국등)      1993\n",
       "김밥(도시락)              1537\n",
       "식육(숯불구이)             1445\n",
       "횟집                   1430\n",
       "전통찻집                  823\n",
       "탕류(보신용)               413\n",
       "출장조리                  370\n",
       "감성주점                  349\n",
       "라이브카페                 276\n",
       "패밀리레스트랑               238\n",
       "냉면집                   126\n",
       "복어취급                  113\n",
       "키즈카페                  101\n",
       "이동조리                  101\n",
       "커피숍                     5\n",
       "기타 휴게음식점                3\n",
       "일반조리판매                  2\n",
       "룸살롱                     1\n",
       "식품등 수입판매업               1\n",
       "간이주점                    1\n",
       "다방                      1\n",
       "제과점영업                   1\n",
       "식품소분업                   1\n",
       "193959.1505             1\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 197,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 5) 유사 업종을 통합 변수로 변경한다.\n",
    "food1['type'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "id": "974eb185-c422-4ca7-b182-b117a040de03",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "food1['type'] = food1['type'].replace([\"까페\", \"다방\", \"라이브카페\", \"커피숍\", \"카페\"], \"카페\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 201,
   "id": "b358fd27-2b9f-4eea-94b1-6246d779eb9a",
   "metadata": {},
   "outputs": [],
   "source": [
    " food1['type']=food1['type'].replace([\"통닭(치킨)\", \"호프/통닭\"], \"치킨\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 203,
   "id": "c02b0f0e-25bf-49f1-bdea-a811fb735df3",
   "metadata": {},
   "outputs": [],
   "source": [
    "food1['type']=food1['type'].replace([\"일식\", \"회집\", \"횟집\"], \"회집\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 205,
   "id": "1c91f03c-5be8-4d1e-98d1-7fcbe0484ee8",
   "metadata": {},
   "outputs": [],
   "source": [
    " food1['type']=food1['type'].replace([\"경양식\", \"패밀리레스토랑\"], \"레스토랑\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 207,
   "id": "52c8d5ef-05c9-4825-bed1-118b3b4dce50",
   "metadata": {},
   "outputs": [],
   "source": [
    " food1['type']=food1['type'].replace(\"정종/대포집/소주방\", \"소주방\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 209,
   "id": "0317f592-a4df-4475-a804-fd31eab92981",
   "metadata": {},
   "outputs": [],
   "source": [
    " food1['type']=food1['type'].replace(\"외국음식전문점(인도,태국등)\", \"외국음식전문점\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 211,
   "id": "f805cd0d-5d86-4db5-9be0-ef383e773257",
   "metadata": {},
   "outputs": [],
   "source": [
    " food1['type']=food1['type'].replace([\"기타\", \"193959.1505\"], pd.NA)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 213,
   "id": "3dbe8092-5e46-41fd-8f28-1599c1bcd5a2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "19000531"
      ]
     },
     "execution_count": 213,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 6) 파생변수 생성하기\n",
    "food1['open_date'].min()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 215,
   "id": "e6e2d186-91ab-4316-a55e-762a0b8faebd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "20220401"
      ]
     },
     "execution_count": 215,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "food1['open_date'].max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 217,
   "id": "018b3b5b-6226-4372-ac51-8354daaac18f",
   "metadata": {},
   "outputs": [],
   "source": [
    "food1.loc[food1['open_date'] < 19700301, 'open_date'] = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 219,
   "id": "93e90d38-4374-4467-8e9c-8a1c4f59744a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0         20200803.0\n",
       "1         20200803.0\n",
       "2         20200803.0\n",
       "3         20200803.0\n",
       "4         20200803.0\n",
       "             ...    \n",
       "474135    20210202.0\n",
       "474136    20210202.0\n",
       "474137    20210202.0\n",
       "474138    20210203.0\n",
       "474139    20201208.0\n",
       "Name: open_date, Length: 474140, dtype: float64"
      ]
     },
     "execution_count": 219,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "food1['open_date']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 221,
   "id": "27ebc777-94f8-48df-b449-02524cfdace9",
   "metadata": {},
   "outputs": [],
   "source": [
    "food1['open_date']=food1['open_date'].astype(str)\n",
    "food1['open_year']=food1['open_date'].str.slice(0,4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 223,
   "id": "c0a88038-b845-4253-9168-f52098359697",
   "metadata": {},
   "outputs": [],
   "source": [
    "food1['close_date']=food1['close_date'].astype(str)\n",
    "food1['close_year']=food1['close_date'].str.slice(0,4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc75fe1f-a897-4a9f-a06e-cc5c4fe60ff7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (1) 가장 오래된 영업 중인 음식점업의 open_year와 type,name을 출력하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 225,
   "id": "515cb9b9-84d1-43a3-95f7-88f02324cef2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "filtered_food1=food1[(~food1['open_date'].isna()) & (food1['status']==\"영업\")]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 227,
   "id": "96ee361c-66cf-480f-8a8d-a9cabc6b3783",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>open_date</th>\n",
       "      <th>status</th>\n",
       "      <th>name</th>\n",
       "      <th>close_date</th>\n",
       "      <th>type</th>\n",
       "      <th>address</th>\n",
       "      <th>open_year</th>\n",
       "      <th>close_year</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>16052</th>\n",
       "      <td>19700320.0</td>\n",
       "      <td>영업</td>\n",
       "      <td>경원집</td>\n",
       "      <td>nan</td>\n",
       "      <td>한식</td>\n",
       "      <td>서울특별시 종로구 적선동 27-0번지</td>\n",
       "      <td>1970</td>\n",
       "      <td>nan</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        open_date status name close_date type               address open_year  \\\n",
       "16052  19700320.0     영업  경원집        nan   한식  서울특별시 종로구 적선동 27-0번지      1970   \n",
       "\n",
       "      close_year  \n",
       "16052        nan  "
      ]
     },
     "execution_count": 227,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " filtered_food1[filtered_food1['open_date'] == filtered_food1['open_date'].min()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1285a5ae-9b78-48b4-a7be-c99d2d061982",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) 개업한 전체 음식점에서 상위 3개 업종의 비율을 출력하시오.\n",
    "# (단 비율은 소숫점 둘째 자리까지 반올림한다.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 229,
   "id": "8e700bd8-cc20-4932-982c-42624b1f2f8b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "filtered_food1=food1[~food1['open_date'].isna() & ~food1['type'].isna()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 231,
   "id": "87fd225f-f7fb-4a0c-a0b9-3de078068ace",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "type\n",
       "간이주점              1\n",
       "감성주점            349\n",
       "기타 휴게음식점          3\n",
       "김밥(도시락)        1537\n",
       "냉면집             126\n",
       "레스토랑          47987\n",
       "룸살롱               1\n",
       "복어취급            113\n",
       "분식            78766\n",
       "뷔페식            2791\n",
       "소주방           12757\n",
       "식육(숯불구이)       1445\n",
       "식품등 수입판매업         1\n",
       "식품소분업             1\n",
       "외국음식전문점        1993\n",
       "이동조리            101\n",
       "일반조리판매            2\n",
       "전통찻집            823\n",
       "제과점영업             1\n",
       "중국식           14858\n",
       "출장조리            370\n",
       "치킨            44524\n",
       "카페             8186\n",
       "키즈카페            101\n",
       "탕류(보신용)         413\n",
       "패밀리레스트랑         238\n",
       "패스트푸드          3911\n",
       "한식           200172\n",
       "회집            19234\n",
       "dtype: int64"
      ]
     },
     "execution_count": 231,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " filtered_food1.groupby('type').size()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 233,
   "id": "250fe6df-1ad1-45a4-9790-92fd35126884",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>type</th>\n",
       "      <th>n</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>간이주점</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>감성주점</td>\n",
       "      <td>349</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>기타 휴게음식점</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>김밥(도시락)</td>\n",
       "      <td>1537</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>냉면집</td>\n",
       "      <td>126</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>레스토랑</td>\n",
       "      <td>47987</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>룸살롱</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>복어취급</td>\n",
       "      <td>113</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>분식</td>\n",
       "      <td>78766</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>뷔페식</td>\n",
       "      <td>2791</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>소주방</td>\n",
       "      <td>12757</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>식육(숯불구이)</td>\n",
       "      <td>1445</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>식품등 수입판매업</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>식품소분업</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>외국음식전문점</td>\n",
       "      <td>1993</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>이동조리</td>\n",
       "      <td>101</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>일반조리판매</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>전통찻집</td>\n",
       "      <td>823</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>제과점영업</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>19</th>\n",
       "      <td>중국식</td>\n",
       "      <td>14858</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>출장조리</td>\n",
       "      <td>370</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>치킨</td>\n",
       "      <td>44524</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>22</th>\n",
       "      <td>카페</td>\n",
       "      <td>8186</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>23</th>\n",
       "      <td>키즈카페</td>\n",
       "      <td>101</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>24</th>\n",
       "      <td>탕류(보신용)</td>\n",
       "      <td>413</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25</th>\n",
       "      <td>패밀리레스트랑</td>\n",
       "      <td>238</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>26</th>\n",
       "      <td>패스트푸드</td>\n",
       "      <td>3911</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>27</th>\n",
       "      <td>한식</td>\n",
       "      <td>200172</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>28</th>\n",
       "      <td>회집</td>\n",
       "      <td>19234</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         type       n\n",
       "0        간이주점       1\n",
       "1        감성주점     349\n",
       "2    기타 휴게음식점       3\n",
       "3     김밥(도시락)    1537\n",
       "4         냉면집     126\n",
       "5        레스토랑   47987\n",
       "6         룸살롱       1\n",
       "7        복어취급     113\n",
       "8          분식   78766\n",
       "9         뷔페식    2791\n",
       "10        소주방   12757\n",
       "11   식육(숯불구이)    1445\n",
       "12  식품등 수입판매업       1\n",
       "13      식품소분업       1\n",
       "14    외국음식전문점    1993\n",
       "15       이동조리     101\n",
       "16     일반조리판매       2\n",
       "17       전통찻집     823\n",
       "18      제과점영업       1\n",
       "19        중국식   14858\n",
       "20       출장조리     370\n",
       "21         치킨   44524\n",
       "22         카페    8186\n",
       "23       키즈카페     101\n",
       "24    탕류(보신용)     413\n",
       "25    패밀리레스트랑     238\n",
       "26      패스트푸드    3911\n",
       "27         한식  200172\n",
       "28         회집   19234"
      ]
     },
     "execution_count": 233,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "filtered_food1.groupby('type').size().reset_index(name='n')\n",
    "# reset_index()만 사용하면, 파이썬은 임의로 0 변수명이 생성\n",
    "# name='n' 숫자가 들어가는 열(Column)에 의미 없는 '0' 대신 내가 원하는 열이름 생"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 235,
   "id": "55353c70-3b62-497a-ac5a-a34aafd26a01",
   "metadata": {},
   "outputs": [],
   "source": [
    " type_counts = filtered_food1.groupby('type').size().reset_index(name='n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 237,
   "id": "08bfcdc4-d4d8-4fef-a950-e19080167398",
   "metadata": {},
   "outputs": [],
   "source": [
    "type_counts['total']=type_counts['n'].sum()\n",
    "type_counts['pct']=round(type_counts['n'] / type_counts['total'] * 100, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 241,
   "id": "6ee2b0e8-5d7e-4433-858b-432cb9198fee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>type</th>\n",
       "      <th>n</th>\n",
       "      <th>total</th>\n",
       "      <th>pct</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>27</th>\n",
       "      <td>한식</td>\n",
       "      <td>200172</td>\n",
       "      <td>440805</td>\n",
       "      <td>45.41</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>분식</td>\n",
       "      <td>78766</td>\n",
       "      <td>440805</td>\n",
       "      <td>17.87</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>레스토랑</td>\n",
       "      <td>47987</td>\n",
       "      <td>440805</td>\n",
       "      <td>10.89</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    type       n   total    pct\n",
       "27    한식  200172  440805  45.41\n",
       "8     분식   78766  440805  17.87\n",
       "5   레스토랑   47987  440805  10.89"
      ]
     },
     "execution_count": 241,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type_counts.sort_values(by='n', ascending=False).head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c6e8c30-038e-43c5-b29c-f870590e1b68",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c751718b-8845-402e-9574-a7c4c3d0eaa5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1423c6b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# CHAPTER 03.작업형 제 1유형\n",
    "# 작업형 제1유형 출제유형: 3문항*10점=30점\n",
    "# 데이터에서 특정행을 순서대로 추출하고, 특정 열변수의 결측치를 중앙값 \n",
    "# 대체 후에 기초 통계량을 출력하는 문제는 매회 출제\n",
    "# 사분위수, 특정열의 비율,이상치의 합, 평균 등 기초통계량을 출제  \n",
    "# 시계열 데이터 전처리 관련 출제 예상"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4eafe90b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 01. \n",
    "# import pandas as pd\n",
    "# house=pd.read_csv(\"c:/data/housing.csv\")\n",
    "# 캘리포니아 주택 데이터에서 결측치가 있는 경우 해당 데이터 행을 제외하고 \n",
    "# 첫 번째 행부터 순서대로 70% 데이터를 추출하여 \"housing_median_age’변수의 \n",
    "# Q1(1사분위) 값을 정수로 출력하시오.\n",
    "# print(), cat()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "id": "34ad6831",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   longitude  latitude  housing_median_age  total_rooms  total_bedrooms  \\\n",
      "0    -122.23     37.88                  41          880           129.0   \n",
      "1    -122.22     37.86                  21         7099          1106.0   \n",
      "2    -122.24     37.85                  52         1467           190.0   \n",
      "\n",
      "   population  households  median_income  median_house_value ocean_proximity  \n",
      "0         322         126         8.3252              452600        NEAR BAY  \n",
      "1        2401        1138         8.3014              358500        NEAR BAY  \n",
      "2         496         177         7.2574              352100        NEAR BAY  \n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "house=pd.read_csv(\"c:/data/housing.csv\")\n",
    "print(house.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "id": "adf318ae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 20640 entries, 0 to 20639\n",
      "Data columns (total 10 columns):\n",
      " #   Column              Non-Null Count  Dtype  \n",
      "---  ------              --------------  -----  \n",
      " 0   longitude           20640 non-null  float64\n",
      " 1   latitude            20640 non-null  float64\n",
      " 2   housing_median_age  20640 non-null  int64  \n",
      " 3   total_rooms         20640 non-null  int64  \n",
      " 4   total_bedrooms      20433 non-null  float64\n",
      " 5   population          20640 non-null  int64  \n",
      " 6   households          20640 non-null  int64  \n",
      " 7   median_income       20640 non-null  float64\n",
      " 8   median_house_value  20640 non-null  int64  \n",
      " 9   ocean_proximity     20640 non-null  object \n",
      "dtypes: float64(4), int64(5), object(1)\n",
      "memory usage: 1.6+ MB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(house.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "id": "cfefbb33",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "longitude               0\n",
      "latitude                0\n",
      "housing_median_age      0\n",
      "total_rooms             0\n",
      "total_bedrooms        207\n",
      "population              0\n",
      "households              0\n",
      "median_income           0\n",
      "median_house_value      0\n",
      "ocean_proximity         0\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(house.isna().sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "id": "d890d144",
   "metadata": {},
   "outputs": [],
   "source": [
    "house_dropna=house.dropna( )\n",
    "# Pandas에서 공통적으로 inplace 인수는 원본의 수정을 의미합니다. \n",
    "# inplace가 True인 경우 원본이 수정됩니다\n",
    "# axis = 0 (default) : 행 버리기\n",
    "# inplace = False (default) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "c29cb784",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "longitude             0\n",
       "latitude              0\n",
       "housing_median_age    0\n",
       "total_rooms           0\n",
       "total_bedrooms        0\n",
       "population            0\n",
       "households            0\n",
       "median_income         0\n",
       "median_house_value    0\n",
       "ocean_proximity       0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 157,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "house_dropna.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e2aa8570",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pandas의 DataFrame, Series 의 행, 열의 개수\n",
    "# len(데이터프레임),len(시리즈)\n",
    "# 파이썬 내장함수 int()를 이용해서 숫자나 문자열을 정수형 (Integer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "id": "3d9d5324",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14303"
      ]
     },
     "execution_count": 158,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "int(len(house_dropna)*0.7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "f137aa34",
   "metadata": {},
   "outputs": [],
   "source": [
    "house_drona_70=house_dropna.iloc[:int(len(house_dropna)*0.7)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b65de3b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# housing_median_age’변수의 Q1(1사분위) 값을 정수로 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "id": "ae6851ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=int(house_drona_70['housing_median_age'].quantile(.25))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 161,
   "id": "ae0295ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "19\n"
     ]
    }
   ],
   "source": [
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88f506c5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "158b7869",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 02. \n",
    "#  import pandas as pd \n",
    "#  house=pd.read_csv(\"c:/data/housing.csv\")\n",
    "#  캘리포니아 주택 데이터에서 첫번째 행부터 순서대로 80%까지의 데이터를 추출한후\n",
    "# ‘total_bedrooms’변수의 결측값(NA)을 total_bedrooms’변수의 중앙값으로 대체하고 \n",
    "#  대체전의 ‘total_bedrooms’ 변수의 표준편차와 대체 후에 표준편차의 차이를 출력하시오\n",
    "#  print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "40a04fd7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   longitude  latitude  housing_median_age  total_rooms  total_bedrooms  \\\n",
      "0    -122.23     37.88                  41          880           129.0   \n",
      "1    -122.22     37.86                  21         7099          1106.0   \n",
      "2    -122.24     37.85                  52         1467           190.0   \n",
      "\n",
      "   population  households  median_income  median_house_value ocean_proximity  \n",
      "0         322         126         8.3252              452600        NEAR BAY  \n",
      "1        2401        1138         8.3014              358500        NEAR BAY  \n",
      "2         496         177         7.2574              352100        NEAR BAY  \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(20640, 10)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "house=pd.read_csv(\"c:/data/housing.csv\")\n",
    "print(house.head(3))\n",
    "house.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "805cf622",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 첫번째 행부터 순서대로 80%까지의 데이터를 추출한후"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ccc60e0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "house_80=house.iloc[:int(len(house)*0.8)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "25f49d57",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(16512, 10)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "house_80.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "f4fb04aa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "longitude               0\n",
       "latitude                0\n",
       "housing_median_age      0\n",
       "total_rooms             0\n",
       "total_bedrooms        159\n",
       "population              0\n",
       "households              0\n",
       "median_income           0\n",
       "median_house_value      0\n",
       "ocean_proximity         0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 159,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "house_80.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 161,
   "id": "50519717",
   "metadata": {},
   "outputs": [],
   "source": [
    "#  대체전의 ‘total_bedrooms’ 변수의 표준편차"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e8f4ae9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "df1=house_80[\"total_bedrooms\"].std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "70cd4cc4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "435.900577052527\n"
     ]
    }
   ],
   "source": [
    "print(df1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 169,
   "id": "c9017af0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 중앙값으로 대체하기\n",
    "df2=house_80.fillna(house_80.median(numeric_only=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 171,
   "id": "8f1f768b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# mean()함수의 numeric_only=True 옵션은 해당 데이터프레임에서 숫자값을 가지는 \n",
    "# 칼럼에 대해서만 평균값을 계산하겠다는 뜻이다. 옵션을 주지 않으면 아래 경고 발생\n",
    "df2=house_80.fillna(house_80.median(numeric_only=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 173,
   "id": "f42d539b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# \"total_bedrooms\" 대체 후에 표준편차"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 175,
   "id": "9a736d1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "df3=df2[\"total_bedrooms\"].std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 177,
   "id": "e93e6a87",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "433.9254297608813\n"
     ]
    }
   ],
   "source": [
    "print(df3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 179,
   "id": "4634219c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# abs() 절대값 함수"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 181,
   "id": "46657427",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.975147291645726\n"
     ]
    }
   ],
   "source": [
    "ans=abs(df1-df3)\n",
    "print(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "c705fc62",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 03.\n",
    "# import pandas as pd\n",
    "# titanic=pd.read_csv(\"c:/data/train_df1.csv\")\n",
    "# 타이타닉(titanic data)의 컬럼 중 빈값 또는 결측치를 확인하여, \n",
    "# 결측치의 비율이 가장 높은 변수명을 출력하시오.\n",
    "# print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "6fb551af",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "258a1942",
   "metadata": {},
   "outputs": [],
   "source": [
    "titanic=pd.read_csv(\"c:/data/train_df1.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "930e8122",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>PassengerId</th>\n",
       "      <th>Survived</th>\n",
       "      <th>Pclass</th>\n",
       "      <th>Name</th>\n",
       "      <th>Sex</th>\n",
       "      <th>Age</th>\n",
       "      <th>SibSp</th>\n",
       "      <th>Parch</th>\n",
       "      <th>Ticket</th>\n",
       "      <th>Fare</th>\n",
       "      <th>Cabin</th>\n",
       "      <th>Embarked</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>3</td>\n",
       "      <td>Braund, Mr. Owen Harris</td>\n",
       "      <td>male</td>\n",
       "      <td>22.0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>A/5 21171</td>\n",
       "      <td>7.2500</td>\n",
       "      <td>NaN</td>\n",
       "      <td>S</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>Cumings, Mrs. John Bradley (Florence Briggs Th...</td>\n",
       "      <td>female</td>\n",
       "      <td>38.0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>PC 17599</td>\n",
       "      <td>71.2833</td>\n",
       "      <td>C85</td>\n",
       "      <td>C</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>Heikkinen, Miss. Laina</td>\n",
       "      <td>female</td>\n",
       "      <td>26.0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>STON/O2. 3101282</td>\n",
       "      <td>7.9250</td>\n",
       "      <td>NaN</td>\n",
       "      <td>S</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   PassengerId  Survived  Pclass  \\\n",
       "0            1         0       3   \n",
       "1            2         1       1   \n",
       "2            3         1       3   \n",
       "\n",
       "                                                Name     Sex   Age  SibSp  \\\n",
       "0                            Braund, Mr. Owen Harris    male  22.0      1   \n",
       "1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   \n",
       "2                             Heikkinen, Miss. Laina  female  26.0      0   \n",
       "\n",
       "   Parch            Ticket     Fare Cabin Embarked  \n",
       "0      0         A/5 21171   7.2500   NaN        S  \n",
       "1      0          PC 17599  71.2833   C85        C  \n",
       "2      0  STON/O2. 3101282   7.9250   NaN        S  "
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "titanic.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "dc105238",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 891 entries, 0 to 890\n",
      "Data columns (total 12 columns):\n",
      " #   Column       Non-Null Count  Dtype  \n",
      "---  ------       --------------  -----  \n",
      " 0   PassengerId  891 non-null    int64  \n",
      " 1   Survived     891 non-null    int64  \n",
      " 2   Pclass       891 non-null    int64  \n",
      " 3   Name         891 non-null    object \n",
      " 4   Sex          891 non-null    object \n",
      " 5   Age          714 non-null    float64\n",
      " 6   SibSp        891 non-null    int64  \n",
      " 7   Parch        891 non-null    int64  \n",
      " 8   Ticket       891 non-null    object \n",
      " 9   Fare         891 non-null    float64\n",
      " 10  Cabin        204 non-null    object \n",
      " 11  Embarked     889 non-null    object \n",
      "dtypes: float64(2), int64(5), object(5)\n",
      "memory usage: 83.7+ KB\n"
     ]
    }
   ],
   "source": [
    "titanic.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "f11494d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "titanic_isna=titanic.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "400dd05a-5665-44fa-91c1-667e77c70fc1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PassengerId    0.000000\n",
       "Survived       0.000000\n",
       "Pclass         0.000000\n",
       "Name           0.000000\n",
       "Sex            0.000000\n",
       "Age            0.198653\n",
       "SibSp          0.000000\n",
       "Parch          0.000000\n",
       "Ticket         0.000000\n",
       "Fare           0.000000\n",
       "Cabin          0.771044\n",
       "Embarked       0.002245\n",
       "dtype: float64"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "titanic.isna().mean()\n",
    "# 타이타닉 데이터에서 각 컬럼별 결측치 비율"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 178,
   "id": "d47452f0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PassengerId      0\n",
      "Survived         0\n",
      "Pclass           0\n",
      "Name             0\n",
      "Sex              0\n",
      "Age            177\n",
      "SibSp            0\n",
      "Parch            0\n",
      "Ticket           0\n",
      "Fare             0\n",
      "Cabin          687\n",
      "Embarked         2\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(titanic_isna)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 179,
   "id": "d0cdcf11",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 179,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(titanic_isna)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "eba92b17",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [파이썬 판다스] 시리즈에 사용되는 통계관련 함수 \n",
    "# 최대 최소 관련\n",
    "# min : 최소값\n",
    "# max : 최댓값\n",
    "# argmin : 최솟값 인덱스\n",
    "# argmax : 최댓값 인덱스"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 180,
   "id": "3d6916d2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "687"
      ]
     },
     "execution_count": 180,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "titanic_isna.max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 181,
   "id": "619dd4cf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "execution_count": 181,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "titanic_isna.argmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 182,
   "id": "55a9059c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Cabin'"
      ]
     },
     "execution_count": 182,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "titanic_isna.index[10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "id": "b24bdab4",
   "metadata": {},
   "outputs": [],
   "source": [
    "ans=titanic_isna.index[10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 184,
   "id": "1b810cc9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cabin\n"
     ]
    }
   ],
   "source": [
    "print(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "407fde04",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 04.\n",
    "# import pandas as pd\n",
    "# boston=pd.read_csv(\"c:/data/boston.csv\")\n",
    "# Boston 데이터이다. 범죄율 컬럼인 CRIM 항목의 상위에서 10번째 값 \n",
    "# (범죄율을 큰 순서로 정렬했을 때 10 번째에 위치한 값)으로 상위 10개의 값을 변환한 후 \n",
    "# age가 80 이상인 데이터를 추출하여 CRIM 평균을 출력하시오\n",
    "# print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "id": "ac8035f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 186,
   "id": "179e6797",
   "metadata": {},
   "outputs": [],
   "source": [
    "boston=pd.read_csv(\"c:/data/boston.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 187,
   "id": "1dbe1d91",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      CRIM    ZN  INDUS  CHAS    NOX     RM   AGE     DIS  RAD  TAX  PTRATIO  \\\n",
      "0  0.00632  18.0   2.31     0  0.538  6.575  65.2  4.0900    1  296     15.3   \n",
      "1  0.02731   0.0   7.07     0  0.469  6.421  78.9  4.9671    2  242     17.8   \n",
      "2  0.02729   0.0   7.07     0  0.469  7.185  61.1  4.9671    2  242     17.8   \n",
      "\n",
      "        B  LSTAT  MEDV  \n",
      "0  396.90   4.98  24.0  \n",
      "1  396.90   9.14  21.6  \n",
      "2  392.83   4.03  34.7  \n"
     ]
    }
   ],
   "source": [
    "print(boston.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 188,
   "id": "5807b678",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 506 entries, 0 to 505\n",
      "Data columns (total 14 columns):\n",
      " #   Column   Non-Null Count  Dtype  \n",
      "---  ------   --------------  -----  \n",
      " 0   CRIM     506 non-null    float64\n",
      " 1   ZN       506 non-null    float64\n",
      " 2   INDUS    506 non-null    float64\n",
      " 3   CHAS     506 non-null    int64  \n",
      " 4   NOX      506 non-null    float64\n",
      " 5   RM       491 non-null    float64\n",
      " 6   AGE      506 non-null    float64\n",
      " 7   DIS      506 non-null    float64\n",
      " 8   RAD      506 non-null    int64  \n",
      " 9   TAX      506 non-null    int64  \n",
      " 10  PTRATIO  506 non-null    float64\n",
      " 11  B        506 non-null    float64\n",
      " 12  LSTAT    506 non-null    float64\n",
      " 13  MEDV     506 non-null    float64\n",
      "dtypes: float64(11), int64(3)\n",
      "memory usage: 55.5 KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(boston.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "3965b244",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 범죄율 컬럼인 crim 항목의 상위에서 10번째 값(즉, \n",
    "# 범죄율을 큰 순서로 정렬했을 때 10 번째에 위치한 값)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 189,
   "id": "55aa7ce1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>CRIM</th>\n",
       "      <th>ZN</th>\n",
       "      <th>INDUS</th>\n",
       "      <th>CHAS</th>\n",
       "      <th>NOX</th>\n",
       "      <th>RM</th>\n",
       "      <th>AGE</th>\n",
       "      <th>DIS</th>\n",
       "      <th>RAD</th>\n",
       "      <th>TAX</th>\n",
       "      <th>PTRATIO</th>\n",
       "      <th>B</th>\n",
       "      <th>LSTAT</th>\n",
       "      <th>MEDV</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>380</th>\n",
       "      <td>88.9762</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.671</td>\n",
       "      <td>6.968</td>\n",
       "      <td>91.9</td>\n",
       "      <td>1.4165</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>396.90</td>\n",
       "      <td>17.21</td>\n",
       "      <td>10.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>418</th>\n",
       "      <td>73.5341</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.679</td>\n",
       "      <td>5.957</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.8026</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>16.45</td>\n",
       "      <td>20.62</td>\n",
       "      <td>8.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>405</th>\n",
       "      <td>67.9208</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>5.683</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.4254</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>384.97</td>\n",
       "      <td>22.98</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        CRIM   ZN  INDUS  CHAS    NOX     RM    AGE     DIS  RAD  TAX  \\\n",
       "380  88.9762  0.0   18.1     0  0.671  6.968   91.9  1.4165   24  666   \n",
       "418  73.5341  0.0   18.1     0  0.679  5.957  100.0  1.8026   24  666   \n",
       "405  67.9208  0.0   18.1     0  0.693  5.683  100.0  1.4254   24  666   \n",
       "\n",
       "     PTRATIO       B  LSTAT  MEDV  \n",
       "380     20.2  396.90  17.21  10.4  \n",
       "418     20.2   16.45  20.62   8.8  \n",
       "405     20.2  384.97  22.98   5.0  "
      ]
     },
     "execution_count": 189,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "boston.sort_values('CRIM',ascending=False).head(3) # 내림차순 정렬"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 190,
   "id": "36467e6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "boston_sort=boston.sort_values('CRIM',ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 191,
   "id": "8d747fef",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>CRIM</th>\n",
       "      <th>ZN</th>\n",
       "      <th>INDUS</th>\n",
       "      <th>CHAS</th>\n",
       "      <th>NOX</th>\n",
       "      <th>RM</th>\n",
       "      <th>AGE</th>\n",
       "      <th>DIS</th>\n",
       "      <th>RAD</th>\n",
       "      <th>TAX</th>\n",
       "      <th>PTRATIO</th>\n",
       "      <th>B</th>\n",
       "      <th>LSTAT</th>\n",
       "      <th>MEDV</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>380</th>\n",
       "      <td>88.9762</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.671</td>\n",
       "      <td>6.968</td>\n",
       "      <td>91.9</td>\n",
       "      <td>1.4165</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>396.90</td>\n",
       "      <td>17.21</td>\n",
       "      <td>10.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>418</th>\n",
       "      <td>73.5341</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.679</td>\n",
       "      <td>5.957</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.8026</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>16.45</td>\n",
       "      <td>20.62</td>\n",
       "      <td>8.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>405</th>\n",
       "      <td>67.9208</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>5.683</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.4254</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>384.97</td>\n",
       "      <td>22.98</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>410</th>\n",
       "      <td>51.1358</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.597</td>\n",
       "      <td>5.757</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.4130</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>2.60</td>\n",
       "      <td>10.11</td>\n",
       "      <td>15.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>414</th>\n",
       "      <td>45.7461</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>4.519</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.6582</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>88.27</td>\n",
       "      <td>36.98</td>\n",
       "      <td>7.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>404</th>\n",
       "      <td>41.5292</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>5.531</td>\n",
       "      <td>85.4</td>\n",
       "      <td>1.6074</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>329.46</td>\n",
       "      <td>27.38</td>\n",
       "      <td>8.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>398</th>\n",
       "      <td>38.3518</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>NaN</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.4896</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>396.90</td>\n",
       "      <td>30.59</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>427</th>\n",
       "      <td>37.6619</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.679</td>\n",
       "      <td>6.202</td>\n",
       "      <td>78.7</td>\n",
       "      <td>1.8629</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>18.82</td>\n",
       "      <td>14.52</td>\n",
       "      <td>10.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>413</th>\n",
       "      <td>28.6558</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.597</td>\n",
       "      <td>5.155</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.5894</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>210.97</td>\n",
       "      <td>20.08</td>\n",
       "      <td>16.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>417</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.679</td>\n",
       "      <td>5.304</td>\n",
       "      <td>89.1</td>\n",
       "      <td>1.6475</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>127.36</td>\n",
       "      <td>26.64</td>\n",
       "      <td>10.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>400</th>\n",
       "      <td>25.0461</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>5.987</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.5888</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>396.90</td>\n",
       "      <td>26.77</td>\n",
       "      <td>5.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        CRIM   ZN  INDUS  CHAS    NOX     RM    AGE     DIS  RAD  TAX  \\\n",
       "380  88.9762  0.0   18.1     0  0.671  6.968   91.9  1.4165   24  666   \n",
       "418  73.5341  0.0   18.1     0  0.679  5.957  100.0  1.8026   24  666   \n",
       "405  67.9208  0.0   18.1     0  0.693  5.683  100.0  1.4254   24  666   \n",
       "410  51.1358  0.0   18.1     0  0.597  5.757  100.0  1.4130   24  666   \n",
       "414  45.7461  0.0   18.1     0  0.693  4.519  100.0  1.6582   24  666   \n",
       "404  41.5292  0.0   18.1     0  0.693  5.531   85.4  1.6074   24  666   \n",
       "398  38.3518  0.0   18.1     0  0.693    NaN  100.0  1.4896   24  666   \n",
       "427  37.6619  0.0   18.1     0  0.679  6.202   78.7  1.8629   24  666   \n",
       "413  28.6558  0.0   18.1     0  0.597  5.155  100.0  1.5894   24  666   \n",
       "417  25.9406  0.0   18.1     0  0.679  5.304   89.1  1.6475   24  666   \n",
       "400  25.0461  0.0   18.1     0  0.693  5.987  100.0  1.5888   24  666   \n",
       "\n",
       "     PTRATIO       B  LSTAT  MEDV  \n",
       "380     20.2  396.90  17.21  10.4  \n",
       "418     20.2   16.45  20.62   8.8  \n",
       "405     20.2  384.97  22.98   5.0  \n",
       "410     20.2    2.60  10.11  15.0  \n",
       "414     20.2   88.27  36.98   7.0  \n",
       "404     20.2  329.46  27.38   8.5  \n",
       "398     20.2  396.90  30.59   5.0  \n",
       "427     20.2   18.82  14.52  10.9  \n",
       "413     20.2  210.97  20.08  16.3  \n",
       "417     20.2  127.36  26.64  10.4  \n",
       "400     20.2  396.90  26.77   5.6  "
      ]
     },
     "execution_count": 191,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "boston_sort.head(11)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 192,
   "id": "6e805dfc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "25.9406"
      ]
     },
     "execution_count": 192,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "boston_sort.iloc[9,0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 193,
   "id": "10f04c0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "crim_10=boston_sort.iloc[9,0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 194,
   "id": "739f9e2f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25.9406\n"
     ]
    }
   ],
   "source": [
    "print(crim_10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "bfab56de",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 'CRIM' 변수의 상위 10개의 값을 변환"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 195,
   "id": "8b07f7e1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "380    88.9762\n",
       "418    73.5341\n",
       "405    67.9208\n",
       "410    51.1358\n",
       "414    45.7461\n",
       "404    41.5292\n",
       "398    38.3518\n",
       "427    37.6619\n",
       "413    28.6558\n",
       "417    25.9406\n",
       "Name: CRIM, dtype: float64"
      ]
     },
     "execution_count": 195,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "boston_sort.iloc[:10,0] "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 196,
   "id": "21e7cb1d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>CRIM</th>\n",
       "      <th>ZN</th>\n",
       "      <th>INDUS</th>\n",
       "      <th>CHAS</th>\n",
       "      <th>NOX</th>\n",
       "      <th>RM</th>\n",
       "      <th>AGE</th>\n",
       "      <th>DIS</th>\n",
       "      <th>RAD</th>\n",
       "      <th>TAX</th>\n",
       "      <th>PTRATIO</th>\n",
       "      <th>B</th>\n",
       "      <th>LSTAT</th>\n",
       "      <th>MEDV</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>380</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.671</td>\n",
       "      <td>6.968</td>\n",
       "      <td>91.9</td>\n",
       "      <td>1.4165</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>396.90</td>\n",
       "      <td>17.21</td>\n",
       "      <td>10.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>418</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.679</td>\n",
       "      <td>5.957</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.8026</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>16.45</td>\n",
       "      <td>20.62</td>\n",
       "      <td>8.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>405</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>5.683</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.4254</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>384.97</td>\n",
       "      <td>22.98</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>410</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.597</td>\n",
       "      <td>5.757</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.4130</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>2.60</td>\n",
       "      <td>10.11</td>\n",
       "      <td>15.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>414</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>4.519</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.6582</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>88.27</td>\n",
       "      <td>36.98</td>\n",
       "      <td>7.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>404</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>5.531</td>\n",
       "      <td>85.4</td>\n",
       "      <td>1.6074</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>329.46</td>\n",
       "      <td>27.38</td>\n",
       "      <td>8.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>398</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>NaN</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.4896</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>396.90</td>\n",
       "      <td>30.59</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>427</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.679</td>\n",
       "      <td>6.202</td>\n",
       "      <td>78.7</td>\n",
       "      <td>1.8629</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>18.82</td>\n",
       "      <td>14.52</td>\n",
       "      <td>10.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>413</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.597</td>\n",
       "      <td>5.155</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.5894</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>210.97</td>\n",
       "      <td>20.08</td>\n",
       "      <td>16.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>417</th>\n",
       "      <td>25.9406</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.679</td>\n",
       "      <td>5.304</td>\n",
       "      <td>89.1</td>\n",
       "      <td>1.6475</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>127.36</td>\n",
       "      <td>26.64</td>\n",
       "      <td>10.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>400</th>\n",
       "      <td>25.0461</td>\n",
       "      <td>0.0</td>\n",
       "      <td>18.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.693</td>\n",
       "      <td>5.987</td>\n",
       "      <td>100.0</td>\n",
       "      <td>1.5888</td>\n",
       "      <td>24</td>\n",
       "      <td>666</td>\n",
       "      <td>20.2</td>\n",
       "      <td>396.90</td>\n",
       "      <td>26.77</td>\n",
       "      <td>5.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        CRIM   ZN  INDUS  CHAS    NOX     RM    AGE     DIS  RAD  TAX  \\\n",
       "380  25.9406  0.0   18.1     0  0.671  6.968   91.9  1.4165   24  666   \n",
       "418  25.9406  0.0   18.1     0  0.679  5.957  100.0  1.8026   24  666   \n",
       "405  25.9406  0.0   18.1     0  0.693  5.683  100.0  1.4254   24  666   \n",
       "410  25.9406  0.0   18.1     0  0.597  5.757  100.0  1.4130   24  666   \n",
       "414  25.9406  0.0   18.1     0  0.693  4.519  100.0  1.6582   24  666   \n",
       "404  25.9406  0.0   18.1     0  0.693  5.531   85.4  1.6074   24  666   \n",
       "398  25.9406  0.0   18.1     0  0.693    NaN  100.0  1.4896   24  666   \n",
       "427  25.9406  0.0   18.1     0  0.679  6.202   78.7  1.8629   24  666   \n",
       "413  25.9406  0.0   18.1     0  0.597  5.155  100.0  1.5894   24  666   \n",
       "417  25.9406  0.0   18.1     0  0.679  5.304   89.1  1.6475   24  666   \n",
       "400  25.0461  0.0   18.1     0  0.693  5.987  100.0  1.5888   24  666   \n",
       "\n",
       "     PTRATIO       B  LSTAT  MEDV  \n",
       "380     20.2  396.90  17.21  10.4  \n",
       "418     20.2   16.45  20.62   8.8  \n",
       "405     20.2  384.97  22.98   5.0  \n",
       "410     20.2    2.60  10.11  15.0  \n",
       "414     20.2   88.27  36.98   7.0  \n",
       "404     20.2  329.46  27.38   8.5  \n",
       "398     20.2  396.90  30.59   5.0  \n",
       "427     20.2   18.82  14.52  10.9  \n",
       "413     20.2  210.97  20.08  16.3  \n",
       "417     20.2  127.36  26.64  10.4  \n",
       "400     20.2  396.90  26.77   5.6  "
      ]
     },
     "execution_count": 196,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "boston_sort.iloc[:10,0] =\n",
    "\n",
    "boston_sort.head(11)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "574a63ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "# age가 80 이상인 데이터를 추출"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 197,
   "id": "4e254977",
   "metadata": {},
   "outputs": [],
   "source": [
    "boston_sort_80=boston_sort[boston_sort['AGE']>=80]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 198,
   "id": "d2861438",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.759386625"
      ]
     },
     "execution_count": 198,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "boston_sort_80['CRIM'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "id": "ebda5647",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5.759386625\n"
     ]
    }
   ],
   "source": [
    "ans=boston_sort_80['CRIM'].mean()\n",
    "print(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "0b1c5b99",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 05 \n",
    "# import pandas as pd\n",
    "# insurance=pd.read_csv(\"c:/data/insurance.csv\")\n",
    "# insurance 데이터 셋이다. charges 변수의 이상치 합을 정수로 출력하시오\n",
    "# (이상치는 평균에서 ±1.5*표준편차 이상이거나 이하인 값의 범위)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 200,
   "id": "1849db91",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 201,
   "id": "aba83c46",
   "metadata": {},
   "outputs": [],
   "source": [
    "insurance=pd.read_csv(\"c:/data/insurance.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 202,
   "id": "2e9d2fab",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>sex</th>\n",
       "      <th>bmi</th>\n",
       "      <th>children</th>\n",
       "      <th>smoker</th>\n",
       "      <th>region</th>\n",
       "      <th>charges</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>19</td>\n",
       "      <td>female</td>\n",
       "      <td>27.90</td>\n",
       "      <td>0</td>\n",
       "      <td>yes</td>\n",
       "      <td>southwest</td>\n",
       "      <td>16884.9240</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>18</td>\n",
       "      <td>male</td>\n",
       "      <td>33.77</td>\n",
       "      <td>1</td>\n",
       "      <td>no</td>\n",
       "      <td>southeast</td>\n",
       "      <td>1725.5523</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>28</td>\n",
       "      <td>male</td>\n",
       "      <td>33.00</td>\n",
       "      <td>3</td>\n",
       "      <td>no</td>\n",
       "      <td>southeast</td>\n",
       "      <td>4449.4620</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   age     sex    bmi  children smoker     region     charges\n",
       "0   19  female  27.90         0    yes  southwest  16884.9240\n",
       "1   18    male  33.77         1     no  southeast   1725.5523\n",
       "2   28    male  33.00         3     no  southeast   4449.4620"
      ]
     },
     "execution_count": 202,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "insurance.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 203,
   "id": "91ed72b3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1338 entries, 0 to 1337\n",
      "Data columns (total 7 columns):\n",
      " #   Column    Non-Null Count  Dtype  \n",
      "---  ------    --------------  -----  \n",
      " 0   age       1338 non-null   int64  \n",
      " 1   sex       1338 non-null   object \n",
      " 2   bmi       1338 non-null   float64\n",
      " 3   children  1338 non-null   int64  \n",
      " 4   smoker    1338 non-null   object \n",
      " 5   region    1338 non-null   object \n",
      " 6   charges   1338 non-null   float64\n",
      "dtypes: float64(2), int64(2), object(3)\n",
      "memory usage: 73.3+ KB\n"
     ]
    }
   ],
   "source": [
    "insurance.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 204,
   "id": "aac58b8f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "age         0\n",
       "sex         0\n",
       "bmi         0\n",
       "children    0\n",
       "smoker      0\n",
       "region      0\n",
       "charges     0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 204,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "insurance.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "1a5bbd9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 이상치의 범위를 설정하기 위해 charges 변수의 평균(mean), 표준편차(sd) 구한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 205,
   "id": "de8068e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "insurance=insurance[\"charges\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 206,
   "id": "b667b0eb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0       16884.92400\n",
       "1        1725.55230\n",
       "2        4449.46200\n",
       "3       21984.47061\n",
       "4        3866.85520\n",
       "           ...     \n",
       "1333    10600.54830\n",
       "1334     2205.98080\n",
       "1335     1629.83350\n",
       "1336     2007.94500\n",
       "1337    29141.36030\n",
       "Name: charges, Length: 1338, dtype: float64"
      ]
     },
     "execution_count": 206,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "insurance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 207,
   "id": "15963c3e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "13270.422265141257"
      ]
     },
     "execution_count": 207,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "insurance.mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 208,
   "id": "1bbbf561",
   "metadata": {},
   "outputs": [],
   "source": [
    "avg=insurance.mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 209,
   "id": "88f2b6cc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12110.011236693994"
      ]
     },
     "execution_count": 209,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "insurance.std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 210,
   "id": "b0f29827",
   "metadata": {},
   "outputs": [],
   "source": [
    "std=insurance.std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 211,
   "id": "b7f08133",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "31435.439120182247\n",
      "-4894.594589899734\n"
     ]
    }
   ],
   "source": [
    "high=avg+1.5*std\n",
    "low=avg-1.5*std\n",
    "print(high)\n",
    "print(low)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "528eee39",
   "metadata": {},
   "outputs": [],
   "source": [
    " # 평균에서 1.5*표준편차 범위를 설정하고 그 결과를 \n",
    " # outlier 객체에 저장한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 212,
   "id": "88398a6d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14      39611.75770\n",
       "19      36837.46700\n",
       "23      37701.87680\n",
       "29      38711.00000\n",
       "30      35585.57600\n",
       "           ...     \n",
       "1301    46718.16325\n",
       "1303    37829.72420\n",
       "1308    33900.65300\n",
       "1313    36397.57600\n",
       "1323    43896.37630\n",
       "Name: charges, Length: 156, dtype: float64"
      ]
     },
     "execution_count": 212,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "insurance[(insurance>=high)|\n",
    "         (insurance<=low)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 213,
   "id": "2569df4e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 213,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "outlier=insurance[(insurance>=high)|\n",
    "                  (insurance<=low)]\n",
    "type(outlier)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 214,
   "id": "19a7e903",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6421430.0206699995"
      ]
     },
     "execution_count": 214,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "outlier.sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 215,
   "id": "23298e86",
   "metadata": {},
   "outputs": [],
   "source": [
    "ans=int(outlier.sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 216,
   "id": "39940de7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6421430\n"
     ]
    }
   ],
   "source": [
    "print(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "72666614",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 06 \n",
    "# import pandas as pd\n",
    "# mtcar=pd.read_csv(\"c:/data/mtcar.csv\")\n",
    "# mtcar 데이터이다. wt 컬럼을 최소-최대 척도(min-max scale)변환한 후 0.5보다 큰 \n",
    "# 레코드 수를 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 243,
   "id": "d500eec8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 245,
   "id": "0cc507db",
   "metadata": {},
   "outputs": [],
   "source": [
    "mtcar=pd.read_csv(\"c:/data/mtcar.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 219,
   "id": "4010a4b7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>mpg</th>\n",
       "      <th>cyl</th>\n",
       "      <th>disp</th>\n",
       "      <th>hp</th>\n",
       "      <th>drat</th>\n",
       "      <th>wt</th>\n",
       "      <th>qsec</th>\n",
       "      <th>vs</th>\n",
       "      <th>am</th>\n",
       "      <th>gear</th>\n",
       "      <th>carb</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>21.0</td>\n",
       "      <td>6</td>\n",
       "      <td>160.0</td>\n",
       "      <td>110</td>\n",
       "      <td>3.90</td>\n",
       "      <td>2.620</td>\n",
       "      <td>16.46</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>21.0</td>\n",
       "      <td>6</td>\n",
       "      <td>160.0</td>\n",
       "      <td>110</td>\n",
       "      <td>3.90</td>\n",
       "      <td>2.875</td>\n",
       "      <td>17.02</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>22.8</td>\n",
       "      <td>4</td>\n",
       "      <td>108.0</td>\n",
       "      <td>93</td>\n",
       "      <td>3.85</td>\n",
       "      <td>2.320</td>\n",
       "      <td>18.61</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    mpg  cyl   disp   hp  drat     wt   qsec  vs  am  gear  carb\n",
       "0  21.0    6  160.0  110  3.90  2.620  16.46   0   1     4     4\n",
       "1  21.0    6  160.0  110  3.90  2.875  17.02   0   1     4     4\n",
       "2  22.8    4  108.0   93  3.85  2.320  18.61   1   1     4     1"
      ]
     },
     "execution_count": 219,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mtcar.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "38d4218f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 피처 스케일링 feature scaling\n",
    "# 서로 다른 변수의 값 범위를 일정한 수준으로 맞추는 작업을 피처 스케일링. \n",
    "# 표준화 = StandardScaler : 평균이 0이고 표준편차가 1인 크기로 변경\n",
    "# 정규화 = MinMaxScaler:모든 값을 0~1 사이의 값으로 바꾸는 것\n",
    "# ( X- (X의 최솟값) ) / ( X의 최댓값 - X의 최솟값 )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 220,
   "id": "18853509",
   "metadata": {},
   "outputs": [],
   "source": [
    "x=mtcar['wt']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 221,
   "id": "201f0a16",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.513"
      ]
     },
     "execution_count": 221,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.min()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 222,
   "id": "d2197acc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.424"
      ]
     },
     "execution_count": 222,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 223,
   "id": "842818be",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_MinMax=(x-x.min())/(x.max()-x.min())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 224,
   "id": "0cf18f42",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    0.283048\n",
       "1    0.348249\n",
       "2    0.206341\n",
       "Name: wt, dtype: float64"
      ]
     },
     "execution_count": 224,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_MinMax.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 225,
   "id": "5660df52",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 225,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(x_MinMax[x_MinMax>0.5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 226,
   "id": "306a352a",
   "metadata": {},
   "outputs": [],
   "source": [
    "ans=len(x_MinMax[x_MinMax>0.5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 227,
   "id": "07a9a2ee",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11\n"
     ]
    }
   ],
   "source": [
    "print(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc8dbf84",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 228,
   "id": "4cf8f856",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 229,
   "id": "1218fe04",
   "metadata": {},
   "outputs": [],
   "source": [
    "mtcar=pd.read_csv(\"c:/data/mtcar.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 230,
   "id": "ff7ea58e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# MinMaxScaler() 함수를 수행할 빈 박스 생성\n",
    "scaler=MinMaxScaler()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 231,
   "id": "40803712",
   "metadata": {},
   "outputs": [],
   "source": [
    "# MinMaxScale 변환\n",
    "mtcar_scaler=scaler.fit_transform(mtcar)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 232,
   "id": "205fc42f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "# 배열 타입으로 출력\n",
    "# mtcar_scaler\n",
    "print(type(mtcar_scaler))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 233,
   "id": "542ea1fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "mtcar_df=pd.DataFrame(mtcar_scaler,columns=mtcar.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 234,
   "id": "7e65a665",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>mpg</th>\n",
       "      <th>cyl</th>\n",
       "      <th>disp</th>\n",
       "      <th>hp</th>\n",
       "      <th>drat</th>\n",
       "      <th>wt</th>\n",
       "      <th>qsec</th>\n",
       "      <th>vs</th>\n",
       "      <th>am</th>\n",
       "      <th>gear</th>\n",
       "      <th>carb</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.165957</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.720629</td>\n",
       "      <td>0.681979</td>\n",
       "      <td>0.207373</td>\n",
       "      <td>0.525952</td>\n",
       "      <td>0.159524</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.428571</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>0.255319</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.510601</td>\n",
       "      <td>0.452297</td>\n",
       "      <td>0.142857</td>\n",
       "      <td>0.653797</td>\n",
       "      <td>0.345238</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.285714</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>0.293617</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.510601</td>\n",
       "      <td>0.452297</td>\n",
       "      <td>0.142857</td>\n",
       "      <td>0.566863</td>\n",
       "      <td>0.369048</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.285714</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>0.204255</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.510601</td>\n",
       "      <td>0.452297</td>\n",
       "      <td>0.142857</td>\n",
       "      <td>0.579647</td>\n",
       "      <td>0.416667</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.285714</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>0.000000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.540636</td>\n",
       "      <td>0.078341</td>\n",
       "      <td>0.955510</td>\n",
       "      <td>0.414286</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.428571</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>0.000000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.970067</td>\n",
       "      <td>0.575972</td>\n",
       "      <td>0.110599</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.395238</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.428571</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>0.182979</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.920180</td>\n",
       "      <td>0.628975</td>\n",
       "      <td>0.216590</td>\n",
       "      <td>0.979801</td>\n",
       "      <td>0.347619</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.428571</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>0.217021</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.615864</td>\n",
       "      <td>0.346290</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.513168</td>\n",
       "      <td>0.282143</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.142857</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>23</th>\n",
       "      <td>0.123404</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.695685</td>\n",
       "      <td>0.681979</td>\n",
       "      <td>0.447005</td>\n",
       "      <td>0.594988</td>\n",
       "      <td>0.108333</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.428571</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>24</th>\n",
       "      <td>0.374468</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.820404</td>\n",
       "      <td>0.434629</td>\n",
       "      <td>0.147465</td>\n",
       "      <td>0.596267</td>\n",
       "      <td>0.303571</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.142857</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>30</th>\n",
       "      <td>0.195745</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.573460</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.359447</td>\n",
       "      <td>0.525952</td>\n",
       "      <td>0.011905</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         mpg  cyl      disp        hp      drat        wt      qsec   vs   am  \\\n",
       "6   0.165957  1.0  0.720629  0.681979  0.207373  0.525952  0.159524  0.0  0.0   \n",
       "11  0.255319  1.0  0.510601  0.452297  0.142857  0.653797  0.345238  0.0  0.0   \n",
       "12  0.293617  1.0  0.510601  0.452297  0.142857  0.566863  0.369048  0.0  0.0   \n",
       "13  0.204255  1.0  0.510601  0.452297  0.142857  0.579647  0.416667  0.0  0.0   \n",
       "14  0.000000  1.0  1.000000  0.540636  0.078341  0.955510  0.414286  0.0  0.0   \n",
       "15  0.000000  1.0  0.970067  0.575972  0.110599  1.000000  0.395238  0.0  0.0   \n",
       "16  0.182979  1.0  0.920180  0.628975  0.216590  0.979801  0.347619  0.0  0.0   \n",
       "21  0.217021  1.0  0.615864  0.346290  0.000000  0.513168  0.282143  0.0  0.0   \n",
       "23  0.123404  1.0  0.695685  0.681979  0.447005  0.594988  0.108333  0.0  0.0   \n",
       "24  0.374468  1.0  0.820404  0.434629  0.147465  0.596267  0.303571  0.0  0.0   \n",
       "30  0.195745  1.0  0.573460  1.000000  0.359447  0.525952  0.011905  0.0  1.0   \n",
       "\n",
       "    gear      carb  \n",
       "6    0.0  0.428571  \n",
       "11   0.0  0.285714  \n",
       "12   0.0  0.285714  \n",
       "13   0.0  0.285714  \n",
       "14   0.0  0.428571  \n",
       "15   0.0  0.428571  \n",
       "16   0.0  0.428571  \n",
       "21   0.0  0.142857  \n",
       "23   0.0  0.428571  \n",
       "24   0.0  0.142857  \n",
       "30   1.0  1.000000  "
      ]
     },
     "execution_count": 234,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mtcar_df[(mtcar_df['wt']>0.5)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 235,
   "id": "35322f4c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 235,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(mtcar_df[(mtcar_df['wt']>0.5)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 236,
   "id": "11793b63",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 표준화 척도 \n",
    "import pandas as pd\n",
    "mtcar=pd.read_csv(\"c:/data/mtcar.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 237,
   "id": "254e1743",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 238,
   "id": "dd2a9b85",
   "metadata": {},
   "outputs": [],
   "source": [
    "# StandardScaler() 함수를 수행할 빈 박스 생성\n",
    "scaler=StandardScaler()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 239,
   "id": "09c5976c",
   "metadata": {},
   "outputs": [],
   "source": [
    "mtcar_stand=scaler.fit_transform(mtcar)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 240,
   "id": "90be78d2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.ndarray"
      ]
     },
     "execution_count": 240,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(mtcar_stand)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 241,
   "id": "2616a3ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "mtcar_stand=pd.DataFrame(mtcar_stand,columns=mtcar.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 242,
   "id": "c280ae1b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>mpg</th>\n",
       "      <th>cyl</th>\n",
       "      <th>disp</th>\n",
       "      <th>hp</th>\n",
       "      <th>drat</th>\n",
       "      <th>wt</th>\n",
       "      <th>qsec</th>\n",
       "      <th>vs</th>\n",
       "      <th>am</th>\n",
       "      <th>gear</th>\n",
       "      <th>carb</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.153299</td>\n",
       "      <td>-0.106668</td>\n",
       "      <td>-0.579750</td>\n",
       "      <td>-0.543655</td>\n",
       "      <td>0.576594</td>\n",
       "      <td>-0.620167</td>\n",
       "      <td>-0.789601</td>\n",
       "      <td>-0.881917</td>\n",
       "      <td>1.208941</td>\n",
       "      <td>0.430331</td>\n",
       "      <td>0.746967</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.153299</td>\n",
       "      <td>-0.106668</td>\n",
       "      <td>-0.579750</td>\n",
       "      <td>-0.543655</td>\n",
       "      <td>0.576594</td>\n",
       "      <td>-0.355382</td>\n",
       "      <td>-0.471202</td>\n",
       "      <td>-0.881917</td>\n",
       "      <td>1.208941</td>\n",
       "      <td>0.430331</td>\n",
       "      <td>0.746967</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.456737</td>\n",
       "      <td>-1.244457</td>\n",
       "      <td>-1.006026</td>\n",
       "      <td>-0.795570</td>\n",
       "      <td>0.481584</td>\n",
       "      <td>-0.931678</td>\n",
       "      <td>0.432823</td>\n",
       "      <td>1.133893</td>\n",
       "      <td>1.208941</td>\n",
       "      <td>0.430331</td>\n",
       "      <td>-1.140108</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        mpg       cyl      disp        hp      drat        wt      qsec  \\\n",
       "0  0.153299 -0.106668 -0.579750 -0.543655  0.576594 -0.620167 -0.789601   \n",
       "1  0.153299 -0.106668 -0.579750 -0.543655  0.576594 -0.355382 -0.471202   \n",
       "2  0.456737 -1.244457 -1.006026 -0.795570  0.481584 -0.931678  0.432823   \n",
       "\n",
       "         vs        am      gear      carb  \n",
       "0 -0.881917  1.208941  0.430331  0.746967  \n",
       "1 -0.881917  1.208941  0.430331  0.746967  \n",
       "2  1.133893  1.208941  0.430331 -1.140108  "
      ]
     },
     "execution_count": 242,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mtcar_stand.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 243,
   "id": "0282f76a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "mpg     1.016001\n",
       "cyl     1.016001\n",
       "disp    1.016001\n",
       "hp      1.016001\n",
       "drat    1.016001\n",
       "wt      1.016001\n",
       "qsec    1.016001\n",
       "vs      1.016001\n",
       "am      1.016001\n",
       "gear    1.016001\n",
       "carb    1.016001\n",
       "dtype: float64"
      ]
     },
     "execution_count": 243,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mtcar_stand.std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 244,
   "id": "cdbbbbff",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "mpg     1.0\n",
       "cyl     1.0\n",
       "disp    1.0\n",
       "hp      1.0\n",
       "drat    1.0\n",
       "wt      1.0\n",
       "qsec    1.0\n",
       "vs      1.0\n",
       "am      1.0\n",
       "gear    1.0\n",
       "carb    1.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 244,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "round(mtcar_stand.std(),1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 245,
   "id": "5d81c17b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "mpg    -0.0\n",
       "cyl     0.0\n",
       "disp    0.0\n",
       "hp      0.0\n",
       "drat   -0.0\n",
       "wt     -0.0\n",
       "qsec   -0.0\n",
       "vs      0.0\n",
       "am      0.0\n",
       "gear   -0.0\n",
       "carb   -0.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 245,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "round(mtcar_stand.mean(),1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "id": "e8096d20",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 07.\n",
    "# import pandas as pd\n",
    "# df=pd.read_csv(\"c:/data/disease.csv\")\n",
    "# 다음은 국가별 연도별 인구 10만 명당 유병률 데이터이다. \n",
    "# 2000년도의 국가별 결핵 유병률 \n",
    "# 데이터에서 2000년도의 평균값보다 큰 유병률 값을 가진 국가수를 출력하시오.\n",
    "# print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 246,
   "id": "cad6f2d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 247,
   "id": "994d030e",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.read_csv(\"c:/data/disease.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 248,
   "id": "0a0ee312",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>Afghanistan</th>\n",
       "      <th>Albania</th>\n",
       "      <th>Algeria</th>\n",
       "      <th>Andorra</th>\n",
       "      <th>Angola</th>\n",
       "      <th>Antigua...Barbuda</th>\n",
       "      <th>Argentina</th>\n",
       "      <th>Armenia</th>\n",
       "      <th>Australia</th>\n",
       "      <th>...</th>\n",
       "      <th>Tanzania</th>\n",
       "      <th>USA</th>\n",
       "      <th>Uruguay</th>\n",
       "      <th>Uzbekistan</th>\n",
       "      <th>Vanuatu</th>\n",
       "      <th>Venezuela</th>\n",
       "      <th>Vietnam</th>\n",
       "      <th>Yemen</th>\n",
       "      <th>Zambia</th>\n",
       "      <th>Zimbabwe</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1999</td>\n",
       "      <td>0</td>\n",
       "      <td>89.0</td>\n",
       "      <td>25.0</td>\n",
       "      <td>245.0</td>\n",
       "      <td>217.0</td>\n",
       "      <td>102.0</td>\n",
       "      <td>193.0</td>\n",
       "      <td>21.0</td>\n",
       "      <td>261.0</td>\n",
       "      <td>...</td>\n",
       "      <td>36.0</td>\n",
       "      <td>249.0</td>\n",
       "      <td>115.0</td>\n",
       "      <td>25.0</td>\n",
       "      <td>21.0</td>\n",
       "      <td>333.0</td>\n",
       "      <td>111</td>\n",
       "      <td>6.0</td>\n",
       "      <td>32.0</td>\n",
       "      <td>64.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2000</td>\n",
       "      <td>0</td>\n",
       "      <td>132.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>138.0</td>\n",
       "      <td>57.0</td>\n",
       "      <td>128.0</td>\n",
       "      <td>25.0</td>\n",
       "      <td>179.0</td>\n",
       "      <td>72.0</td>\n",
       "      <td>...</td>\n",
       "      <td>6.0</td>\n",
       "      <td>158.0</td>\n",
       "      <td>35.0</td>\n",
       "      <td>101.0</td>\n",
       "      <td>18.0</td>\n",
       "      <td>100.0</td>\n",
       "      <td>2</td>\n",
       "      <td>0.0</td>\n",
       "      <td>19.0</td>\n",
       "      <td>18.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2001</td>\n",
       "      <td>0</td>\n",
       "      <td>54.0</td>\n",
       "      <td>14.0</td>\n",
       "      <td>312.0</td>\n",
       "      <td>45.0</td>\n",
       "      <td>45.0</td>\n",
       "      <td>221.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>212.0</td>\n",
       "      <td>...</td>\n",
       "      <td>1.0</td>\n",
       "      <td>84.0</td>\n",
       "      <td>220.0</td>\n",
       "      <td>8.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1</td>\n",
       "      <td>0.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 194 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   year  Afghanistan  Albania  Algeria  Andorra  Angola  Antigua...Barbuda  \\\n",
       "0  1999            0     89.0     25.0    245.0   217.0              102.0   \n",
       "1  2000            0    132.0      0.0    138.0    57.0              128.0   \n",
       "2  2001            0     54.0     14.0    312.0    45.0               45.0   \n",
       "\n",
       "   Argentina  Armenia  Australia  ...  Tanzania    USA  Uruguay  Uzbekistan  \\\n",
       "0      193.0     21.0      261.0  ...      36.0  249.0    115.0        25.0   \n",
       "1       25.0    179.0       72.0  ...       6.0  158.0     35.0       101.0   \n",
       "2      221.0     11.0      212.0  ...       1.0   84.0    220.0         8.0   \n",
       "\n",
       "   Vanuatu  Venezuela  Vietnam  Yemen  Zambia  Zimbabwe  \n",
       "0     21.0      333.0      111    6.0    32.0      64.0  \n",
       "1     18.0      100.0        2    0.0    19.0      18.0  \n",
       "2     11.0        3.0        1    0.0     4.0       4.0  \n",
       "\n",
       "[3 rows x 194 columns]"
      ]
     },
     "execution_count": 248,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 249,
   "id": "35c130d9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>variable</th>\n",
       "      <th>value</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1999</td>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2000</td>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2001</td>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2002</td>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1999</td>\n",
       "      <td>Albania</td>\n",
       "      <td>89.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>767</th>\n",
       "      <td>2002</td>\n",
       "      <td>Zambia</td>\n",
       "      <td>2.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>768</th>\n",
       "      <td>1999</td>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>64.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>769</th>\n",
       "      <td>2000</td>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>18.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>770</th>\n",
       "      <td>2001</td>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>771</th>\n",
       "      <td>2002</td>\n",
       "      <td>Zimbabwe</td>\n",
       "      <td>4.7</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>772 rows × 3 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     year     variable  value\n",
       "0    1999  Afghanistan    0.0\n",
       "1    2000  Afghanistan    0.0\n",
       "2    2001  Afghanistan    0.0\n",
       "3    2002  Afghanistan    0.0\n",
       "4    1999      Albania   89.0\n",
       "..    ...          ...    ...\n",
       "767  2002       Zambia    2.5\n",
       "768  1999     Zimbabwe   64.0\n",
       "769  2000     Zimbabwe   18.0\n",
       "770  2001     Zimbabwe    4.0\n",
       "771  2002     Zimbabwe    4.7\n",
       "\n",
       "[772 rows x 3 columns]"
      ]
     },
     "execution_count": 249,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.melt(df,id_vars=['year'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 250,
   "id": "0302e41e",
   "metadata": {},
   "outputs": [],
   "source": [
    "df1=pd.melt(df,id_vars=['year'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 251,
   "id": "193db9b4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.frame.DataFrame"
      ]
     },
     "execution_count": 251,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(df1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 252,
   "id": "a9e71b71",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_2000=df1[df1['year']==2000]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 253,
   "id": "a9547be9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Int64Index: 193 entries, 1 to 769\n",
      "Data columns (total 3 columns):\n",
      " #   Column    Non-Null Count  Dtype  \n",
      "---  ------    --------------  -----  \n",
      " 0   year      193 non-null    int64  \n",
      " 1   variable  193 non-null    object \n",
      " 2   value     193 non-null    float64\n",
      "dtypes: float64(1), int64(1), object(1)\n",
      "memory usage: 6.0+ KB\n"
     ]
    }
   ],
   "source": [
    "df_2000.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 254,
   "id": "aad9747b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "81.01036269430051"
      ]
     },
     "execution_count": 254,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2000년도의 평균값\n",
    "df_2000['value'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 255,
   "id": "fc1055bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "avg=df_2000['value'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 256,
   "id": "239e5a7f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1      False\n",
       "5       True\n",
       "9      False\n",
       "13      True\n",
       "17     False\n",
       "       ...  \n",
       "753     True\n",
       "757    False\n",
       "761    False\n",
       "765    False\n",
       "769    False\n",
       "Name: value, Length: 193, dtype: bool"
      ]
     },
     "execution_count": 256,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(df_2000['value']>avg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 257,
   "id": "5e4c10df",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>variable</th>\n",
       "      <th>value</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2000</td>\n",
       "      <td>Albania</td>\n",
       "      <td>132.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>2000</td>\n",
       "      <td>Andorra</td>\n",
       "      <td>138.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>2000</td>\n",
       "      <td>Antigua...Barbuda</td>\n",
       "      <td>128.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>29</th>\n",
       "      <td>2000</td>\n",
       "      <td>Armenia</td>\n",
       "      <td>179.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>45</th>\n",
       "      <td>2000</td>\n",
       "      <td>Bahamas</td>\n",
       "      <td>176.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>725</th>\n",
       "      <td>2000</td>\n",
       "      <td>United.Arab.Emirates</td>\n",
       "      <td>135.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>729</th>\n",
       "      <td>2000</td>\n",
       "      <td>United.Kingdom</td>\n",
       "      <td>126.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>737</th>\n",
       "      <td>2000</td>\n",
       "      <td>USA</td>\n",
       "      <td>158.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>745</th>\n",
       "      <td>2000</td>\n",
       "      <td>Uzbekistan</td>\n",
       "      <td>101.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>753</th>\n",
       "      <td>2000</td>\n",
       "      <td>Venezuela</td>\n",
       "      <td>100.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>76 rows × 3 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     year              variable  value\n",
       "5    2000               Albania  132.0\n",
       "13   2000               Andorra  138.0\n",
       "21   2000     Antigua...Barbuda  128.0\n",
       "29   2000               Armenia  179.0\n",
       "45   2000               Bahamas  176.0\n",
       "..    ...                   ...    ...\n",
       "725  2000  United.Arab.Emirates  135.0\n",
       "729  2000        United.Kingdom  126.0\n",
       "737  2000                   USA  158.0\n",
       "745  2000            Uzbekistan  101.0\n",
       "753  2000             Venezuela  100.0\n",
       "\n",
       "[76 rows x 3 columns]"
      ]
     },
     "execution_count": 257,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_2000[(df_2000['value']>avg)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 258,
   "id": "ae1d7f76",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "76"
      ]
     },
     "execution_count": 258,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(df_2000[(df_2000['value']>avg)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 259,
   "id": "3137c228",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "76\n"
     ]
    }
   ],
   "source": [
    "ans=len(df_2000[(df_2000['value']>avg)])\n",
    "print(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "id": "17151cc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 08.\n",
    "# import pandas as pd\n",
    "# df=pd.read_csv(\"c:/data/facebook.csv\")\n",
    "# 주어진 데이터는 페이스북의 라이브에 대한 사용자 반응을 집계한 것이다. 여러 반응 중 \n",
    "# love 반응(num_loves)과 wow반응(num_wows)을 매우 긍정적인 반응이라고 정의할 때 \n",
    "# 전체 반응의수(num_reaction)에서 매우 긍정적인 반응의 수가 차지하는 비율을 계산한 후\n",
    "# 그 비율이 0.5보다 작고, 0.4보다 크며 유형이 비디오(video)인 건수를 정수로 출력하시오.\n",
    "# print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 260,
   "id": "aec0db35",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 261,
   "id": "ca26ba99",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.read_csv(\"c:/data/facebook.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 262,
   "id": "a7106f2f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>status_id</th>\n",
       "      <th>status_type</th>\n",
       "      <th>status_published</th>\n",
       "      <th>num_reactions</th>\n",
       "      <th>num_comments</th>\n",
       "      <th>num_shares</th>\n",
       "      <th>num_likes</th>\n",
       "      <th>num_loves</th>\n",
       "      <th>num_wows</th>\n",
       "      <th>num_hahas</th>\n",
       "      <th>num_sads</th>\n",
       "      <th>num_angrys</th>\n",
       "      <th>react_comment_r</th>\n",
       "      <th>react_share_r</th>\n",
       "      <th>postive_reactions</th>\n",
       "      <th>negative_reactions</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>246675545449582_1649696485147474</td>\n",
       "      <td>video</td>\n",
       "      <td>4/22/2018 6:00</td>\n",
       "      <td>529</td>\n",
       "      <td>512</td>\n",
       "      <td>262</td>\n",
       "      <td>432</td>\n",
       "      <td>92</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1.033203</td>\n",
       "      <td>2.019084</td>\n",
       "      <td>527</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>246675545449582_1649426988507757</td>\n",
       "      <td>photo</td>\n",
       "      <td>4/21/2018 22:45</td>\n",
       "      <td>150</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>150</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>150</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>246675545449582_1648730588577397</td>\n",
       "      <td>video</td>\n",
       "      <td>4/21/2018 6:17</td>\n",
       "      <td>227</td>\n",
       "      <td>236</td>\n",
       "      <td>57</td>\n",
       "      <td>204</td>\n",
       "      <td>21</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.961864</td>\n",
       "      <td>3.982456</td>\n",
       "      <td>226</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                          status_id status_type status_published  \\\n",
       "0  246675545449582_1649696485147474       video   4/22/2018 6:00   \n",
       "1  246675545449582_1649426988507757       photo  4/21/2018 22:45   \n",
       "2  246675545449582_1648730588577397       video   4/21/2018 6:17   \n",
       "\n",
       "   num_reactions  num_comments  num_shares  num_likes  num_loves  num_wows  \\\n",
       "0            529           512         262        432         92         3   \n",
       "1            150             0           0        150          0         0   \n",
       "2            227           236          57        204         21         1   \n",
       "\n",
       "   num_hahas  num_sads  num_angrys  react_comment_r  react_share_r  \\\n",
       "0          1         1           0         1.033203       2.019084   \n",
       "1          0         0           0         0.000000       0.000000   \n",
       "2          1         0           0         0.961864       3.982456   \n",
       "\n",
       "   postive_reactions  negative_reactions  \n",
       "0                527                   2  \n",
       "1                150                   0  \n",
       "2                226                   1  "
      ]
     },
     "execution_count": 262,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 263,
   "id": "fe646cb0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 6997 entries, 0 to 6996\n",
      "Data columns (total 16 columns):\n",
      " #   Column              Non-Null Count  Dtype  \n",
      "---  ------              --------------  -----  \n",
      " 0   status_id           6997 non-null   object \n",
      " 1   status_type         6997 non-null   object \n",
      " 2   status_published    6997 non-null   object \n",
      " 3   num_reactions       6997 non-null   int64  \n",
      " 4   num_comments        6997 non-null   int64  \n",
      " 5   num_shares          6997 non-null   int64  \n",
      " 6   num_likes           6997 non-null   int64  \n",
      " 7   num_loves           6997 non-null   int64  \n",
      " 8   num_wows            6997 non-null   int64  \n",
      " 9   num_hahas           6997 non-null   int64  \n",
      " 10  num_sads            6997 non-null   int64  \n",
      " 11  num_angrys          6997 non-null   int64  \n",
      " 12  react_comment_r     6877 non-null   float64\n",
      " 13  react_share_r       6880 non-null   float64\n",
      " 14  postive_reactions   6997 non-null   int64  \n",
      " 15  negative_reactions  6997 non-null   int64  \n",
      "dtypes: float64(2), int64(11), object(3)\n",
      "memory usage: 874.8+ KB\n"
     ]
    }
   ],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 264,
   "id": "38fe9159",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "status_id               0\n",
       "status_type             0\n",
       "status_published        0\n",
       "num_reactions           0\n",
       "num_comments            0\n",
       "num_shares              0\n",
       "num_likes               0\n",
       "num_loves               0\n",
       "num_wows                0\n",
       "num_hahas               0\n",
       "num_sads                0\n",
       "num_angrys              0\n",
       "react_comment_r       120\n",
       "react_share_r         117\n",
       "postive_reactions       0\n",
       "negative_reactions      0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 264,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 265,
   "id": "d73db476",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['ratio']=((df['num_loves']+df['num_wows'])/(df['num_reactions']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 266,
   "id": "a9a6dae2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>status_id</th>\n",
       "      <th>status_type</th>\n",
       "      <th>status_published</th>\n",
       "      <th>num_reactions</th>\n",
       "      <th>num_comments</th>\n",
       "      <th>num_shares</th>\n",
       "      <th>num_likes</th>\n",
       "      <th>num_loves</th>\n",
       "      <th>num_wows</th>\n",
       "      <th>num_hahas</th>\n",
       "      <th>num_sads</th>\n",
       "      <th>num_angrys</th>\n",
       "      <th>react_comment_r</th>\n",
       "      <th>react_share_r</th>\n",
       "      <th>postive_reactions</th>\n",
       "      <th>negative_reactions</th>\n",
       "      <th>ratio</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3114</th>\n",
       "      <td>134115277150304_226952507866580</td>\n",
       "      <td>video</td>\n",
       "      <td>2/15/2018 22:55</td>\n",
       "      <td>255</td>\n",
       "      <td>926</td>\n",
       "      <td>181</td>\n",
       "      <td>142</td>\n",
       "      <td>108</td>\n",
       "      <td>0</td>\n",
       "      <td>5</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.275378</td>\n",
       "      <td>1.408840</td>\n",
       "      <td>250</td>\n",
       "      <td>5</td>\n",
       "      <td>0.423529</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4622</th>\n",
       "      <td>725980084255106_838993039620476</td>\n",
       "      <td>video</td>\n",
       "      <td>3/26/2018 7:17</td>\n",
       "      <td>1397</td>\n",
       "      <td>771</td>\n",
       "      <td>695</td>\n",
       "      <td>765</td>\n",
       "      <td>485</td>\n",
       "      <td>139</td>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>1.811933</td>\n",
       "      <td>2.010072</td>\n",
       "      <td>1389</td>\n",
       "      <td>8</td>\n",
       "      <td>0.446671</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4774</th>\n",
       "      <td>614855718638584_852682288189258</td>\n",
       "      <td>video</td>\n",
       "      <td>6/11/2018 1:18</td>\n",
       "      <td>259</td>\n",
       "      <td>695</td>\n",
       "      <td>263</td>\n",
       "      <td>151</td>\n",
       "      <td>106</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.372662</td>\n",
       "      <td>0.984791</td>\n",
       "      <td>257</td>\n",
       "      <td>2</td>\n",
       "      <td>0.409266</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4791</th>\n",
       "      <td>614855718638584_851581351632685</td>\n",
       "      <td>video</td>\n",
       "      <td>6/10/2018 1:02</td>\n",
       "      <td>146</td>\n",
       "      <td>303</td>\n",
       "      <td>221</td>\n",
       "      <td>73</td>\n",
       "      <td>69</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0.481848</td>\n",
       "      <td>0.660633</td>\n",
       "      <td>144</td>\n",
       "      <td>2</td>\n",
       "      <td>0.486301</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4810</th>\n",
       "      <td>614855718638584_850456998411787</td>\n",
       "      <td>video</td>\n",
       "      <td>6/9/2018 1:11</td>\n",
       "      <td>184</td>\n",
       "      <td>530</td>\n",
       "      <td>224</td>\n",
       "      <td>101</td>\n",
       "      <td>80</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0.347170</td>\n",
       "      <td>0.821429</td>\n",
       "      <td>181</td>\n",
       "      <td>3</td>\n",
       "      <td>0.434783</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6255</th>\n",
       "      <td>1050855161656896_1633473383395068</td>\n",
       "      <td>video</td>\n",
       "      <td>5/22/2018 8:41</td>\n",
       "      <td>416</td>\n",
       "      <td>5352</td>\n",
       "      <td>580</td>\n",
       "      <td>204</td>\n",
       "      <td>194</td>\n",
       "      <td>3</td>\n",
       "      <td>13</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0.077728</td>\n",
       "      <td>0.717241</td>\n",
       "      <td>401</td>\n",
       "      <td>15</td>\n",
       "      <td>0.473558</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6258</th>\n",
       "      <td>1050855161656896_1630620870346986</td>\n",
       "      <td>video</td>\n",
       "      <td>5/19/2018 9:14</td>\n",
       "      <td>370</td>\n",
       "      <td>6316</td>\n",
       "      <td>633</td>\n",
       "      <td>182</td>\n",
       "      <td>166</td>\n",
       "      <td>2</td>\n",
       "      <td>17</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>0.058581</td>\n",
       "      <td>0.584518</td>\n",
       "      <td>350</td>\n",
       "      <td>20</td>\n",
       "      <td>0.454054</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6282</th>\n",
       "      <td>1050855161656896_1616943501714723</td>\n",
       "      <td>video</td>\n",
       "      <td>5/5/2018 8:45</td>\n",
       "      <td>236</td>\n",
       "      <td>5237</td>\n",
       "      <td>526</td>\n",
       "      <td>138</td>\n",
       "      <td>97</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.045064</td>\n",
       "      <td>0.448669</td>\n",
       "      <td>236</td>\n",
       "      <td>0</td>\n",
       "      <td>0.415254</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6318</th>\n",
       "      <td>1050855161656896_1598796110196129</td>\n",
       "      <td>video</td>\n",
       "      <td>4/16/2018 2:07</td>\n",
       "      <td>239</td>\n",
       "      <td>2574</td>\n",
       "      <td>419</td>\n",
       "      <td>140</td>\n",
       "      <td>95</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.092852</td>\n",
       "      <td>0.570406</td>\n",
       "      <td>236</td>\n",
       "      <td>3</td>\n",
       "      <td>0.401674</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6648</th>\n",
       "      <td>1050855161656896_1422444124497996</td>\n",
       "      <td>video</td>\n",
       "      <td>10/16/2017 9:17</td>\n",
       "      <td>517</td>\n",
       "      <td>5514</td>\n",
       "      <td>388</td>\n",
       "      <td>243</td>\n",
       "      <td>220</td>\n",
       "      <td>8</td>\n",
       "      <td>43</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>0.093761</td>\n",
       "      <td>1.332474</td>\n",
       "      <td>471</td>\n",
       "      <td>46</td>\n",
       "      <td>0.441006</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>90 rows × 17 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                              status_id status_type status_published  \\\n",
       "3114    134115277150304_226952507866580       video  2/15/2018 22:55   \n",
       "4622    725980084255106_838993039620476       video   3/26/2018 7:17   \n",
       "4774    614855718638584_852682288189258       video   6/11/2018 1:18   \n",
       "4791    614855718638584_851581351632685       video   6/10/2018 1:02   \n",
       "4810    614855718638584_850456998411787       video    6/9/2018 1:11   \n",
       "...                                 ...         ...              ...   \n",
       "6255  1050855161656896_1633473383395068       video   5/22/2018 8:41   \n",
       "6258  1050855161656896_1630620870346986       video   5/19/2018 9:14   \n",
       "6282  1050855161656896_1616943501714723       video    5/5/2018 8:45   \n",
       "6318  1050855161656896_1598796110196129       video   4/16/2018 2:07   \n",
       "6648  1050855161656896_1422444124497996       video  10/16/2017 9:17   \n",
       "\n",
       "      num_reactions  num_comments  num_shares  num_likes  num_loves  num_wows  \\\n",
       "3114            255           926         181        142        108         0   \n",
       "4622           1397           771         695        765        485       139   \n",
       "4774            259           695         263        151        106         0   \n",
       "4791            146           303         221         73         69         2   \n",
       "4810            184           530         224        101         80         0   \n",
       "...             ...           ...         ...        ...        ...       ...   \n",
       "6255            416          5352         580        204        194         3   \n",
       "6258            370          6316         633        182        166         2   \n",
       "6282            236          5237         526        138         97         1   \n",
       "6318            239          2574         419        140         95         1   \n",
       "6648            517          5514         388        243        220         8   \n",
       "\n",
       "      num_hahas  num_sads  num_angrys  react_comment_r  react_share_r  \\\n",
       "3114          5         0           0         0.275378       1.408840   \n",
       "4622          4         1           3         1.811933       2.010072   \n",
       "4774          2         0           0         0.372662       0.984791   \n",
       "4791          1         0           1         0.481848       0.660633   \n",
       "4810          1         1           1         0.347170       0.821429   \n",
       "...         ...       ...         ...              ...            ...   \n",
       "6255         13         1           1         0.077728       0.717241   \n",
       "6258         17         3           0         0.058581       0.584518   \n",
       "6282          0         0           0         0.045064       0.448669   \n",
       "6318          2         1           0         0.092852       0.570406   \n",
       "6648         43         3           0         0.093761       1.332474   \n",
       "\n",
       "      postive_reactions  negative_reactions     ratio  \n",
       "3114                250                   5  0.423529  \n",
       "4622               1389                   8  0.446671  \n",
       "4774                257                   2  0.409266  \n",
       "4791                144                   2  0.486301  \n",
       "4810                181                   3  0.434783  \n",
       "...                 ...                 ...       ...  \n",
       "6255                401                  15  0.473558  \n",
       "6258                350                  20  0.454054  \n",
       "6282                236                   0  0.415254  \n",
       "6318                236                   3  0.401674  \n",
       "6648                471                  46  0.441006  \n",
       "\n",
       "[90 rows x 17 columns]"
      ]
     },
     "execution_count": 266,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[(df['ratio']>0.4)&\n",
    "   (df['ratio']<0.5)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 267,
   "id": "bbcfb48d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "90"
      ]
     },
     "execution_count": 267,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(df[(df['ratio']>0.4)&\n",
    "   (df['ratio']<0.5)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 268,
   "id": "037ab051",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "photo     4242\n",
       "video     2333\n",
       "status     359\n",
       "link        63\n",
       "Name: status_type, dtype: int64"
      ]
     },
     "execution_count": 268,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['status_type'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 269,
   "id": "83a2b003",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "90\n"
     ]
    }
   ],
   "source": [
    "ans=len(df[(df['ratio']>0.4)&\n",
    "       (df['ratio']<0.5)&\n",
    "       (df['status_type']=='video')])\n",
    "print(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "id": "bf21d476",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 09.\n",
    "# import pandas as pd\n",
    "# df=pd.read_csv(\"c:/data/netflix.csv\",encoding_errors='ignore')\n",
    "# 주어진 데이터는 넷플릭스 등록 콘텐츠의 메타데이터이다.\n",
    "# 2018년 1월중 넷플리스에 등록된 \n",
    "# 콘텐츠 중에서 “United Kingdom”이 단독 제작한 콘텐츠의 수를 정수로 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 427,
   "id": "13a28312",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 429,
   "id": "fdb8347c",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.read_csv(\"c:/data/netflix.csv\",encoding_errors='ignore')\n",
    "# Pandas api로 csv파일을 읽을 때, 인코딩 오류 발생"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 431,
   "id": "bfa957a3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 8807 entries, 0 to 8806\n",
      "Data columns (total 11 columns):\n",
      " #   Column        Non-Null Count  Dtype \n",
      "---  ------        --------------  ----- \n",
      " 0   show_id       8807 non-null   object\n",
      " 1   type          8807 non-null   object\n",
      " 2   title         8806 non-null   object\n",
      " 3   director      6173 non-null   object\n",
      " 4   cast          7982 non-null   object\n",
      " 5   country       7976 non-null   object\n",
      " 6   date_added    8797 non-null   object\n",
      " 7   release_year  8807 non-null   int64 \n",
      " 8   rating        8803 non-null   object\n",
      " 9   duration      8804 non-null   object\n",
      " 10  listed_in     8807 non-null   object\n",
      "dtypes: int64(1), object(10)\n",
      "memory usage: 757.0+ KB\n"
     ]
    }
   ],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 273,
   "id": "08659589",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>show_id</th>\n",
       "      <th>type</th>\n",
       "      <th>title</th>\n",
       "      <th>director</th>\n",
       "      <th>cast</th>\n",
       "      <th>country</th>\n",
       "      <th>date_added</th>\n",
       "      <th>release_year</th>\n",
       "      <th>rating</th>\n",
       "      <th>duration</th>\n",
       "      <th>listed_in</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>s1</td>\n",
       "      <td>Movie</td>\n",
       "      <td>Dick Johnson Is Dead</td>\n",
       "      <td>Kirsten Johnson</td>\n",
       "      <td>NaN</td>\n",
       "      <td>United States</td>\n",
       "      <td>25-Sep-21</td>\n",
       "      <td>2020</td>\n",
       "      <td>PG-13</td>\n",
       "      <td>90 min</td>\n",
       "      <td>Documentaries</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>s2</td>\n",
       "      <td>TV Show</td>\n",
       "      <td>Blood &amp; Water</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Ama Qamata, Khosi Ngema, Gail Mabalane, Thaban...</td>\n",
       "      <td>South Africa</td>\n",
       "      <td>24-Sep-21</td>\n",
       "      <td>2021</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>2 Seasons</td>\n",
       "      <td>International TV Shows, TV Dramas, TV Mysteries</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>s3</td>\n",
       "      <td>TV Show</td>\n",
       "      <td>Ganglands</td>\n",
       "      <td>Julien Leclercq</td>\n",
       "      <td>Sami Bouajila, Tracy Gotoas, Samuel Jouy, Nabi...</td>\n",
       "      <td>NaN</td>\n",
       "      <td>24-Sep-21</td>\n",
       "      <td>2021</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>1 Season</td>\n",
       "      <td>Crime TV Shows, International TV Shows, TV Act...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  show_id     type                 title         director  \\\n",
       "0      s1    Movie  Dick Johnson Is Dead  Kirsten Johnson   \n",
       "1      s2  TV Show         Blood & Water              NaN   \n",
       "2      s3  TV Show             Ganglands  Julien Leclercq   \n",
       "\n",
       "                                                cast        country  \\\n",
       "0                                                NaN  United States   \n",
       "1  Ama Qamata, Khosi Ngema, Gail Mabalane, Thaban...   South Africa   \n",
       "2  Sami Bouajila, Tracy Gotoas, Samuel Jouy, Nabi...            NaN   \n",
       "\n",
       "  date_added  release_year rating   duration  \\\n",
       "0  25-Sep-21          2020  PG-13     90 min   \n",
       "1  24-Sep-21          2021  TV-MA  2 Seasons   \n",
       "2  24-Sep-21          2021  TV-MA   1 Season   \n",
       "\n",
       "                                           listed_in  \n",
       "0                                      Documentaries  \n",
       "1    International TV Shows, TV Dramas, TV Mysteries  \n",
       "2  Crime TV Shows, International TV Shows, TV Act...  "
      ]
     },
     "execution_count": 273,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 433,
   "id": "124228e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime as dt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 435,
   "id": "c0fe3af2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.datetime(2026, 5, 21, 10, 18, 38, 447726)"
      ]
     },
     "execution_count": 435,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = dt.datetime.now()\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "cc5bc449",
   "metadata": {},
   "outputs": [],
   "source": [
    "# x.year, x.month, x.day, x.hour, x.minute, x.second, x.microsecond"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 443,
   "id": "49eb31b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['date_added'] = pd.to_datetime(df['date_added'], errors='coerce')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 453,
   "id": "a66ba74f-0586-4612-8bd9-1ebd201e2d98",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 8807 entries, 0 to 8806\n",
      "Data columns (total 11 columns):\n",
      " #   Column        Non-Null Count  Dtype         \n",
      "---  ------        --------------  -----         \n",
      " 0   show_id       8807 non-null   object        \n",
      " 1   type          8807 non-null   object        \n",
      " 2   title         8806 non-null   object        \n",
      " 3   director      6173 non-null   object        \n",
      " 4   cast          7982 non-null   object        \n",
      " 5   country       7976 non-null   object        \n",
      " 6   date_added    8797 non-null   datetime64[ns]\n",
      " 7   release_year  8807 non-null   int64         \n",
      " 8   rating        8803 non-null   object        \n",
      " 9   duration      8804 non-null   object        \n",
      " 10  listed_in     8807 non-null   object        \n",
      "dtypes: datetime64[ns](1), int64(1), object(9)\n",
      "memory usage: 757.0+ KB\n"
     ]
    }
   ],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 445,
   "id": "bbc65480",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>show_id</th>\n",
       "      <th>type</th>\n",
       "      <th>title</th>\n",
       "      <th>director</th>\n",
       "      <th>cast</th>\n",
       "      <th>country</th>\n",
       "      <th>date_added</th>\n",
       "      <th>release_year</th>\n",
       "      <th>rating</th>\n",
       "      <th>duration</th>\n",
       "      <th>listed_in</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>s1</td>\n",
       "      <td>Movie</td>\n",
       "      <td>Dick Johnson Is Dead</td>\n",
       "      <td>Kirsten Johnson</td>\n",
       "      <td>NaN</td>\n",
       "      <td>United States</td>\n",
       "      <td>2021-09-25</td>\n",
       "      <td>2020</td>\n",
       "      <td>PG-13</td>\n",
       "      <td>90 min</td>\n",
       "      <td>Documentaries</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>s2</td>\n",
       "      <td>TV Show</td>\n",
       "      <td>Blood &amp; Water</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Ama Qamata, Khosi Ngema, Gail Mabalane, Thaban...</td>\n",
       "      <td>South Africa</td>\n",
       "      <td>2021-09-24</td>\n",
       "      <td>2021</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>2 Seasons</td>\n",
       "      <td>International TV Shows, TV Dramas, TV Mysteries</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>s3</td>\n",
       "      <td>TV Show</td>\n",
       "      <td>Ganglands</td>\n",
       "      <td>Julien Leclercq</td>\n",
       "      <td>Sami Bouajila, Tracy Gotoas, Samuel Jouy, Nabi...</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2021-09-24</td>\n",
       "      <td>2021</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>1 Season</td>\n",
       "      <td>Crime TV Shows, International TV Shows, TV Act...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  show_id     type                 title         director  \\\n",
       "0      s1    Movie  Dick Johnson Is Dead  Kirsten Johnson   \n",
       "1      s2  TV Show         Blood & Water              NaN   \n",
       "2      s3  TV Show             Ganglands  Julien Leclercq   \n",
       "\n",
       "                                                cast        country  \\\n",
       "0                                                NaN  United States   \n",
       "1  Ama Qamata, Khosi Ngema, Gail Mabalane, Thaban...   South Africa   \n",
       "2  Sami Bouajila, Tracy Gotoas, Samuel Jouy, Nabi...            NaN   \n",
       "\n",
       "  date_added  release_year rating   duration  \\\n",
       "0 2021-09-25          2020  PG-13     90 min   \n",
       "1 2021-09-24          2021  TV-MA  2 Seasons   \n",
       "2 2021-09-24          2021  TV-MA   1 Season   \n",
       "\n",
       "                                           listed_in  \n",
       "0                                      Documentaries  \n",
       "1    International TV Shows, TV Dramas, TV Mysteries  \n",
       "2  Crime TV Shows, International TV Shows, TV Act...  "
      ]
     },
     "execution_count": 445,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 455,
   "id": "d084d39b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>show_id</th>\n",
       "      <th>type</th>\n",
       "      <th>title</th>\n",
       "      <th>director</th>\n",
       "      <th>cast</th>\n",
       "      <th>country</th>\n",
       "      <th>date_added</th>\n",
       "      <th>release_year</th>\n",
       "      <th>rating</th>\n",
       "      <th>duration</th>\n",
       "      <th>listed_in</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>5057</th>\n",
       "      <td>s5058</td>\n",
       "      <td>TV Show</td>\n",
       "      <td>Retribution</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Georgina Campbell, Joe Dempsie, Adrian Edmonds...</td>\n",
       "      <td>United Kingdom</td>\n",
       "      <td>2018-01-30</td>\n",
       "      <td>2016</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>1 Season</td>\n",
       "      <td>British TV Shows, Crime TV Shows, Internationa...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5074</th>\n",
       "      <td>s5075</td>\n",
       "      <td>Movie</td>\n",
       "      <td>Bad Day for the Cut</td>\n",
       "      <td>Chris Baugh</td>\n",
       "      <td>Nigel O'Neill, Susan Lynch, J?zef Pawlowski, S...</td>\n",
       "      <td>United Kingdom</td>\n",
       "      <td>2018-01-18</td>\n",
       "      <td>2017</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>99 min</td>\n",
       "      <td>Independent Movies, International Movies, Thri...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5097</th>\n",
       "      <td>s5098</td>\n",
       "      <td>TV Show</td>\n",
       "      <td>Lovesick</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Johnny Flynn, Antonia Thomas, Daniel Ings, Han...</td>\n",
       "      <td>United Kingdom</td>\n",
       "      <td>2018-01-01</td>\n",
       "      <td>2018</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>3 Seasons</td>\n",
       "      <td>British TV Shows, International TV Shows, Roma...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7398</th>\n",
       "      <td>s7399</td>\n",
       "      <td>Movie</td>\n",
       "      <td>Manolo: The Boy Who Made Shoes for Lizards</td>\n",
       "      <td>Michael Roberts</td>\n",
       "      <td>Manolo Blahnik, Anna Wintour, Andr? Leon Talle...</td>\n",
       "      <td>United Kingdom</td>\n",
       "      <td>2018-01-15</td>\n",
       "      <td>2017</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>89 min</td>\n",
       "      <td>Documentaries, International Movies</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8357</th>\n",
       "      <td>s8358</td>\n",
       "      <td>TV Show</td>\n",
       "      <td>The Inbetweeners</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Simon Bird, James Buckley, Blake Harrison, Joe...</td>\n",
       "      <td>United Kingdom</td>\n",
       "      <td>2018-01-01</td>\n",
       "      <td>2010</td>\n",
       "      <td>TV-MA</td>\n",
       "      <td>3 Seasons</td>\n",
       "      <td>British TV Shows, TV Comedies</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8619</th>\n",
       "      <td>s8620</td>\n",
       "      <td>Movie</td>\n",
       "      <td>Treasures from the Wreck of the Unbelievable</td>\n",
       "      <td>Sam Hobkinson</td>\n",
       "      <td>NaN</td>\n",
       "      <td>United Kingdom</td>\n",
       "      <td>2018-01-01</td>\n",
       "      <td>2017</td>\n",
       "      <td>TV-G</td>\n",
       "      <td>82 min</td>\n",
       "      <td>Documentaries, Dramas, International Movies</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     show_id     type                                         title  \\\n",
       "5057   s5058  TV Show                                   Retribution   \n",
       "5074   s5075    Movie                           Bad Day for the Cut   \n",
       "5097   s5098  TV Show                                      Lovesick   \n",
       "7398   s7399    Movie    Manolo: The Boy Who Made Shoes for Lizards   \n",
       "8357   s8358  TV Show                              The Inbetweeners   \n",
       "8619   s8620    Movie  Treasures from the Wreck of the Unbelievable   \n",
       "\n",
       "             director                                               cast  \\\n",
       "5057              NaN  Georgina Campbell, Joe Dempsie, Adrian Edmonds...   \n",
       "5074      Chris Baugh  Nigel O'Neill, Susan Lynch, J?zef Pawlowski, S...   \n",
       "5097              NaN  Johnny Flynn, Antonia Thomas, Daniel Ings, Han...   \n",
       "7398  Michael Roberts  Manolo Blahnik, Anna Wintour, Andr? Leon Talle...   \n",
       "8357              NaN  Simon Bird, James Buckley, Blake Harrison, Joe...   \n",
       "8619    Sam Hobkinson                                                NaN   \n",
       "\n",
       "             country date_added  release_year rating   duration  \\\n",
       "5057  United Kingdom 2018-01-30          2016  TV-MA   1 Season   \n",
       "5074  United Kingdom 2018-01-18          2017  TV-MA     99 min   \n",
       "5097  United Kingdom 2018-01-01          2018  TV-MA  3 Seasons   \n",
       "7398  United Kingdom 2018-01-15          2017  TV-MA     89 min   \n",
       "8357  United Kingdom 2018-01-01          2010  TV-MA  3 Seasons   \n",
       "8619  United Kingdom 2018-01-01          2017   TV-G     82 min   \n",
       "\n",
       "                                              listed_in  \n",
       "5057  British TV Shows, Crime TV Shows, Internationa...  \n",
       "5074  Independent Movies, International Movies, Thri...  \n",
       "5097  British TV Shows, International TV Shows, Roma...  \n",
       "7398                Documentaries, International Movies  \n",
       "8357                      British TV Shows, TV Comedies  \n",
       "8619        Documentaries, Dramas, International Movies  "
      ]
     },
     "execution_count": 455,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[(df['date_added']>='2018-01-01')&\n",
    "(df['date_added']<='2018-01-31')&\n",
    "(df['country']=='United Kingdom')]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 449,
   "id": "66f1ba68",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 449,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(df[(df['date_added']>='2018-01-01')&\n",
    "(df['date_added']<='2018-01-31')&\n",
    "(df['country']=='United Kingdom')])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 451,
   "id": "b50aa7cb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n"
     ]
    }
   ],
   "source": [
    "ans=len(df[(df['date_added']>='2018-01-01')&\n",
    "(df['date_added']<='2018-01-31')&\n",
    "(df['country']=='United Kingdom')])\n",
    "print(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98e8a285-b2a4-46cd-871f-e27fe9e9007c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 10 주어진 데이터프레임 a의 'y' 컬럼에서 1사분위수(Q1)와 3사분위수(Q3)의 차이를 절댓값으로 계산하시오. 이후, 소수점 이하는 버리고 정수로 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 247,
   "id": "742dd5cb-5697-4775-ac49-762421024bc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "x=np.random.choice(range(1, 21), size=10, replace=False)\n",
    "y=[1, 2, 3, 4, 5, 37, 41, 42, 44, 10]\n",
    "a = pd.DataFrame({'x': x, 'y': y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 249,
   "id": "7a547278-255f-4417-bf44-98670b68b721",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.25     3.25\n",
       "0.50     7.50\n",
       "0.75    40.00\n",
       "Name: y, dtype: float64"
      ]
     },
     "execution_count": 249,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "quantiles=a['y'].quantile([0.25, 0.5, 0.75])\n",
    "quantiles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 257,
   "id": "2caa4400-608b-4021-9473-52c55fe90b8d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.25"
      ]
     },
     "execution_count": 257,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.iloc[0, 0] "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 259,
   "id": "ac227b27-9eab-490e-9102-534853e7bb62",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "40.0"
      ]
     },
     "execution_count": 259,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.iloc[2, 0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 251,
   "id": "e623690c-ec7a-41e9-81c4-da8bd6dbe6f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "36\n"
     ]
    }
   ],
   "source": [
    "df=pd.DataFrame({'quantiles': quantiles})\n",
    "diff=abs(df.iloc[0, 0] - df.iloc[2, 0])\n",
    "print(int(np.floor(diff)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a15c6ad5-a5ac-47c8-b60c-251c1daa3db5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 11. 종량제 봉투 데이터에서 용도가 '음식물쓰레기'이고 사용대상이 '가정용'인 봉투 중 '2L 가격'의 평균을 계산한 후, \n",
    "# 소수점을 버린 정수로 출력하시오.\n",
    "# (단, \"2L가격\" 컬럼은 종량제 봉투가 존재하면 가격을 값으로, 존재하지 않으면 0으로 기록됨)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 261,
   "id": "0335b5cb-225f-411d-ad37-586b40335236",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 749 entries, 0 to 748\n",
      "Data columns (total 21 columns):\n",
      " #   Column  Non-Null Count  Dtype \n",
      "---  ------  --------------  ----- \n",
      " 0   시도명     749 non-null    object\n",
      " 1   시군구명    749 non-null    object\n",
      " 2   종류      749 non-null    object\n",
      " 3   처리방식    749 non-null    object\n",
      " 4   용도      749 non-null    object\n",
      " 5   사용대상    749 non-null    object\n",
      " 6   1L가격    749 non-null    int64 \n",
      " 7   1.5L가격  749 non-null    int64 \n",
      " 8   2L가격    749 non-null    int64 \n",
      " 9   2.5L가격  749 non-null    int64 \n",
      " 10  3L가격    749 non-null    int64 \n",
      " 11  5L가격    749 non-null    int64 \n",
      " 12  10L가격   749 non-null    int64 \n",
      " 13  20L가격   749 non-null    int64 \n",
      " 14  30L가격   749 non-null    int64 \n",
      " 15  50L가격   749 non-null    int64 \n",
      " 16  60L가격   749 non-null    int64 \n",
      " 17  75L가격   749 non-null    int64 \n",
      " 18  100L가격  749 non-null    int64 \n",
      " 19  120L가격  749 non-null    int64 \n",
      " 20  125L가격  749 non-null    int64 \n",
      "dtypes: int64(15), object(6)\n",
      "memory usage: 123.0+ KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.read_csv(\"c:/data/trash.csv\", encoding=\"euc-kr\")\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 263,
   "id": "c308864e-d5a1-4f6f-a29a-f56512576d77",
   "metadata": {},
   "outputs": [],
   "source": [
    "filtered_df=df[(df['용도']=='음식물쓰레기') &\n",
    "(df['사용대상']=='가정용') &\n",
    "(df['2L가격'] != 0)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 265,
   "id": "c3f63612-1fe8-4163-821d-84a87e547d3d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "119.32692307692308"
      ]
     },
     "execution_count": 265,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " filtered_df['2L가격'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 267,
   "id": "a07c06b9-65ed-4d16-acbc-2cab0eae2bca",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "119\n"
     ]
    }
   ],
   "source": [
    "ans=filtered_df['2L가격'].mean()\n",
    "print(int(ans))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df5d9dea-6d43-4db5-9f11-59eec532410f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 10. 주어진 데이터프레임 a의 'y' 컬럼에서 1사분위수(Q1)와 3사분위수(Q3)의 차이를 절댓값으로 계산하시오. \n",
    "# 이후, 소수점 이하는 버리고 정수로 출력하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "61465205-a566-42b7-9d03-ae2120645451",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "x=np.random.choice(range(1, 21), size=10, replace=False)\n",
    "y=[1, 2, 3, 4, 5, 37, 41, 42, 44, 10]\n",
    "a = pd.DataFrame({'x': x, 'y': y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "3c1b423a-147a-4427-a7dc-97782854dc7d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.25     3.25\n",
       "0.50     7.50\n",
       "0.75    40.00\n",
       "Name: y, dtype: float64"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "quantiles=a['y'].quantile([0.25, 0.5, 0.75])\n",
    "quantiles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "e0519eeb-7238-400a-ba58-a531c3e3d8c5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "36\n"
     ]
    }
   ],
   "source": [
    "df=pd.DataFrame({'quantiles': quantiles})\n",
    "diff=abs(df.iloc[0, 0] - df.iloc[2, 0])\n",
    "print(int(np.floor(diff)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccaae612-095b-4c78-b438-2737530ef259",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 11. 종량제 봉투 데이터에서 용도가 '음식물쓰레기'이고 사용대상이 '가정용'인 봉투 중 '2L 가격'의 \n",
    "# 평균을 계산한 후, 소수점을 버린 정수로 출력하시오.\n",
    "# (단, \"2L가격\" 컬럼은 종량제 봉투가 존재하면 가격을 값으로, 존재하지 않으면 0으로 기록됨)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "89960fb3-1a03-4f0c-83bd-258078273fa7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 749 entries, 0 to 748\n",
      "Data columns (total 21 columns):\n",
      " #   Column  Non-Null Count  Dtype \n",
      "---  ------  --------------  ----- \n",
      " 0   시도명     749 non-null    object\n",
      " 1   시군구명    749 non-null    object\n",
      " 2   종류      749 non-null    object\n",
      " 3   처리방식    749 non-null    object\n",
      " 4   용도      749 non-null    object\n",
      " 5   사용대상    749 non-null    object\n",
      " 6   1L가격    749 non-null    int64 \n",
      " 7   1.5L가격  749 non-null    int64 \n",
      " 8   2L가격    749 non-null    int64 \n",
      " 9   2.5L가격  749 non-null    int64 \n",
      " 10  3L가격    749 non-null    int64 \n",
      " 11  5L가격    749 non-null    int64 \n",
      " 12  10L가격   749 non-null    int64 \n",
      " 13  20L가격   749 non-null    int64 \n",
      " 14  30L가격   749 non-null    int64 \n",
      " 15  50L가격   749 non-null    int64 \n",
      " 16  60L가격   749 non-null    int64 \n",
      " 17  75L가격   749 non-null    int64 \n",
      " 18  100L가격  749 non-null    int64 \n",
      " 19  120L가격  749 non-null    int64 \n",
      " 20  125L가격  749 non-null    int64 \n",
      "dtypes: int64(15), object(6)\n",
      "memory usage: 123.0+ KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.read_csv(\"c:/data/trash.csv\", encoding=\"euc-kr\")\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "24e3672b-60fb-4d7a-8273-9da0f5cfe502",
   "metadata": {},
   "outputs": [],
   "source": [
    "filtered_df=df[(df['용도']=='음식물쓰레기') &\n",
    "(df['사용대상']=='가정용') &\n",
    "(df['2L가격'] != 0)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "e00c2c57-e1c7-4d3e-9d36-00438c9afd10",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "119.32692307692308"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " filtered_df['2L가격'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "14bc98e1-1128-41eb-8454-69971f15c41d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "119\n"
     ]
    }
   ],
   "source": [
    "ans=filtered_df['2L가격'].mean()\n",
    "print(int(ans))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73f0051a-e3de-4b5a-82a7-961e07f85530",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 12. 비만도(BMI) 데이터에서 각 개인의 BMI 지수를 Weight(kg) / Height(m)²로 계산한 후, ‘정상\n",
    "# (18.5 이상 23 미만)’과 ‘과체중(23 이상 25 미만)’에 해당하는 인원 수를 각각 구하고\n",
    "# 두 값의  차이를 정수로 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 269,
   "id": "fcac448d-a359-42f0-bc8f-fe73a90ff9d3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 500 entries, 0 to 499\n",
      "Data columns (total 3 columns):\n",
      " #   Column  Non-Null Count  Dtype \n",
      "---  ------  --------------  ----- \n",
      " 0   Gender  500 non-null    object\n",
      " 1   Height  500 non-null    int64 \n",
      " 2   Weight  500 non-null    int64 \n",
      "dtypes: int64(2), object(1)\n",
      "memory usage: 11.8+ KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df1 = pd.read_csv(\"c:/data/bmi.csv\")\n",
    "df1.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 271,
   "id": "70b92a94-8a61-4f34-9398-19bf2968ecb8",
   "metadata": {},
   "outputs": [],
   "source": [
    " df1['Height1']=df1['Height'] / 100\n",
    "df1['bmi']=df1['Weight'] / (df1['Height1'] ** 2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 273,
   "id": "4ef1b202-cf92-471a-9309-c84b45d03112",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "47"
      ]
     },
     "execution_count": 273,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " len(df1[(df1['bmi'] >= 18.5) & (df1['bmi'] < 23)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 275,
   "id": "e6e61309-7e8a-4de2-9e1b-7e61eb870c27",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "19"
      ]
     },
     "execution_count": 275,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(df1[(df1['bmi'] >= 23) & (df1['bmi'] < 25)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 277,
   "id": "b484d49d-5202-491f-97a6-d95475672174",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "28\n"
     ]
    }
   ],
   "source": [
    "ans1=len(df1[(df1['bmi'] >= 18.5) & (df1['bmi'] < 23)])\n",
    "ans2=len(df1[(df1['bmi'] >= 23) & (df1['bmi'] < 25)])\n",
    "print(int(ans1-ans2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6bb2e718-047b-43bf-a079-8d227ed65f6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 13.  students.csv 데이터에서 순 전입학생 수(총 전입학생 수－총 전출학생 수)가 가장 많은 학교의 전체 학생수를 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 279,
   "id": "bc9fb825-c58d-47c4-bdf3-1fe10380f2cc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 24 entries, 0 to 23\n",
      "Data columns (total 5 columns):\n",
      " #   Column  Non-Null Count  Dtype \n",
      "---  ------  --------------  ----- \n",
      " 0   학교      24 non-null     object\n",
      " 1   학년      24 non-null     int64 \n",
      " 2   총전입학생   24 non-null     int64 \n",
      " 3   총전출학생   24 non-null     int64 \n",
      " 4   전체학생수   24 non-null     int64 \n",
      "dtypes: int64(4), object(1)\n",
      "memory usage: 1.1+ KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df2 = pd.read_csv(\"c:/data/students.csv\", encoding=\"euc-kr\")\n",
    "df2.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 281,
   "id": "70d8b104-8a59-4426-bb6e-b818a8bcd166",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>학교</th>\n",
       "      <th>순전입학생</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>A</td>\n",
       "      <td>18</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>-9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>D</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>E</td>\n",
       "      <td>14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>F</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>G</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>H</td>\n",
       "      <td>-1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  학교  순전입학생\n",
       "0  A     18\n",
       "1  B     13\n",
       "2  C     -9\n",
       "3  D      7\n",
       "4  E     14\n",
       "5  F      1\n",
       "6  G     10\n",
       "7  H     -1"
      ]
     },
     "execution_count": 281,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2['순전입학생']=df2['총전입학생']-df2['총전출학생']\n",
    "df2.groupby('학교')['순전입학생'].sum().reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 283,
   "id": "2d42d975-9297-435d-a7a6-2a9d91317d98",
   "metadata": {},
   "outputs": [],
   "source": [
    " filtered_df = df2[df2['학교'] == \"A\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 285,
   "id": "e2f20483-939d-4c8f-8f53-d09b7410d166",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "566\n"
     ]
    }
   ],
   "source": [
    "total_students_sum=filtered_df['전체학생수'].sum()\n",
    "print(total_students_sum)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fdd9beec-8ae9-4023-90b8-42686280e9d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 14. 주어진 데이터는 출동 소방서별 신고 접수 시각과 실제 출동 시각을 기록한 파일이다.\n",
    "# 각 출동 소방서별로 신고일시부터 출동일시까지 걸린 시간의 연도별 월평균을 계산한 후, \n",
    "# 가장 늦게 출발한 출동 소방서의 월평균 출동 시간을 분 단위로 출력하시오.\n",
    "# (단, 30초 단위로 반올림하여 제출할 것)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "3ef4b41d-07d0-4654-b5cf-6370009e2d8e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 21542 entries, 0 to 21541\n",
      "Data columns (total 3 columns):\n",
      " #   Column  Non-Null Count  Dtype \n",
      "---  ------  --------------  ----- \n",
      " 0   신고일시    21542 non-null  object\n",
      " 1   출동일시    21542 non-null  object\n",
      " 2   출동소방서   21542 non-null  object\n",
      "dtypes: object(3)\n",
      "memory usage: 505.0+ KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/firestation.csv')\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "9396b4ac-d935-4c03-ad95-58859aa5fa91",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "신고일시     0\n",
       "출동일시     0\n",
       "출동소방서    0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " df.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "be18aed7-d162-4fb2-b7f0-0a98219b0c6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['신고일시_1']=pd.to_datetime(df['신고일시'])\n",
    "df['출동일시_1']=pd.to_datetime(df['출동일시'])\n",
    "df['시간차']=(df['출동일시_1']-df['신고일시_1']).dt.total_seconds()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "20b73d5a-aae5-463a-9c23-9f846291541d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>mean_time</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>출동소방서</th>\n",
       "      <th>신고일시_1</th>\n",
       "      <th>신고일시_1</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"5\" valign=\"top\">가평119안전센터</th>\n",
       "      <th rowspan=\"5\" valign=\"top\">2018</th>\n",
       "      <th>1</th>\n",
       "      <td>90.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>180.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>60.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>120.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <th>...</th>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"5\" valign=\"top\">화성소방서</th>\n",
       "      <th rowspan=\"5\" valign=\"top\">2018</th>\n",
       "      <th>8</th>\n",
       "      <td>144.285714</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>157.777778</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>141.714286</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>169.879518</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>116.341463</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>623 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                          mean_time\n",
       "출동소방서     신고일시_1 신고일시_1            \n",
       "가평119안전센터 2018   1        90.000000\n",
       "                 2       180.000000\n",
       "                 4        60.000000\n",
       "                 5       120.000000\n",
       "                 6         0.000000\n",
       "...                             ...\n",
       "화성소방서     2018   8       144.285714\n",
       "                 9       157.777778\n",
       "                 10      141.714286\n",
       "                 11      169.879518\n",
       "                 12      116.341463\n",
       "\n",
       "[623 rows x 1 columns]"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.groupby([df['출동소방서'], df['신고일시_1'].dt.year, df['신고일시_1'].dt.month]).agg(mean_time=('시간차', 'mean'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "1cfac884-1e13-4e8b-86a0-2884de0bba13",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>mean_time</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>출동소방서</th>\n",
       "      <th>신고일시_1</th>\n",
       "      <th>신고일시_1</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>대화119안전센터</th>\n",
       "      <th>2018</th>\n",
       "      <th>9</th>\n",
       "      <td>3840.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">초월119안전센터</th>\n",
       "      <th rowspan=\"2\" valign=\"top\">2018</th>\n",
       "      <th>7</th>\n",
       "      <td>2925.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2865.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">경기도소방재난본부</th>\n",
       "      <th rowspan=\"2\" valign=\"top\">2018</th>\n",
       "      <th>8</th>\n",
       "      <td>2220.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>1620.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <th>...</th>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>용문119안전센터</th>\n",
       "      <th>2018</th>\n",
       "      <th>2</th>\n",
       "      <td>45.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>설악119안전센터</th>\n",
       "      <th>2018</th>\n",
       "      <th>6</th>\n",
       "      <td>45.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>백암119안전센터</th>\n",
       "      <th>2018</th>\n",
       "      <th>12</th>\n",
       "      <td>40.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>영북119안전센터</th>\n",
       "      <th>2018</th>\n",
       "      <th>3</th>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>가평119안전센터</th>\n",
       "      <th>2018</th>\n",
       "      <th>6</th>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>623 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                         mean_time\n",
       "출동소방서     신고일시_1 신고일시_1           \n",
       "대화119안전센터 2018   9          3840.0\n",
       "초월119안전센터 2018   7          2925.0\n",
       "                 6          2865.0\n",
       "경기도소방재난본부 2018   8          2220.0\n",
       "                 10         1620.0\n",
       "...                            ...\n",
       "용문119안전센터 2018   2            45.0\n",
       "설악119안전센터 2018   6            45.0\n",
       "백암119안전센터 2018   12           40.0\n",
       "영북119안전센터 2018   3             0.0\n",
       "가평119안전센터 2018   6             0.0\n",
       "\n",
       "[623 rows x 1 columns]"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df=df.groupby([df['출동소방서'], df['신고일시_1'].dt.year, df['신고일시_1'].dt.month]).agg(mean_time=('시간차', 'mean'))\n",
    "df.sort_values(by='mean_time', ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "9ee8fd97-d2c1-486e-9c84-941ab54ffba0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "64\n"
     ]
    }
   ],
   "source": [
    "df1=df.sort_values(by='mean_time', ascending=False)\n",
    "mean_time_in_minutes = df1.iloc[0]['mean_time'] / 60\n",
    "print(round(mean_time_in_minutes))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f06a3d06-7e4b-43a7-a2c8-ab14f3face36",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 15. 15개 초등학교의 학년별 학생 수와 교사 수 데이터에서 각 학교의 교사 1인당 학생 수를 계산한 후, \n",
    "# 가장 많은 학교를 찾아 해당 학교의 교사 수를 정수로 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "1e8deaa3-bf9b-455e-97c2-b0168c33c702",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 6309 entries, 0 to 6308\n",
      "Data columns (total 8 columns):\n",
      " #   Column       Non-Null Count  Dtype \n",
      "---  ------       --------------  ----- \n",
      " 0   school_name  6309 non-null   object\n",
      " 1   student_1    6309 non-null   int64 \n",
      " 2   student_2    6309 non-null   int64 \n",
      " 3   student_3    6309 non-null   int64 \n",
      " 4   student_4    6309 non-null   int64 \n",
      " 5   student_5    6309 non-null   int64 \n",
      " 6   student_6    6309 non-null   int64 \n",
      " 7   teacher      6309 non-null   int64 \n",
      "dtypes: int64(7), object(1)\n",
      "memory usage: 394.4+ KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/elementary.csv')\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "e26baecc-ea12-494a-9ec9-aecaa6cff4bb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "school_name    0\n",
       "student_1      0\n",
       "student_2      0\n",
       "student_3      0\n",
       "student_4      0\n",
       "student_5      0\n",
       "student_6      0\n",
       "teacher        0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "4ba24fcc-7a88-43b4-836c-38ba16492ed8",
   "metadata": {},
   "outputs": [],
   "source": [
    " df['total'] = df[['student_1', 'student_2', 'student_3', 'student_4', 'student_5', 'student_6']].sum(axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "1073d706-ae64-4c9f-90c3-570acbcc86ea",
   "metadata": {},
   "outputs": [],
   "source": [
    " df['teacher_1']=df['total']/df['teacher']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "777a45eb-3f6c-40d2-8c6d-34338a1c55ac",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>school_name</th>\n",
       "      <th>student_1</th>\n",
       "      <th>student_2</th>\n",
       "      <th>student_3</th>\n",
       "      <th>student_4</th>\n",
       "      <th>student_5</th>\n",
       "      <th>student_6</th>\n",
       "      <th>teacher</th>\n",
       "      <th>total</th>\n",
       "      <th>teacher_1</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1044</th>\n",
       "      <td>대구삼육초등학교</td>\n",
       "      <td>36</td>\n",
       "      <td>39</td>\n",
       "      <td>40</td>\n",
       "      <td>39</td>\n",
       "      <td>37</td>\n",
       "      <td>28</td>\n",
       "      <td>6</td>\n",
       "      <td>219</td>\n",
       "      <td>36.500000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3387</th>\n",
       "      <td>원주삼육초등학교</td>\n",
       "      <td>84</td>\n",
       "      <td>90</td>\n",
       "      <td>90</td>\n",
       "      <td>90</td>\n",
       "      <td>96</td>\n",
       "      <td>96</td>\n",
       "      <td>16</td>\n",
       "      <td>546</td>\n",
       "      <td>34.125000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1464</th>\n",
       "      <td>광주삼육초등학교</td>\n",
       "      <td>90</td>\n",
       "      <td>96</td>\n",
       "      <td>96</td>\n",
       "      <td>96</td>\n",
       "      <td>102</td>\n",
       "      <td>102</td>\n",
       "      <td>18</td>\n",
       "      <td>582</td>\n",
       "      <td>32.333333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>360</th>\n",
       "      <td>태강삼육초등학교</td>\n",
       "      <td>129</td>\n",
       "      <td>128</td>\n",
       "      <td>128</td>\n",
       "      <td>128</td>\n",
       "      <td>128</td>\n",
       "      <td>128</td>\n",
       "      <td>24</td>\n",
       "      <td>769</td>\n",
       "      <td>32.041667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>687</th>\n",
       "      <td>동성초등학교</td>\n",
       "      <td>128</td>\n",
       "      <td>128</td>\n",
       "      <td>128</td>\n",
       "      <td>128</td>\n",
       "      <td>127</td>\n",
       "      <td>89</td>\n",
       "      <td>23</td>\n",
       "      <td>728</td>\n",
       "      <td>31.652174</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6229</th>\n",
       "      <td>추자초등학교신양분교장</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2778</th>\n",
       "      <td>포천삼정초등학교</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>7</td>\n",
       "      <td>5</td>\n",
       "      <td>0.714286</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5122</th>\n",
       "      <td>흑산초등학교홍도분교장</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0.500000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6032</th>\n",
       "      <td>산양초등학교곤리분교장</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0.500000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3403</th>\n",
       "      <td>기린초등학교방동분교장</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>6309 rows × 10 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      school_name  student_1  student_2  student_3  student_4  student_5  \\\n",
       "1044     대구삼육초등학교         36         39         40         39         37   \n",
       "3387     원주삼육초등학교         84         90         90         90         96   \n",
       "1464     광주삼육초등학교         90         96         96         96        102   \n",
       "360      태강삼육초등학교        129        128        128        128        128   \n",
       "687        동성초등학교        128        128        128        128        127   \n",
       "...           ...        ...        ...        ...        ...        ...   \n",
       "6229  추자초등학교신양분교장          0          0          0          0          0   \n",
       "2778     포천삼정초등학교          0          0          0          2          1   \n",
       "5122  흑산초등학교홍도분교장          0          0          0          0          1   \n",
       "6032  산양초등학교곤리분교장          0          0          0          1          0   \n",
       "3403  기린초등학교방동분교장          0          0          0          0          0   \n",
       "\n",
       "      student_6  teacher  total  teacher_1  \n",
       "1044         28        6    219  36.500000  \n",
       "3387         96       16    546  34.125000  \n",
       "1464        102       18    582  32.333333  \n",
       "360         128       24    769  32.041667  \n",
       "687          89       23    728  31.652174  \n",
       "...         ...      ...    ...        ...  \n",
       "6229          1        1      1   1.000000  \n",
       "2778          2        7      5   0.714286  \n",
       "5122          0        2      1   0.500000  \n",
       "6032          0        2      1   0.500000  \n",
       "3403          0        0      0        NaN  \n",
       "\n",
       "[6309 rows x 10 columns]"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " df.sort_values(by='teacher_1', ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "8398b983-bd10-47e3-8dc0-1599496ad7a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n"
     ]
    }
   ],
   "source": [
    "df_sorted = df.sort_values(by='teacher_1', ascending=False)\n",
    "print(df_sorted['teacher'].iloc[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5da7dbe2-3d5d-4d88-9f09-d55b3c95cd81",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 16. 월별 범죄 발생 건수가 기록된 데이터가 주어진다. 연도별 월평균 범죄 발생 건수를 계산한 후, \n",
    "# 범죄가 가장 많이 발생한 연도의 월평균 건수를 정수로 출력하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "874dabbb-bdab-4e48-bb69-5af97b61c6cb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 84 entries, 0 to 83\n",
      "Data columns (total 7 columns):\n",
      " #   Column  Non-Null Count  Dtype \n",
      "---  ------  --------------  ----- \n",
      " 0   년월      84 non-null     object\n",
      " 1   강력범     84 non-null     int64 \n",
      " 2   절도범     84 non-null     int64 \n",
      " 3   폭력범     84 non-null     int64 \n",
      " 4   지능범     84 non-null     int64 \n",
      " 5   풍속범     84 non-null     int64 \n",
      " 6   기타형사범   84 non-null     int64 \n",
      "dtypes: int64(6), object(1)\n",
      "memory usage: 4.7+ KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/crime.csv')\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "7435a538-a8e3-4694-9ea9-3b2ab9705919",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>강력범</th>\n",
       "      <th>절도범</th>\n",
       "      <th>폭력범</th>\n",
       "      <th>지능범</th>\n",
       "      <th>풍속범</th>\n",
       "      <th>기타형사범</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>84.000000</td>\n",
       "      <td>84.000000</td>\n",
       "      <td>84.000000</td>\n",
       "      <td>84.000000</td>\n",
       "      <td>84.000000</td>\n",
       "      <td>84.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>446.285714</td>\n",
       "      <td>3840.976190</td>\n",
       "      <td>5931.738095</td>\n",
       "      <td>5659.059524</td>\n",
       "      <td>236.666667</td>\n",
       "      <td>1405.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>143.197780</td>\n",
       "      <td>1359.567144</td>\n",
       "      <td>986.131802</td>\n",
       "      <td>906.075429</td>\n",
       "      <td>161.785767</td>\n",
       "      <td>287.946796</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>22.000000</td>\n",
       "      <td>91.000000</td>\n",
       "      <td>263.000000</td>\n",
       "      <td>256.000000</td>\n",
       "      <td>8.000000</td>\n",
       "      <td>44.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>340.500000</td>\n",
       "      <td>2653.500000</td>\n",
       "      <td>5504.750000</td>\n",
       "      <td>5265.000000</td>\n",
       "      <td>149.750000</td>\n",
       "      <td>1257.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>420.000000</td>\n",
       "      <td>3924.500000</td>\n",
       "      <td>6034.000000</td>\n",
       "      <td>5831.500000</td>\n",
       "      <td>190.500000</td>\n",
       "      <td>1408.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>559.500000</td>\n",
       "      <td>4765.250000</td>\n",
       "      <td>6501.250000</td>\n",
       "      <td>6174.500000</td>\n",
       "      <td>265.500000</td>\n",
       "      <td>1577.250000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>724.000000</td>\n",
       "      <td>7317.000000</td>\n",
       "      <td>7849.000000</td>\n",
       "      <td>7115.000000</td>\n",
       "      <td>1216.000000</td>\n",
       "      <td>2099.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "              강력범          절도범          폭력범          지능범          풍속범  \\\n",
       "count   84.000000    84.000000    84.000000    84.000000    84.000000   \n",
       "mean   446.285714  3840.976190  5931.738095  5659.059524   236.666667   \n",
       "std    143.197780  1359.567144   986.131802   906.075429   161.785767   \n",
       "min     22.000000    91.000000   263.000000   256.000000     8.000000   \n",
       "25%    340.500000  2653.500000  5504.750000  5265.000000   149.750000   \n",
       "50%    420.000000  3924.500000  6034.000000  5831.500000   190.500000   \n",
       "75%    559.500000  4765.250000  6501.250000  6174.500000   265.500000   \n",
       "max    724.000000  7317.000000  7849.000000  7115.000000  1216.000000   \n",
       "\n",
       "             기타형사범  \n",
       "count    84.000000  \n",
       "mean   1405.666667  \n",
       "std     287.946796  \n",
       "min      44.000000  \n",
       "25%    1257.000000  \n",
       "50%    1408.000000  \n",
       "75%    1577.250000  \n",
       "max    2099.000000  "
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " df.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "a64b505c-beea-405b-86b8-171f96b278d7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>년월</th>\n",
       "      <th>강력범</th>\n",
       "      <th>절도범</th>\n",
       "      <th>폭력범</th>\n",
       "      <th>지능범</th>\n",
       "      <th>풍속범</th>\n",
       "      <th>기타형사범</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2007-01</td>\n",
       "      <td>291</td>\n",
       "      <td>2608</td>\n",
       "      <td>6494</td>\n",
       "      <td>5283</td>\n",
       "      <td>242</td>\n",
       "      <td>1126</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2007-02</td>\n",
       "      <td>252</td>\n",
       "      <td>2403</td>\n",
       "      <td>4613</td>\n",
       "      <td>4270</td>\n",
       "      <td>158</td>\n",
       "      <td>880</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2007-03</td>\n",
       "      <td>292</td>\n",
       "      <td>2273</td>\n",
       "      <td>6242</td>\n",
       "      <td>5110</td>\n",
       "      <td>196</td>\n",
       "      <td>1119</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2007-04</td>\n",
       "      <td>306</td>\n",
       "      <td>2794</td>\n",
       "      <td>6813</td>\n",
       "      <td>5492</td>\n",
       "      <td>250</td>\n",
       "      <td>1311</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2007-05</td>\n",
       "      <td>298</td>\n",
       "      <td>3469</td>\n",
       "      <td>7221</td>\n",
       "      <td>5432</td>\n",
       "      <td>192</td>\n",
       "      <td>1412</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        년월  강력범   절도범   폭력범   지능범  풍속범  기타형사범\n",
       "0  2007-01  291  2608  6494  5283  242   1126\n",
       "1  2007-02  252  2403  4613  4270  158    880\n",
       "2  2007-03  292  2273  6242  5110  196   1119\n",
       "3  2007-04  306  2794  6813  5492  250   1311\n",
       "4  2007-05  298  3469  7221  5432  192   1412"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "89659bf6-7f22-49a2-b3b6-e4ca97e85736",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['year']=df['년월'].str[:4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "939ec140-430f-41e6-84b3-67c1ba2eeff8",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['case'] = df[['강력범', '절도범', '폭력범', '지능범', '풍속범', '기타형사범']].sum(axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "4460d70f-7bd5-4e33-9d67-f8c9e5eeda37",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>case_mean</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2007</td>\n",
       "      <td>14880.333333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2008</td>\n",
       "      <td>15631.833333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2009</td>\n",
       "      <td>17505.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2010</td>\n",
       "      <td>17391.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2011</td>\n",
       "      <td>18613.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2012</td>\n",
       "      <td>19291.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2013</td>\n",
       "      <td>19329.250000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   year     case_mean\n",
       "0  2007  14880.333333\n",
       "1  2008  15631.833333\n",
       "2  2009  17505.666667\n",
       "3  2010  17391.000000\n",
       "4  2011  18613.000000\n",
       "5  2012  19291.666667\n",
       "6  2013  19329.250000"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " df.groupby('year').agg(case_mean=('case', 'mean')).reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "id": "836ff958-a3c4-404f-8018-b0d4c7561ab9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "19329\n"
     ]
    }
   ],
   "source": [
    "df2=df.groupby('year').agg(case_mean=('case', 'mean')).reset_index()\n",
    "print(round(df2[df2['year'] == '2013']['case_mean'].values[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "105df6fd-d776-40b4-9048-5e59ea92f04d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 17. 결측치를 포함한 행을 제거한 후 학생들이 가장 많이 수강한 과목의 점수를 표준화하고, 표준화된 \n",
    "# 점수 중 최댓값을 소수점 셋째 자리까지 반올림하여 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "f4b66f5b-689e-41b2-b966-6867020ddf30",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv(\"c:/data/7_type1_1.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "59d736dc-40ef-4b77-9994-37fe81f0f429",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>student_id</th>\n",
       "      <th>evaluation_subject</th>\n",
       "      <th>learning_period</th>\n",
       "      <th>score</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>103</td>\n",
       "      <td>22</td>\n",
       "      <td>87.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>93</td>\n",
       "      <td>70</td>\n",
       "      <td>92.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2</td>\n",
       "      <td>15</td>\n",
       "      <td>22</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3</td>\n",
       "      <td>107</td>\n",
       "      <td>22</td>\n",
       "      <td>51.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>4</td>\n",
       "      <td>72</td>\n",
       "      <td>22</td>\n",
       "      <td>73.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   student_id  evaluation_subject  learning_period  score\n",
       "0           0                 103               22   87.0\n",
       "1           1                  93               70   92.0\n",
       "2           2                  15               22    2.0\n",
       "3           3                 107               22   51.0\n",
       "4           4                  72               22   73.0"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "57b37d9b-80d9-4105-b4b4-77684232bd80",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "student_id            0\n",
       "evaluation_subject    0\n",
       "learning_period       0\n",
       "score                 2\n",
       "dtype: int64"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "9ea3d91b-fe59-4111-ab68-a54dc78a0fb6",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_cleaned=df.dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "31b149ab-1438-49f6-8dbe-c1720f09b12e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_cleaned['evaluation_subject'].value_counts().idxmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "b7b8ccae-fda8-4a49-942d-5060bee228b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "most_taken_subject=df_cleaned['evaluation_subject'].value_counts().idxmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "38f82e22-e176-4596-a487-479f7e092eba",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "scaler=StandardScaler()\n",
    "standardized_score = scaler.fit_transform(df_cleaned[df_cleaned['evaluation_subject']==most_taken_subject][['score']])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "034ff991-acd8-4f07-a165-2adbe3f2b7f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "max_standardized_score=round(standardized_score.max(), 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "53059d00-7f1e-4311-b64a-7f2ee41846af",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.183\n"
     ]
    }
   ],
   "source": [
    "print(max_standardized_score)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d97bcc9-e761-4a79-a37a-da085f1eeb24",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 18. MEDV 변수와 가장 높은 상관관계를 갖는 변수를 식별한 후, 해당 변수의 평균값을 소수점 셋째 자리까지 반올림하여 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "44400b89-6674-4f86-8a53-7291d8c551d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv(\"c:/data/7_type1_2.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "3b78dd1c-8353-4f43-af73-61bf735263a7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 506 entries, 0 to 505\n",
      "Data columns (total 13 columns):\n",
      " #   Column   Non-Null Count  Dtype  \n",
      "---  ------   --------------  -----  \n",
      " 0   CRIM     506 non-null    float64\n",
      " 1   ZN       506 non-null    float64\n",
      " 2   INDUS    506 non-null    float64\n",
      " 3   CHAS     506 non-null    int64  \n",
      " 4   NOX      506 non-null    float64\n",
      " 5   RM       506 non-null    float64\n",
      " 6   AGE      506 non-null    float64\n",
      " 7   DIS      506 non-null    float64\n",
      " 8   RAD      506 non-null    int64  \n",
      " 9   TAX      506 non-null    int64  \n",
      " 10  PTRATIO  506 non-null    float64\n",
      " 11  LSTAT    506 non-null    float64\n",
      " 12  MEDV     506 non-null    float64\n",
      "dtypes: float64(10), int64(3)\n",
      "memory usage: 51.5 KB\n"
     ]
    }
   ],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "id": "39fa73b5-6065-40ad-b22a-637254dbe5b0",
   "metadata": {},
   "outputs": [],
   "source": [
    " correlation_matrix=df.corr()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "id": "01c2e1ac-1319-4b0f-b20b-d756bd5f6660",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'LSTAT'"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation_matrix[\"MEDV\"].drop(\"MEDV\").abs().idxmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "id": "9b3c90af-1f3c-47a5-8ac5-2630de04a862",
   "metadata": {},
   "outputs": [],
   "source": [
    " most_correlated_var=correlation_matrix[\"MEDV\"].drop(\"MEDV\").abs().idxmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "id": "0270c241-e189-4977-b87e-243a9cbc6419",
   "metadata": {},
   "outputs": [],
   "source": [
    " mean_value=round(df[most_correlated_var].mean(), 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "id": "d815d732-b421-4c0a-b866-15c9e9c6488b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LSTAT 12.653\n"
     ]
    }
   ],
   "source": [
    " print(most_correlated_var, mean_value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4ba3732-557f-4a17-8b39-3dae05a2d380",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 19 상자그림(Boxplot)을 활용하여 'Weight' 변수에서 이상값의 개수를 구하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "id": "3a13a305-5bd1-43c2-a32a-26038af92889",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv(\"c:/data/7_type1_3.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "id": "45ed21ce-6e05-46ce-97b9-de261c04274f",
   "metadata": {},
   "outputs": [],
   "source": [
    "Q1,Q3=df[\"Weight\"].quantile([0.25, 0.75])\n",
    "IQR=Q3 - Q1\n",
    "lower_bound,upper_bound=Q1-1.5*IQR,Q3+1.5*IQR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "id": "d2c4894b-daa5-4399-a01b-c5d09d832ec7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 125,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "((df[\"Weight\"] < lower_bound)|(df[\"Weight\"] > upper_bound)).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "id": "4fa8ea32-1d98-4d29-b4e6-92e5fabf6b92",
   "metadata": {},
   "outputs": [],
   "source": [
    " num_weight_outliers = ((df[\"Weight\"] < lower_bound)|(df[\"Weight\"] > upper_bound)).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "id": "8a7ec4c8-707e-4ef4-9997-7a437fe1337b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    " print(num_weight_outliers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb7bda6f-1fd9-41f8-a6b6-db0402ebefcf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 20. 국가별 맥주 소비량 데이터이다. 대륙(Continent)별 맥주 소비량(beer_servings)의 평균을 계산하고, \n",
    "# 평균이 가장 큰 대륙을 찾은 후 그 대륙에서 맥주 소비량이 5번째로 많은 국가(Country)의 맥주 소비량을 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "id": "449a81ab-70a9-4a44-921c-285fd50afbd9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 193 entries, 0 to 192\n",
      "Data columns (total 6 columns):\n",
      " #   Column                        Non-Null Count  Dtype  \n",
      "---  ------                        --------------  -----  \n",
      " 0   country                       193 non-null    object \n",
      " 1   beer_servings                 193 non-null    int64  \n",
      " 2   spirit_servings               193 non-null    int64  \n",
      " 3   wine_servings                 193 non-null    int64  \n",
      " 4   total_litres_of_pure_alcohol  193 non-null    float64\n",
      " 5   continent                     193 non-null    object \n",
      "dtypes: float64(1), int64(3), object(2)\n",
      "memory usage: 9.2+ KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/8_type1_1.csv')\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "id": "b46c88c7-1a4a-486b-b4f8-72f2e50eda5b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "country                         0\n",
       "beer_servings                   0\n",
       "spirit_servings                 0\n",
       "wine_servings                   0\n",
       "total_litres_of_pure_alcohol    0\n",
       "continent                       0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 133,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "id": "fc5270f3-cc51-410c-8ac7-a9e2dc65ebe7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "continent\n",
       "Europe           281.666667\n",
       "Africa           276.849057\n",
       "South America    243.583333\n",
       "Asia             234.727273\n",
       "North America    225.521739\n",
       "Oceania          208.812500\n",
       "Name: beer_servings, dtype: float64"
      ]
     },
     "execution_count": 135,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " df.groupby('continent')['beer_servings'].mean().sort_values(ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "eea50b66-5875-44af-8e85-3c0f848bd146",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Europe\n"
     ]
    }
   ],
   "source": [
    "continent_mean=df.groupby('continent')['beer_servings'].mean().sort_values(ascending=False)\n",
    "top_continent=continent_mean.idxmax()\n",
    "print(top_continent)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "38933b30-853a-49c5-babc-4bfd8647b1b7",
   "metadata": {},
   "outputs": [],
   "source": [
    " top_continent_countries=df[df['continent']==\"Europe\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "id": "97c04007-8be4-490c-9bca-5a35b4cc6fc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "top_continent_countries=top_continent_countries.sort_values(by='beer_servings', ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "id": "5f65763d-cf87-4f55-9baa-4964bba267ce",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "        country  beer_servings  spirit_servings  wine_servings  \\\n",
      "140     Romania            498              232            289   \n",
      "135      Poland            491              253             22   \n",
      "93       Latvia            476              279             91   \n",
      "42      Croatia            475              358            154   \n",
      "10   Azerbaijan            466               35             48   \n",
      "44       Cyprus            463              136            103   \n",
      "\n",
      "     total_litres_of_pure_alcohol continent  \n",
      "140                     15.141624    Europe  \n",
      "135                     10.686925    Europe  \n",
      "93                       1.157278    Europe  \n",
      "42                      17.837938    Europe  \n",
      "10                       1.999698    Europe  \n",
      "44                      10.266523    Europe  \n"
     ]
    }
   ],
   "source": [
    " print((top_continent_countries).head(6))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "id": "295a294f-b5c7-4e3e-bd0e-eff3d9e5dbac",
   "metadata": {},
   "outputs": [],
   "source": [
    " fifth_highest=top_continent_countries.iloc[4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "6b891acc-223a-4e41-80ff-30918217ae5f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "466\n"
     ]
    }
   ],
   "source": [
    " print(fifth_highest['beer_servings'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7602edc3-3859-489a-a269-d3bec4c9abd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 21. 국가별 방문에 대한 데이터이다. ‘관광객 비율’이 두 번째로 높은 국가의 '사업' 방문객 수를 a라고 정의하고,\n",
    "# ‘관광’이 두 번째로 높은  국가의 ‘공무’ 방문객 수를 b로 정의할 때 a와 b의 합을 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "id": "b5bd9ee8-9e68-481d-bc5f-dd2e9fed2c48",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/8_type1_2.csv',encoding='cp949')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "id": "1131bac1-dc8e-4377-abe5-58b8262faeb6",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['관광객 비율']=df['관광']/(df['관광'] +df['공무']+df['사업']+df['기타'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "id": "df3c7933-6cdf-47e4-8ca0-a41b3f85b1f3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "나라            국가50\n",
       "관광            1186\n",
       "공무             147\n",
       "사업             201\n",
       "기타              87\n",
       "관광객 비율    0.731647\n",
       "Name: 49, dtype: object"
      ]
     },
     "execution_count": 155,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " df.sort_values(by='관광객 비율', ascending=False).iloc[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "e3531ccf-c4af-4768-a18d-614517771654",
   "metadata": {},
   "outputs": [],
   "source": [
    " second_highest_tourism_country = df.sort_values(by='관광객 비율', ascending=False).iloc[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "61f9b38a-301d-4315-954a-2c608fff939f",
   "metadata": {},
   "outputs": [],
   "source": [
    " a=second_highest_tourism_country['사업']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 161,
   "id": "b9d38152-f940-4d97-8d3c-b6704e617373",
   "metadata": {},
   "outputs": [],
   "source": [
    " second_highest_sightseeing_country = df.sort_values(by='관광', ascending=False).iloc[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 163,
   "id": "30fe3074-9d15-433e-a46d-90b4aa7e67b2",
   "metadata": {},
   "outputs": [],
   "source": [
    " b=second_highest_sightseeing_country['공무']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 165,
   "id": "28896a55-1725-4574-b203-950d2ddecaa2",
   "metadata": {},
   "outputs": [],
   "source": [
    "total=a + b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 167,
   "id": "3f568634-2d7b-4b54-b067-2a3cfaa92ecb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "362\n"
     ]
    }
   ],
   "source": [
    " print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c133039b-5eab-4dd6-a440-4b9462fcf695",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 22 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 301,
   "id": "fa2e4044-ff80-4e6b-a4b3-84cad869e018",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "wine=pd.read_csv(\"c:/data/wine_dataset.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 303,
   "id": "8743fe0a-e881-433b-88db-5211d65c843f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 305,
   "id": "f5938a91-2a59-439d-98ce-017b36d55d43",
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler=MinMaxScaler()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 307,
   "id": "fdd97552-8d94-43d8-a151-192ac4316ba2",
   "metadata": {},
   "outputs": [],
   "source": [
    "wine['density_scaled']=scaler.fit_transform(wine[['density']])\n",
    "wine['alcohol_scaled']=scaler.fit_transform(wine[['alcohol']])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 309,
   "id": "612dd022-6fb2-4ecb-b89e-62756a470ac9",
   "metadata": {},
   "outputs": [],
   "source": [
    "density_std=np.std(wine['density_scaled'])\n",
    "alcohol_std=np.std(wine['alcohol_scaled'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 311,
   "id": "e588352c-5bcb-489a-9652-6cd5b6603dab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.017\n"
     ]
    }
   ],
   "source": [
    "result=round(density_std - alcohol_std, 3)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "01a158d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# CHAPTER 04.작업형 제 2유형\n",
    "# 작업형 제 2유형이 합격을 결정하는 변수이다.\n",
    "# 1문항,40점 배정\n",
    "# ① 작업형 1,3 유형에 비해 코딩량이 많아 문법적 오류 발생이 빈번하다. \n",
    "# ② 가장 단순하고 이해도 높은 분류 또는 예측 모형을 선택한다.\n",
    "# ③ 답안 작성 요구 사항을 꼼꼼하게 확인하고 또 확인한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f07c7ea7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 공지사항\n",
    "# 출력을 원하실 경우 print() 함수 활용\n",
    "# 예시) print(df.head())\n",
    "# getcwd(), chdir() 등 작업 폴더 설정 불필요\n",
    "# 파일 경로 상 내부 드라이브 경로(C: 등) 접근 불가\n",
    "# 아래 코드 예측변수와 수험번호를 개인별로 변경하여 활용\n",
    "# pd.DataFrame({'cust_id': X_test.cust_id, 'gender': pred}).to_csv('003000000.csv', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0a7700e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 01 기출문제 (분류모형 구축),binary class\n",
    "# 빅데이터 분석 기사 체험 환경과 동일한 데이터셋이므로 체험 환경에서 아래 해당 코딩을 실행 하는 것이 중요\n",
    "# 백화점 고객의 1년간 구매 데이터이다.\n",
    "# 고객 3,500명에 대한 학습용 데이터(x_train.csv,y_train.csv)를 이용하여 \n",
    "# 성별 예측 모형을 만든 후 이를 평가용 데이터(x_test.csv)에 적용하여 \n",
    "# 얻은 2,482명의 고객 성별 예측값(남자일 확률)을 csv파일로 제출하시오.\n",
    "# 제출할 모델의 성능은 ROC_AUC 평가지표에 따라 채점\n",
    "# binary class classfication"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0867e2df",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 유의사항\n",
    "# 성능이 우수한 예측 모형을 구축하려면 적절한 데이터 전처리, Feature Engineering(변수 스케일링,인코딩) \n",
    "# 분류 알고리즘 사용,하이퍼 파라미터 최적화, 모형 앙상블 등이 수반되어야 한다.\n",
    "# ㉮ 제공 데이터 목록\n",
    "# ① y_train.csv : 고객의 성별 데이터(학습용), csv 형식파일\n",
    "# ② x_train.csv,x_test.csv : 고객의 상품구매 속성(학습용 및 평가용), csv 형식파일\n",
    "# ㉯ 데이터 형식 및 내용\n",
    "# ① y_train.csv(3,500명 데이터)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 187,
   "id": "399ee980",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 189,
   "id": "6384b366",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 한글깨짐 문제를 해결하기 위해 encoding = 'cp949' 사용합니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 191,
   "id": "a1094033",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train=pd.read_csv(\"c:/data/x_train.csv\",encoding = 'cp949' )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 193,
   "id": "60fb4036",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_test=pd.read_csv(\"c:/data/x_test.csv\",encoding = 'cp949')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 195,
   "id": "fcfd8ab9",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_train=pd.read_csv(\"c:/data/y_train.csv\",encoding = 'cp949')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 197,
   "id": "dd9f7f1b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1) 학습데이터와 평가데이터 컬럼(변수)와 데이터의 행과 열의 수를 확인"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "id": "bdccffc9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   cust_id      총구매액     최대구매액       환불금액   주구매상품 주구매지점  내점일수   내점당구매건수  \\\n",
      "0        0  68282840  11264000  6860000.0      기타   강남점    19  3.894737   \n",
      "1        1   2136000   2136000   300000.0     스포츠   잠실점     2  1.500000   \n",
      "2        2   3197000   1639000        NaN  남성 캐주얼   관악점     2  2.000000   \n",
      "\n",
      "     주말방문비율  구매주기  \n",
      "0  0.527027    17  \n",
      "1  0.000000     1  \n",
      "2  0.000000     1  \n"
     ]
    }
   ],
   "source": [
    "print(x_train.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 201,
   "id": "3e501bea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3500, 10)\n"
     ]
    }
   ],
   "source": [
    "print(x_train.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 203,
   "id": "eadf795e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   cust_id       총구매액     최대구매액        환불금액 주구매상품 주구매지점  내점일수    내점당구매건수  \\\n",
      "0     3500   70900400  22000000   4050000.0    골프  부산본점    13   1.461538   \n",
      "1     3501  310533100  38558000  48034700.0   농산물   잠실점    90   2.433333   \n",
      "2     3502  305264140  14825000  30521000.0  가공식품  본  점   101  14.623762   \n",
      "\n",
      "     주말방문비율  구매주기  \n",
      "0  0.789474    26  \n",
      "1  0.369863     3  \n",
      "2  0.083277     3  \n"
     ]
    }
   ],
   "source": [
    "# x_test 변수에는 타켓(목표)변수가 없음\n",
    "print(x_test.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 205,
   "id": "d5aff222",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(2482, 10)\n"
     ]
    }
   ],
   "source": [
    "print(x_test.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 207,
   "id": "d8490f12",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   cust_id  gender\n",
      "0        0       0\n",
      "1        1       0\n",
      "2        2       1\n"
     ]
    }
   ],
   "source": [
    "print(y_train.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 209,
   "id": "38997ae1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3500, 2)\n"
     ]
    }
   ],
   "source": [
    "# 데이터가 각각 x_train,y_train,x_test 분할된 상태에서 실기 응시\n",
    "print(y_train.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 211,
   "id": "0f89a3a9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 3500 entries, 0 to 3499\n",
      "Data columns (total 10 columns):\n",
      " #   Column   Non-Null Count  Dtype  \n",
      "---  ------   --------------  -----  \n",
      " 0   cust_id  3500 non-null   int64  \n",
      " 1   총구매액     3500 non-null   int64  \n",
      " 2   최대구매액    3500 non-null   int64  \n",
      " 3   환불금액     1205 non-null   float64\n",
      " 4   주구매상품    3500 non-null   object \n",
      " 5   주구매지점    3500 non-null   object \n",
      " 6   내점일수     3500 non-null   int64  \n",
      " 7   내점당구매건수  3500 non-null   float64\n",
      " 8   주말방문비율   3500 non-null   float64\n",
      " 9   구매주기     3500 non-null   int64  \n",
      "dtypes: float64(3), int64(5), object(2)\n",
      "memory usage: 273.6+ KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(x_train.info())\n",
    "# 주구매상품,주구매지점 변수는 문자형(object)\n",
    "# 환불금액 변수는 결측치가 존재"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 213,
   "id": "9a9a159b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2) 불필요한 컬럼 삭제\n",
    "# cust_id는 고객 ID로 불필요한 컬럼\n",
    "# 답안 제출시에 필요한 컬럼이므로 별도 변수명 저장\n",
    "x_test_cust_id=x_test['cust_id']\n",
    "x_train=x_train.drop(columns=['cust_id'])\n",
    "y_train=y_train.drop(columns=['cust_id'])\n",
    "x_test=x_test.drop(columns=['cust_id'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 215,
   "id": "d0efe2e5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "총구매액          0\n",
      "최대구매액         0\n",
      "환불금액       2295\n",
      "주구매상품         0\n",
      "주구매지점         0\n",
      "내점일수          0\n",
      "내점당구매건수       0\n",
      "주말방문비율        0\n",
      "구매주기          0\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 3)결측치 처리\n",
    "print(x_train.isna().sum())\n",
    "# 환불금액에서 결측치는 환불 이력이 없음을 의미함으로 결측치를 숫자 '0' 대체한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 217,
   "id": "f41fca22",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "총구매액          0\n",
      "최대구매액         0\n",
      "환불금액       1611\n",
      "주구매상품         0\n",
      "주구매지점         0\n",
      "내점일수          0\n",
      "내점당구매건수       0\n",
      "주말방문비율        0\n",
      "구매주기          0\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(x_test.isna().sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 219,
   "id": "d5b8431e",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train['환불금액']=x_train['환불금액'].fillna(0)\n",
    "x_test['환불금액']=x_test['환불금액'].fillna(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 221,
   "id": "9e86f286",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "총구매액       0\n",
      "최대구매액      0\n",
      "환불금액       0\n",
      "주구매상품      0\n",
      "주구매지점      0\n",
      "내점일수       0\n",
      "내점당구매건수    0\n",
      "주말방문비율     0\n",
      "구매주기       0\n",
      "dtype: int64\n",
      "총구매액       0\n",
      "최대구매액      0\n",
      "환불금액       0\n",
      "주구매상품      0\n",
      "주구매지점      0\n",
      "내점일수       0\n",
      "내점당구매건수    0\n",
      "주말방문비율     0\n",
      "구매주기       0\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 결측치 처리 여부를 체크한다.\n",
    "print(x_train.isna().sum())\n",
    "print(x_test.isna().sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 223,
   "id": "db3132c3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['기타' '스포츠' '남성 캐주얼' '보석' '디자이너' '시티웨어' '명품' '농산물' '화장품' '골프' '구두' '가공식품'\n",
      " '수산품' '아동' '차/커피' '캐주얼' '섬유잡화' '육류' '축산가공' '젓갈/반찬' '액세서리' '피혁잡화' '일용잡화'\n",
      " '주방가전' '주방용품' '건강식품' '가구' '주류' '모피/피혁' '남성 트랜디' '셔츠' '남성정장' '생활잡화'\n",
      " '트래디셔널' '란제리/내의' '커리어' '침구/수예' '대형가전' '통신/컴퓨터' '식기' '소형가전' '악기']\n"
     ]
    }
   ],
   "source": [
    "# 4) 인코딩(범주형변수)\n",
    "# 사이킷런은 카테고리만을 위한 데이터 타입이 없으며, 모두 숫자로 변환해야 함\n",
    "# '주구매상품' 변수에서 중복을 제외한 값 확인\n",
    "print(x_train['주구매상품'].unique())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 225,
   "id": "74fd19a6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "42\n"
     ]
    }
   ],
   "source": [
    "# 42개의 값으로 구성\n",
    "print(x_train['주구매상품'].unique().size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 227,
   "id": "5830a643",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['강남점' '잠실점' '관악점' '광주점' '본  점' '일산점' '대전점' '부산본점' '분당점' '영등포점' '미아점'\n",
      " '청량리점' '안양점' '부평점' '동래점' '포항점' '노원점' '창원점' '센텀시티점' '인천점' '대구점' '전주점'\n",
      " '울산점' '상인점']\n"
     ]
    }
   ],
   "source": [
    "# '주구매상품' 변수에서 중복을 제외한 값 확인\n",
    "print(x_train['주구매지점'].unique())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 229,
   "id": "88d24964",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24\n"
     ]
    }
   ],
   "source": [
    "# 24개의  값으로 구성\n",
    "print(x_train['주구매지점'].unique().size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 231,
   "id": "e6149894",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 라벨 인코딩 수행\n",
    "# 사이킷런 패키지의 전처리 모듈에서 라벨 인코딩 함수 가져오기\n",
    "from sklearn.preprocessing import LabelEncoder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 233,
   "id": "0a224348",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 인코더 함수 생성\n",
    "encoder=LabelEncoder()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 235,
   "id": "08727adf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# '주구매상품' 라벨 인코딩 수행\n",
    "x_train['주구매상품']=encoder.fit_transform(x_train['주구매상품'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 237,
   "id": "22f7b356",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0     5\n",
      "1    21\n",
      "2     6\n",
      "Name: 주구매상품, dtype: int32\n"
     ]
    }
   ],
   "source": [
    "# 라벨 인코딩 수행 확인\n",
    "print(x_train['주구매상품'].head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 239,
   "id": "e4afe392",
   "metadata": {},
   "outputs": [],
   "source": [
    "# '주구매상품' 라벨 인코딩 수행\n",
    "x_train['주구매지점']=encoder.fit_transform(x_train['주구매지점'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 241,
   "id": "7f61a535",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0     0\n",
      "1    19\n",
      "2     1\n",
      "Name: 주구매지점, dtype: int32\n"
     ]
    }
   ],
   "source": [
    "# 라벨 인코딩 수행 확인\n",
    "print(x_train['주구매지점'].head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 243,
   "id": "e323298c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# x_test 동일하게 인코딩 수행\n",
    "x_test['주구매상품']=encoder.fit_transform(x_test['주구매상품'])\n",
    "x_test['주구매지점']=encoder.fit_transform(x_test['주구매지점'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 245,
   "id": "8d436426",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       총구매액     최대구매액       환불금액  주구매상품  주구매지점  내점일수   내점당구매건수    주말방문비율  구매주기\n",
      "0  68282840  11264000  6860000.0      5      0    19  3.894737  0.527027    17\n",
      "1   2136000   2136000   300000.0     21     19     2  1.500000  0.000000     1\n",
      "2   3197000   1639000        0.0      6      1     2  2.000000  0.000000     1\n"
     ]
    }
   ],
   "source": [
    "# 인코딩 확인\n",
    "print(x_train.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 369,
   "id": "d229cbdf",
   "metadata": {},
   "outputs": [],
   "source": [
    "#5) 표준화,StandardScaler()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 371,
   "id": "74324d80",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 373,
   "id": "1ece9342",
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler=StandardScaler()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 387,
   "id": "a4227919-629b-4e65-b4a7-ff7ee6d91efc",
   "metadata": {},
   "outputs": [],
   "source": [
    " # 숫자형 컬럼만 선택\n",
    "num_cols=x_train.select_dtypes(include=['number']).columns\n",
    "x_train[num_cols] = scaler.fit_transform(x_train[num_cols])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 389,
   "id": "196e90f0-60f8-439e-b82e-3e395c286b79",
   "metadata": {},
   "outputs": [],
   "source": [
    "num_cols=x_test.select_dtypes(include=['number']).columns\n",
    "x_test[num_cols] = scaler.transform(x_test[num_cols])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "1424e062",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 변수들의 단위 차이로 인해 숫자의 스케일이 크게 달라지는 경우. \n",
    "# 이 경우에는 스케일링(scaling)으로 해결한다\n",
    "# ① StandardScaler\n",
    "# 평균을 제거하고 데이터를 단위 분산으로 조정한다. \n",
    "# 그러나 이상치가 있다면 평균과 표준편차에 영향을 미쳐 변환된 데이터의 확산은 \n",
    "# 매우 달라지게 된다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "05562212",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ② MinMaxScaler\n",
    "# 모든 feature 값이 0~1사이에 있도록 데이터를 재조정한다. 다만 이상치가 있는 경우 변환된 값이 \n",
    "# 매우 좁은 범위로 압축될 수 있다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "0d277b21",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ③ MaxAbsScaler\n",
    "# 최대절대값과 0이 각각 1, 0이 되도록 스케일링"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "9bd92910",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ④ RobustScaler\n",
    "# 아웃라이어의 영향을 최소화한 기법이다.\n",
    "# 중앙값(median)과 IQR(interquartile range)을 사용하기 때문에 \n",
    "# StandardScaler와 비교해보면 표준화 후 동일한 값을 더 넓게 분포하게 됨"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "571ce739-b959-48a3-ab77-a86ae1542c28",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 연속형 변수만 표준화 (거리기반 알고리즘 사용할 때)\n",
    "# 범주형 변수의 인코딩을 제외하하고 표준화 방법"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3045500f-8cc0-4d8b-9a46-67f3b372caa7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 거리 기반 알고리즘에서는 레이블 인코딩 대신에 get_dummies 사용\n",
    "x_train = pd.get_dummies(x_train)\n",
    "x_test = pd.get_dummies(x_test)\n",
    "x_train, x_test = x_train.align(x_test, join='left', axis=1, fill_value=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 247,
   "id": "6da55320-2de1-4808-b844-120721e2498c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "num_cols = ['총구매액', '최대구매액', '환불금액', '내점일수', \n",
    "            '내점당구매건수', '주말방문비율', '구매주기']\n",
    "scaler = StandardScaler()\n",
    "x_train[num_cols] = scaler.fit_transform(x_train[num_cols])\n",
    "x_test[num_cols] = scaler.transform(x_test[num_cols])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 391,
   "id": "f5f44cf4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 393,
   "id": "79b899bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "model=RandomForestClassifier()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 395,
   "id": "bf82d0f3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-1 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-1 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-1 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-1 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-1 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-1 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;RandomForestClassifier<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.ensemble.RandomForestClassifier.html\">?<span>Documentation for RandomForestClassifier</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestClassifier()</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestClassifier()"
      ]
     },
     "execution_count": 395,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.fit(x_train,y_train.values.ravel())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 397,
   "id": "f6b3e036",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_test_predicted=model.predict(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 399,
   "id": "9860c7a8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 0, 0, ..., 1, 0, 0], dtype=int64)"
      ]
     },
     "execution_count": 399,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_test_predicted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 401,
   "id": "e78af6d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 7) 모델 평가\n",
    "from sklearn.metrics import accuracy_score,roc_auc_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 403,
   "id": "a7c78950",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9999993041406415\n"
     ]
    }
   ],
   "source": [
    "# 분류모형으로 예측값(y_test_predicted)에 맞춰볼 수 있는 y_test값은 문제에서 제공되지 않음\n",
    "# 학습데이터 모델을 만들고 정확도롤 측정\n",
    "y_train_proba = model.predict_proba(x_train)[:, 1]\n",
    "print(roc_auc_score(y_train, y_train_proba))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 405,
   "id": "2af6b1fd-e2fc-4c57-9d51-9fcaf9833e5e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9994285714285714\n"
     ]
    }
   ],
   "source": [
    " y_train_predicted=model.predict(x_train)\n",
    "print(accuracy_score(y_train,y_train_predicted))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 407,
   "id": "1a2b497f-c8ba-49a6-bedd-c5169565a55b",
   "metadata": {},
   "outputs": [],
   "source": [
    " y_test_proba=model.predict_proba(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 409,
   "id": "188ea21e-4a2c-45c3-84af-3605bf499ad7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      0     1\n",
      "0  0.50  0.50\n",
      "1  0.77  0.23\n",
      "2  0.79  0.21\n",
      "3  0.58  0.42\n",
      "4  0.55  0.45\n"
     ]
    }
   ],
   "source": [
    " print(pd.DataFrame(y_test_proba).head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0908f37b-0b84-4069-8f0d-386bf4d81dd7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 8) 데이터 병합"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac18562e-9dca-4107-ab92-265649a530e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 9)답안 제출"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 411,
   "id": "5de780e4-6af8-47fd-92e5-8e7c7d869f6e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0       0.50\n",
      "1       0.23\n",
      "2       0.21\n",
      "3       0.42\n",
      "4       0.45\n",
      "        ... \n",
      "2477    0.63\n",
      "2478    0.64\n",
      "2479    0.58\n",
      "2480    0.42\n",
      "2481    0.44\n",
      "Name: 1, Length: 2482, dtype: float64\n"
     ]
    }
   ],
   "source": [
    " print(pd.DataFrame(y_test_proba)[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 413,
   "id": "dfac4abd-a9a5-4593-bc65-e8a090bc0d93",
   "metadata": {},
   "outputs": [],
   "source": [
    " df=pd.DataFrame(y_test_proba)[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 415,
   "id": "dec8cd5d-9820-4f83-b376-fa5a021db3d4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0       0.50\n",
       "1       0.23\n",
       "2       0.21\n",
       "3       0.42\n",
       "4       0.45\n",
       "        ... \n",
       "2477    0.63\n",
       "2478    0.64\n",
       "2479    0.58\n",
       "2480    0.42\n",
       "2481    0.44\n",
       "Name: 1, Length: 2482, dtype: float64"
      ]
     },
     "execution_count": 415,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 417,
   "id": "97860e6a-56e9-4a94-a713-ca5536501294",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>cust_id</th>\n",
       "      <th>1</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3500</td>\n",
       "      <td>0.50</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3501</td>\n",
       "      <td>0.23</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3502</td>\n",
       "      <td>0.21</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3503</td>\n",
       "      <td>0.42</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3504</td>\n",
       "      <td>0.45</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2477</th>\n",
       "      <td>5977</td>\n",
       "      <td>0.63</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2478</th>\n",
       "      <td>5978</td>\n",
       "      <td>0.64</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2479</th>\n",
       "      <td>5979</td>\n",
       "      <td>0.58</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2480</th>\n",
       "      <td>5980</td>\n",
       "      <td>0.42</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2481</th>\n",
       "      <td>5981</td>\n",
       "      <td>0.44</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>2482 rows × 2 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      cust_id     1\n",
       "0        3500  0.50\n",
       "1        3501  0.23\n",
       "2        3502  0.21\n",
       "3        3503  0.42\n",
       "4        3504  0.45\n",
       "...       ...   ...\n",
       "2477     5977  0.63\n",
       "2478     5978  0.64\n",
       "2479     5979  0.58\n",
       "2480     5980  0.42\n",
       "2481     5981  0.44\n",
       "\n",
       "[2482 rows x 2 columns]"
      ]
     },
     "execution_count": 417,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.concat([x_test_cust_id,df],axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 419,
   "id": "2f8ee80f-a6ab-4fae-a0ab-7f5c5499135d",
   "metadata": {},
   "outputs": [],
   "source": [
    "final_df=pd.concat([x_test_cust_id,df],axis=1).rename(columns={1:'gender'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 421,
   "id": "f0adfaba-04fa-4f8f-b88b-0243e9c2de90",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>cust_id</th>\n",
       "      <th>gender</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3500</td>\n",
       "      <td>0.50</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3501</td>\n",
       "      <td>0.23</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3502</td>\n",
       "      <td>0.21</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3503</td>\n",
       "      <td>0.42</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3504</td>\n",
       "      <td>0.45</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   cust_id  gender\n",
       "0     3500    0.50\n",
       "1     3501    0.23\n",
       "2     3502    0.21\n",
       "3     3503    0.42\n",
       "4     3504    0.45"
      ]
     },
     "execution_count": 421,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "final_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 423,
   "id": "42a0bb44-6372-4adf-abbc-ea671c48584a",
   "metadata": {},
   "outputs": [],
   "source": [
    "final_df.to_csv(\"000001.csv\",index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 425,
   "id": "3ba639ea-b479-4e28-b2c3-52adf9340197",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      cust_id  gender\n",
      "0        3500    0.50\n",
      "1        3501    0.23\n",
      "2        3502    0.21\n",
      "3        3503    0.42\n",
      "4        3504    0.45\n",
      "...       ...     ...\n",
      "2477     5977    0.63\n",
      "2478     5978    0.64\n",
      "2479     5979    0.58\n",
      "2480     5980    0.42\n",
      "2481     5981    0.44\n",
      "\n",
      "[2482 rows x 2 columns]\n"
     ]
    }
   ],
   "source": [
    "final_df=pd.read_csv(\"000001.csv\")\n",
    "print(final_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "ab332171",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 성별에 대한 확률 predict_proba()함수를 사용"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "id": "f35a394f",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_test_proba=model.predict_proba(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "id": "70b3cac5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      0     1\n",
      "0  0.49  0.51\n",
      "1  0.85  0.15\n",
      "2  0.84  0.16\n",
      "3  0.53  0.47\n",
      "4  0.64  0.36\n"
     ]
    }
   ],
   "source": [
    "print(pd.DataFrame(y_test_proba).head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "id": "e17a4108",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import roc_auc_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "deb4a8a7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9993911230613358\n"
     ]
    }
   ],
   "source": [
    "print(roc_auc_score(y_train,y_train_predicted))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "157a3e58",
   "metadata": {},
   "outputs": [],
   "source": [
    "#8)답안 제출하기\n",
    "# 최종 답안은 남성(1)에 대한 확률임"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "id": "3120e747",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0       0.51\n",
      "1       0.15\n",
      "2       0.16\n",
      "3       0.47\n",
      "4       0.36\n",
      "        ... \n",
      "2477    0.64\n",
      "2478    0.70\n",
      "2479    0.66\n",
      "2480    0.51\n",
      "2481    0.45\n",
      "Name: 1, Length: 2482, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "print(pd.DataFrame(y_test_proba)[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "bf7a96a0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 9) 데이터 프레임 병합 함수, pandas.concat() 함수로 데이터프레임 \n",
    "# pandas.concat() 함수는 기본적으로 시리즈나 데이터프레임과 같은 \n",
    "# 판다스 객체들을 특정 방향(축)으로 이어붙이는 함수\n",
    "# axis=0,행을 기준이며 1이면 열을 기준으로 연결"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "id": "822ce714",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df1 = pd.DataFrame({'name':['A','B','C','D'],\n",
    "                   'age':[18,30,25,42],\n",
    "                   'city':['Seoul','Incheon','Seoul','Busan']}, index=[0,1,2,3])\n",
    "\n",
    "df2 = pd.DataFrame({'name':['B','C','D','E'],\n",
    "                   'age':[30,25,42,11],\n",
    "                   'city':['Incheon','Seoul','Busan','Suwon'],\n",
    "                   'height':[150, 170, 180, 135]}, index=[1,2,3,4])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "id": "4571e82b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>A</td>\n",
       "      <td>18</td>\n",
       "      <td>Seoul</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>30</td>\n",
       "      <td>Incheon</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>25</td>\n",
       "      <td>Seoul</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  name  age     city\n",
       "0    A   18    Seoul\n",
       "1    B   30  Incheon\n",
       "2    C   25    Seoul"
      ]
     },
     "execution_count": 150,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "id": "6450fb20",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>height</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>30</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>150</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>25</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>170</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>D</td>\n",
       "      <td>42</td>\n",
       "      <td>Busan</td>\n",
       "      <td>180</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  name  age     city  height\n",
       "1    B   30  Incheon     150\n",
       "2    C   25    Seoul     170\n",
       "3    D   42    Busan     180"
      ]
     },
     "execution_count": 151,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "id": "80c9d004",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>height</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>A</td>\n",
       "      <td>18</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>30</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>25</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>D</td>\n",
       "      <td>42</td>\n",
       "      <td>Busan</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>30</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>150.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>25</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>170.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>D</td>\n",
       "      <td>42</td>\n",
       "      <td>Busan</td>\n",
       "      <td>180.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>E</td>\n",
       "      <td>11</td>\n",
       "      <td>Suwon</td>\n",
       "      <td>135.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  name  age     city  height\n",
       "0    A   18    Seoul     NaN\n",
       "1    B   30  Incheon     NaN\n",
       "2    C   25    Seoul     NaN\n",
       "3    D   42    Busan     NaN\n",
       "1    B   30  Incheon   150.0\n",
       "2    C   25    Seoul   170.0\n",
       "3    D   42    Busan   180.0\n",
       "4    E   11    Suwon   135.0"
      ]
     },
     "execution_count": 152,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# axis=0은 행을 기준으로, 즉 위아래로 두 데이터프레임을 이어붙이게 된다.axis=0 디폴트\n",
    "# df1 에는 'height' 컬럼이 없으므로 NaN 값이 채워진다.\n",
    "pd.concat([df1,df2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "id": "1fa476fa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>height</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>A</td>\n",
       "      <td>18</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>30</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>25</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>D</td>\n",
       "      <td>42</td>\n",
       "      <td>Busan</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>B</td>\n",
       "      <td>30</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>150.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>C</td>\n",
       "      <td>25</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>170.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>D</td>\n",
       "      <td>42</td>\n",
       "      <td>Busan</td>\n",
       "      <td>180.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>E</td>\n",
       "      <td>11</td>\n",
       "      <td>Suwon</td>\n",
       "      <td>135.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  name  age     city  height\n",
       "0    A   18    Seoul     NaN\n",
       "1    B   30  Incheon     NaN\n",
       "2    C   25    Seoul     NaN\n",
       "3    D   42    Busan     NaN\n",
       "4    B   30  Incheon   150.0\n",
       "5    C   25    Seoul   170.0\n",
       "6    D   42    Busan   180.0\n",
       "7    E   11    Suwon   135.0"
      ]
     },
     "execution_count": 153,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 새로운 인덱스 번호를 부여하고 싶다면 ignore_index=True \n",
    "pd.concat([df1, df2], ignore_index=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "522f3693",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>height</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>A</td>\n",
       "      <td>18.0</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>30.0</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>B</td>\n",
       "      <td>30.0</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>150.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>25.0</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>C</td>\n",
       "      <td>25.0</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>170.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>D</td>\n",
       "      <td>42.0</td>\n",
       "      <td>Busan</td>\n",
       "      <td>D</td>\n",
       "      <td>42.0</td>\n",
       "      <td>Busan</td>\n",
       "      <td>180.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>E</td>\n",
       "      <td>11.0</td>\n",
       "      <td>Suwon</td>\n",
       "      <td>135.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  name   age     city name   age     city  height\n",
       "0    A  18.0    Seoul  NaN   NaN      NaN     NaN\n",
       "1    B  30.0  Incheon    B  30.0  Incheon   150.0\n",
       "2    C  25.0    Seoul    C  25.0    Seoul   170.0\n",
       "3    D  42.0    Busan    D  42.0    Busan   180.0\n",
       "4  NaN   NaN      NaN    E  11.0    Suwon   135.0"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# axis=1 값을 통해 열방향(좌우) 연결\n",
    "# df1의 인덱스는 0,1,2,3이고, df2의 인덱스는 1,2,3,4 이므로 그에 맞게 연결\n",
    "# df1에는 4행이 없고, df2에는 0행이 없으므로 해당 데이터는 NaN 값으로 채워짐\n",
    "pd.concat([df1, df2], axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "id": "549ad69e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>height</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>30</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>B</td>\n",
       "      <td>30</td>\n",
       "      <td>Incheon</td>\n",
       "      <td>150</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>25</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>C</td>\n",
       "      <td>25</td>\n",
       "      <td>Seoul</td>\n",
       "      <td>170</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>D</td>\n",
       "      <td>42</td>\n",
       "      <td>Busan</td>\n",
       "      <td>D</td>\n",
       "      <td>42</td>\n",
       "      <td>Busan</td>\n",
       "      <td>180</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  name  age     city name  age     city  height\n",
       "1    B   30  Incheon    B   30  Incheon     150\n",
       "2    C   25    Seoul    C   25    Seoul     170\n",
       "3    D   42    Busan    D   42    Busan     180"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#  join='inner'로 설정을 하면 교집합에 해당하는 부분만 이어붙이게 된다.\n",
    "pd.concat([df1, df2], axis=1, join='inner')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "id": "eb57c802",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.DataFrame(y_test_proba)[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "id": "53e36db6",
   "metadata": {},
   "outputs": [],
   "source": [
    "final_df=pd.concat([x_test_cust_id,df],axis=1).rename(columns={1:'gender'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "id": "7ac6fbbc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>cust_id</th>\n",
       "      <th>gender</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3500</td>\n",
       "      <td>0.51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3501</td>\n",
       "      <td>0.15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3502</td>\n",
       "      <td>0.16</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3503</td>\n",
       "      <td>0.47</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3504</td>\n",
       "      <td>0.36</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   cust_id  gender\n",
       "0     3500    0.51\n",
       "1     3501    0.15\n",
       "2     3502    0.16\n",
       "3     3503    0.47\n",
       "4     3504    0.36"
      ]
     },
     "execution_count": 156,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "final_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "df9efc91",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 수험번호.csv 파일 제출\n",
    "final_df.to_csv(\"000001.csv\",index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "43abda7b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      cust_id  gender\n",
      "0        3500    0.52\n",
      "1        3501    0.22\n",
      "2        3502    0.14\n",
      "3        3503    0.41\n",
      "4        3504    0.48\n",
      "...       ...     ...\n",
      "2477     5977    0.63\n",
      "2478     5978    0.61\n",
      "2479     5979    0.63\n",
      "2480     5980    0.51\n",
      "2481     5981    0.46\n",
      "\n",
      "[2482 rows x 2 columns]\n"
     ]
    }
   ],
   "source": [
    "# 제출 파일의 재확인 실행하기\n",
    "final_df=pd.read_csv(\"000001.csv\")\n",
    "print(final_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "id": "cd1e4965",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 10)랜덤포레스트 하이퍼파라미터 튜닝\n",
    "# 트리기반의 앙상블 알고리즘의 단점은 하이퍼 파라미터가 많고, 학습시간이 많이 소모됨\n",
    "# 빅데이터 분석기사 실기 실행시간은 1분 미만으로 제한되어 있음\n",
    "# 하이퍼 파라미터를 입력하지 않아도 빅데이터 분석기사 실기 합격에는 문제가 없음\n",
    "# 따라서 아래의 최적 하이퍼 파라미터는 실습 환경에서만 사용할 것을 추천함"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "61bee3c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 랜덤포레스트 사용하는 하이퍼 파라미터\n",
    "# n_estimators : 결정트리의 갯수, 디폴트는 10개, 많이 설정할수록 성능은 향상\n",
    "# max_features : 최대 선택할 특성의 수,max_features 값을 크게 하면 같은 특성을 고려하므로 \n",
    "# tree들이 매우 비슷\n",
    "# Max_depth: 트리의 깊이로, 이 수가 높을 수록 복잡한 트리가 생성\n",
    "# GridSearchCV( )함수를 이용해 랜덤포레스트 하이퍼 파라미터 튜닝을 수행"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "id": "92bbf1ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import GridSearchCV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "60d1fc91",
   "metadata": {},
   "outputs": [],
   "source": [
    "params={\n",
    "    'max_depth':[3,4,5,6],\n",
    "    'min_samples_leaf':[3,4,5,6],\n",
    "    'min_samples_split':[2,4,6]\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "id": "c226b703",
   "metadata": {},
   "outputs": [],
   "source": [
    "rf_clf=RandomForestClassifier(n_estimators=50,random_state=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 161,
   "id": "d282c275",
   "metadata": {},
   "outputs": [],
   "source": [
    "grid_cv=GridSearchCV(rf_clf,param_grid=params,cv=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 162,
   "id": "5a03187f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-6 {color: black;background-color: white;}#sk-container-id-6 pre{padding: 0;}#sk-container-id-6 div.sk-toggleable {background-color: white;}#sk-container-id-6 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-6 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-6 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-6 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-6 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-6 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-6 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-6 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-6 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-6 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-6 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-6 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-6 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-6 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-6 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-6 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-6 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-6 div.sk-item {position: relative;z-index: 1;}#sk-container-id-6 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-6 div.sk-item::before, #sk-container-id-6 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-6 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-6 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-6 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-6 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-6 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-6 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-6 div.sk-label-container {text-align: center;}#sk-container-id-6 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-6 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-6\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=2,\n",
       "             estimator=RandomForestClassifier(n_estimators=50, random_state=0),\n",
       "             param_grid={&#x27;max_depth&#x27;: [3, 4, 5, 6],\n",
       "                         &#x27;min_samples_leaf&#x27;: [3, 4, 5, 6],\n",
       "                         &#x27;min_samples_split&#x27;: [2, 4, 6]})</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-8\" type=\"checkbox\" ><label for=\"sk-estimator-id-8\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=2,\n",
       "             estimator=RandomForestClassifier(n_estimators=50, random_state=0),\n",
       "             param_grid={&#x27;max_depth&#x27;: [3, 4, 5, 6],\n",
       "                         &#x27;min_samples_leaf&#x27;: [3, 4, 5, 6],\n",
       "                         &#x27;min_samples_split&#x27;: [2, 4, 6]})</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-9\" type=\"checkbox\" ><label for=\"sk-estimator-id-9\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier(n_estimators=50, random_state=0)</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-10\" type=\"checkbox\" ><label for=\"sk-estimator-id-10\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier(n_estimators=50, random_state=0)</pre></div></div></div></div></div></div></div></div></div></div>"
      ],
      "text/plain": [
       "GridSearchCV(cv=2,\n",
       "             estimator=RandomForestClassifier(n_estimators=50, random_state=0),\n",
       "             param_grid={'max_depth': [3, 4, 5, 6],\n",
       "                         'min_samples_leaf': [3, 4, 5, 6],\n",
       "                         'min_samples_split': [2, 4, 6]})"
      ]
     },
     "execution_count": 162,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "grid_cv.fit(x_train,y_train.values.ravel())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 163,
   "id": "1b55098e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'max_depth': 5, 'min_samples_leaf': 4, 'min_samples_split': 2}\n"
     ]
    }
   ],
   "source": [
    "print(grid_cv.best_params_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "id": "0b62f961",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 11) knn 알고리즘 수행"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 164,
   "id": "c6226c8d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 165,
   "id": "4e01dd3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 'uniform': 거리에 가중치 부여하지 않음\n",
    "#  n_neighbors=5 (디폴트), 작은 수면 과대적합 (1이면 과대적합)\n",
    "knn = KNeighborsClassifier(n_neighbors = 5,metric='euclidean')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 166,
   "id": "e11262cf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-7 {color: black;background-color: white;}#sk-container-id-7 pre{padding: 0;}#sk-container-id-7 div.sk-toggleable {background-color: white;}#sk-container-id-7 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-7 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-7 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-7 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-7 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-7 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-7 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-7 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-7 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-7 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-7 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-7 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-7 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-7 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-7 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-7 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-7 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-7 div.sk-item {position: relative;z-index: 1;}#sk-container-id-7 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-7 div.sk-item::before, #sk-container-id-7 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-7 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-7 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-7 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-7 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-7 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-7 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-7 div.sk-label-container {text-align: center;}#sk-container-id-7 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-7 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-7\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>KNeighborsClassifier(metric=&#x27;euclidean&#x27;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-11\" type=\"checkbox\" checked><label for=\"sk-estimator-id-11\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">KNeighborsClassifier</label><div class=\"sk-toggleable__content\"><pre>KNeighborsClassifier(metric=&#x27;euclidean&#x27;)</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "KNeighborsClassifier(metric='euclidean')"
      ]
     },
     "execution_count": 166,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn.fit(x_train,y_train.values.ravel())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 167,
   "id": "5c92b1cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_test_predicted=knn.predict_proba(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 168,
   "id": "e215bfb2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0. , 1. ],\n",
       "       [1. , 0. ],\n",
       "       [1. , 0. ],\n",
       "       ...,\n",
       "       [0.6, 0.4],\n",
       "       [0.6, 0.4],\n",
       "       [0.2, 0.8]])"
      ]
     },
     "execution_count": 168,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_test_predicted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 169,
   "id": "810ee263",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.DataFrame(y_test_proba)[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 170,
   "id": "68072541",
   "metadata": {},
   "outputs": [],
   "source": [
    "final_df=pd.concat([x_test_cust_id,df],axis=1).rename(columns={1:'gender'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 171,
   "id": "a9d03318",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>cust_id</th>\n",
       "      <th>gender</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3500</td>\n",
       "      <td>0.51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3501</td>\n",
       "      <td>0.15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3502</td>\n",
       "      <td>0.16</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3503</td>\n",
       "      <td>0.47</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3504</td>\n",
       "      <td>0.36</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   cust_id  gender\n",
       "0     3500    0.51\n",
       "1     3501    0.15\n",
       "2     3502    0.16\n",
       "3     3503    0.47\n",
       "4     3504    0.36"
      ]
     },
     "execution_count": 171,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "final_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 172,
   "id": "e9b46aef",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 02 기출문제 (분류모형 구축),multiclass \n",
    "# 보험관련 학습용 데이터 Insurance_train_10.csv 데이터를 이용하여 “Segmentation”\n",
    "# 예측모형을 개발하려고 한다. \n",
    "# 자동차 회사는 기존 시장에서 영업팀은 모든 고객을 4개의 “\n",
    "# Segmentation” 분류하고 새로운 시장에서 동일한 전략을 사용할 계획이다.\n",
    "# 평가는 제출된 csv 파일의 macro-F1 평가지표에 따라 시행한다.\n",
    "# to_csv('수험번호.csv',index=False)으로 제출"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 685,
   "id": "8ed3a824",
   "metadata": {},
   "outputs": [],
   "source": [
    "#1) 데이터 불러오기 \n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
    "from sklearn.metrics import accuracy_score, f1_score, make_scorer\n",
    "from sklearn.model_selection import cross_val_score, KFold\n",
    "train10=pd.read_csv(\"c:/data/Insurance_train_10.csv\")\n",
    "test10=pd.read_csv(\"c:/data/Insurance_test_10.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 687,
   "id": "4b11ca3b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Gender Ever_Married  Age Graduated  Profession  Work_Experience  \\\n",
      "0    Male           No   22        No  Healthcare                1   \n",
      "1  Female          Yes   67       Yes    Engineer                1   \n",
      "2    Male          Yes   67       Yes      Lawyer                0   \n",
      "\n",
      "  Spending_Score  Family_Size  Segmentation  \n",
      "0            Low            4             4  \n",
      "1            Low            1             2  \n",
      "2           High            2             2  \n",
      "(6969, 9)\n"
     ]
    }
   ],
   "source": [
    "print(train10.head(3))\n",
    "print(train10.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 689,
   "id": "af91a4be",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Gender Ever_Married  Age Graduated  Profession  Work_Experience  \\\n",
      "0  Female          Yes   36       Yes    Engineer                0   \n",
      "1    Male          Yes   37       Yes  Healthcare                8   \n",
      "2  Female          Yes   69        No         NaN                0   \n",
      "\n",
      "  Spending_Score  Family_Size  \n",
      "0            Low            1  \n",
      "1        Average            4  \n",
      "2            Low            1  \n",
      "(2267, 8)\n"
     ]
    }
   ],
   "source": [
    "print(test10.head(3))\n",
    "print(test10.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 691,
   "id": "6b67b6ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 6969 entries, 0 to 6968\n",
      "Data columns (total 9 columns):\n",
      " #   Column           Non-Null Count  Dtype \n",
      "---  ------           --------------  ----- \n",
      " 0   Gender           6969 non-null   object\n",
      " 1   Ever_Married     6862 non-null   object\n",
      " 2   Age              6969 non-null   int64 \n",
      " 3   Graduated        6909 non-null   object\n",
      " 4   Profession       6877 non-null   object\n",
      " 5   Work_Experience  6969 non-null   int64 \n",
      " 6   Spending_Score   6969 non-null   object\n",
      " 7   Family_Size      6969 non-null   int64 \n",
      " 8   Segmentation     6969 non-null   int64 \n",
      "dtypes: int64(4), object(5)\n",
      "memory usage: 490.1+ KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(train10.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 693,
   "id": "ab2f517f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#2)결측치 처리"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 695,
   "id": "bcf18238",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gender               0\n",
      "Ever_Married       107\n",
      "Age                  0\n",
      "Graduated           60\n",
      "Profession          92\n",
      "Work_Experience      0\n",
      "Spending_Score       0\n",
      "Family_Size          0\n",
      "Segmentation         0\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(train10.isna().sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 697,
   "id": "d57461ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "train10=train10.dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 699,
   "id": "15221321",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gender             0\n",
      "Ever_Married       0\n",
      "Age                0\n",
      "Graduated          0\n",
      "Profession         0\n",
      "Work_Experience    0\n",
      "Spending_Score     0\n",
      "Family_Size        0\n",
      "Segmentation       0\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(train10.isna().sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 701,
   "id": "7f5affda",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gender              0\n",
      "Ever_Married       42\n",
      "Age                 0\n",
      "Graduated          19\n",
      "Profession         30\n",
      "Work_Experience     0\n",
      "Spending_Score      0\n",
      "Family_Size         0\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(test10.isna().sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 703,
   "id": "54e236d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "test10=test10.dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 705,
   "id": "29933453",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gender             0\n",
      "Ever_Married       0\n",
      "Age                0\n",
      "Graduated          0\n",
      "Profession         0\n",
      "Work_Experience    0\n",
      "Spending_Score     0\n",
      "Family_Size        0\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(test10.isna().sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 711,
   "id": "2f90e19f-0657-4479-ab40-73aba12d98f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "target_col = 'Segmentation'\n",
    "x_train10 = train10.drop(columns=[target_col])\n",
    "y_train10 = train10[target_col]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 713,
   "id": "5a929785",
   "metadata": {},
   "outputs": [],
   "source": [
    "#3) 인코딩 변환(Encoding transformation)\n",
    "categorical_cols = ['Gender', 'Ever_Married', 'Graduated', 'Profession', 'Spending_Score']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 715,
   "id": "6ac8ee6c-31b4-4c74-84b3-c321bc7c5bcd",
   "metadata": {},
   "outputs": [],
   "source": [
    "for col in categorical_cols:\n",
    "    encoder = LabelEncoder()\n",
    "    x_train10[col] = encoder.fit_transform(x_train10[col])\n",
    "    test10[col] = encoder.transform(test10[col])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cf1df03-d401-4ed8-adfa-eb8046dc10a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4) 표준화(Standardization)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 717,
   "id": "6fa1eb6e-18aa-41d0-9a0b-bb31bf3f1e3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler = StandardScaler()\n",
    "x_train10_scaled = pd.DataFrame(scaler.fit_transform(x_train10), columns=x_train10.columns)\n",
    "test10_scaled = pd.DataFrame(scaler.transform(test10), columns=x_train10.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 719,
   "id": "57bc83c0-f2df-45cd-992f-de35de2632d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5) 모델 학습 및 예측\n",
    "model = RandomForestClassifier(random_state=42)\n",
    "model.fit(x_train10_scaled, y_train10)\n",
    "y_train_predicted = model.predict(x_train10_scaled)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 721,
   "id": "70d856b3-e575-4f24-9e58-ae4f4cc12dec",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9277715317205174\n"
     ]
    }
   ],
   "source": [
    "# 6) 모델 평가\n",
    "print(f1_score(y_train10,y_train_predicted, average='macro'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 723,
   "id": "b926984f-cc93-40e8-85cc-8087ff6fd588",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9285501637392081\n"
     ]
    }
   ],
   "source": [
    "print(f1_score(y_train10,y_train_predicted, average='micro'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 725,
   "id": "b98cd958-515a-4858-aae9-6ed1330035c8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1497,   55,   52,   24],\n",
       "       [  47, 1414,   97,   25],\n",
       "       [  24,   63, 1617,   31],\n",
       "       [  26,   16,   20, 1710]], dtype=int64)"
      ]
     },
     "execution_count": 725,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "confusion_matrix(y_train10,y_train_predicted)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 729,
   "id": "aaa930d4-2cac-4787-9cd1-70e0c6ee3444",
   "metadata": {},
   "outputs": [],
   "source": [
    "#7) 답안 제출\n",
    "y_test=model.predict(test10_scaled)\n",
    "df=pd.DataFrame(y_test)\n",
    "final_df=df.rename(columns={0:'Segmentation_pred'})\n",
    "final_df.to_csv(\"000002.csv\",index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 731,
   "id": "553cd981-951a-491d-8e51-8ae6795acad9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Segmentation_pred\n",
      "0                  2\n",
      "1                  3\n",
      "2                  3\n"
     ]
    }
   ],
   "source": [
    "print(final_df.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccaf89fc-5ae5-461b-bdeb-ba8a62e4c0a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 03∙워싱턴 D.C 의 Capital Bikeshare 프로그램에서 자전거 대여 수요를 예측하기 \n",
    "# 위한 프로젝트이다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 410,
   "id": "999a399e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# kaggle 자전거 수요 예측 경연 데이터 셋 \n",
    "# datetime: hourly data + timestamp\n",
    "# season: 1(봄),2(여름),3(가을),4(겨울)\n",
    "# holiday:1,0(휴일 아닌날)\n",
    "# workingday: 1(주중),0(주말및 휴일)\n",
    "# weather: 1(맑음),2(안개,흐림),3(가벼운 비),4(심한 비)\n",
    "# temp: 온도\n",
    "# atemp:체감온도\n",
    "# humidity:상대습도\n",
    "# windspeed:풍속\n",
    "# casual:사전에 등록된 사용자가 대여한 횟수\n",
    "# registered:사전에 등록된 사용자가 대여한 횟수\n",
    "# count: 대여횟수"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 735,
   "id": "0180ed66",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "           datetime  season  holiday  workingday  weather  temp   atemp  \\\n",
      "0  2011-01-01 00:00       1        0           0        1  9.84  14.395   \n",
      "1  2011-01-01 01:00       1        0           0        1  9.02  13.635   \n",
      "2  2011-01-01 02:00       1        0           0        1  9.02  13.635   \n",
      "\n",
      "   humidity  windspeed  casual  registered  count  \n",
      "0        81        0.0       3          13     16  \n",
      "1        80        0.0       8          32     40  \n",
      "2        80        0.0       5          27     32  \n"
     ]
    }
   ],
   "source": [
    "# 1) 데이터 탐색\n",
    "import pandas as pd\n",
    "bike_df=pd.read_csv(\"c:/data/bike_train.csv\")\n",
    "print(bike_df.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 737,
   "id": "f3f4fa6d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(10886, 12)\n"
     ]
    }
   ],
   "source": [
    "# 10886개 행과 12개 컬럼\n",
    "print(bike_df.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 739,
   "id": "e3763933",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 10886 entries, 0 to 10885\n",
      "Data columns (total 12 columns):\n",
      " #   Column      Non-Null Count  Dtype  \n",
      "---  ------      --------------  -----  \n",
      " 0   datetime    10886 non-null  object \n",
      " 1   season      10886 non-null  int64  \n",
      " 2   holiday     10886 non-null  int64  \n",
      " 3   workingday  10886 non-null  int64  \n",
      " 4   weather     10886 non-null  int64  \n",
      " 5   temp        10886 non-null  float64\n",
      " 6   atemp       10886 non-null  float64\n",
      " 7   humidity    10886 non-null  int64  \n",
      " 8   windspeed   10886 non-null  float64\n",
      " 9   casual      10886 non-null  int64  \n",
      " 10  registered  10886 non-null  int64  \n",
      " 11  count       10886 non-null  int64  \n",
      "dtypes: float64(3), int64(8), object(1)\n",
      "memory usage: 1020.7+ KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(bike_df.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 741,
   "id": "0433582b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 문자열을 datetime type 변경\n",
    "import datetime as dt\n",
    "bike_df['datetime']=pd.to_datetime(bike_df['datetime'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 743,
   "id": "f078881e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 10886 entries, 0 to 10885\n",
      "Data columns (total 12 columns):\n",
      " #   Column      Non-Null Count  Dtype         \n",
      "---  ------      --------------  -----         \n",
      " 0   datetime    10886 non-null  datetime64[ns]\n",
      " 1   season      10886 non-null  int64         \n",
      " 2   holiday     10886 non-null  int64         \n",
      " 3   workingday  10886 non-null  int64         \n",
      " 4   weather     10886 non-null  int64         \n",
      " 5   temp        10886 non-null  float64       \n",
      " 6   atemp       10886 non-null  float64       \n",
      " 7   humidity    10886 non-null  int64         \n",
      " 8   windspeed   10886 non-null  float64       \n",
      " 9   casual      10886 non-null  int64         \n",
      " 10  registered  10886 non-null  int64         \n",
      " 11  count       10886 non-null  int64         \n",
      "dtypes: datetime64[ns](1), float64(3), int64(8)\n",
      "memory usage: 1020.7 KB\n"
     ]
    }
   ],
   "source": [
    "bike_df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 745,
   "id": "dc014c89",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>datetime</th>\n",
       "      <th>season</th>\n",
       "      <th>holiday</th>\n",
       "      <th>workingday</th>\n",
       "      <th>weather</th>\n",
       "      <th>temp</th>\n",
       "      <th>atemp</th>\n",
       "      <th>humidity</th>\n",
       "      <th>windspeed</th>\n",
       "      <th>casual</th>\n",
       "      <th>registered</th>\n",
       "      <th>count</th>\n",
       "      <th>year</th>\n",
       "      <th>month</th>\n",
       "      <th>day</th>\n",
       "      <th>hour</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2011-01-01 00:00:00</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>9.84</td>\n",
       "      <td>14.395</td>\n",
       "      <td>81</td>\n",
       "      <td>0.0</td>\n",
       "      <td>3</td>\n",
       "      <td>13</td>\n",
       "      <td>16</td>\n",
       "      <td>2011</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2011-01-01 01:00:00</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>9.02</td>\n",
       "      <td>13.635</td>\n",
       "      <td>80</td>\n",
       "      <td>0.0</td>\n",
       "      <td>8</td>\n",
       "      <td>32</td>\n",
       "      <td>40</td>\n",
       "      <td>2011</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2011-01-01 02:00:00</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>9.02</td>\n",
       "      <td>13.635</td>\n",
       "      <td>80</td>\n",
       "      <td>0.0</td>\n",
       "      <td>5</td>\n",
       "      <td>27</td>\n",
       "      <td>32</td>\n",
       "      <td>2011</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             datetime  season  holiday  workingday  weather  temp   atemp  \\\n",
       "0 2011-01-01 00:00:00       1        0           0        1  9.84  14.395   \n",
       "1 2011-01-01 01:00:00       1        0           0        1  9.02  13.635   \n",
       "2 2011-01-01 02:00:00       1        0           0        1  9.02  13.635   \n",
       "\n",
       "   humidity  windspeed  casual  registered  count  year  month  day  hour  \n",
       "0        81        0.0       3          13     16  2011      1    1     0  \n",
       "1        80        0.0       8          32     40  2011      1    1     1  \n",
       "2        80        0.0       5          27     32  2011      1    1     2  "
      ]
     },
     "execution_count": 745,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 'datetime' 연도,월,요일,시간등으로 분리\n",
    "bike_df['year']=bike_df['datetime'].dt.year\n",
    "bike_df['month']=bike_df['datetime'].dt.month\n",
    "bike_df['day']=bike_df['datetime'].dt.day\n",
    "bike_df['hour']=bike_df['datetime'].dt.hour\n",
    "bike_df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 747,
   "id": "a205274c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#2)불필요한 컬럼 삭제\n",
    "# casual+registered=count 의미\n",
    "# datetime,casual,registered 삭제\n",
    "drop_columns=['datetime','casual','registered']\n",
    "bike_df_drop=bike_df.drop(drop_columns,axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 749,
   "id": "505bc7f7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   season  holiday  workingday  weather  temp   atemp  humidity  windspeed  \\\n",
      "0       1        0           0        1  9.84  14.395        81        0.0   \n",
      "1       1        0           0        1  9.02  13.635        80        0.0   \n",
      "2       1        0           0        1  9.02  13.635        80        0.0   \n",
      "\n",
      "   count  year  month  day  hour  \n",
      "0     16  2011      1    1     0  \n",
      "1     40  2011      1    1     1  \n",
      "2     32  2011      1    1     2  \n"
     ]
    }
   ],
   "source": [
    "print(bike_df_drop.head(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 751,
   "id": "f06b89d7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 10886 entries, 0 to 10885\n",
      "Data columns (total 13 columns):\n",
      " #   Column      Non-Null Count  Dtype  \n",
      "---  ------      --------------  -----  \n",
      " 0   season      10886 non-null  int64  \n",
      " 1   holiday     10886 non-null  int64  \n",
      " 2   workingday  10886 non-null  int64  \n",
      " 3   weather     10886 non-null  int64  \n",
      " 4   temp        10886 non-null  float64\n",
      " 5   atemp       10886 non-null  float64\n",
      " 6   humidity    10886 non-null  int64  \n",
      " 7   windspeed   10886 non-null  float64\n",
      " 8   count       10886 non-null  int64  \n",
      " 9   year        10886 non-null  int32  \n",
      " 10  month       10886 non-null  int32  \n",
      " 11  day         10886 non-null  int32  \n",
      " 12  hour        10886 non-null  int32  \n",
      "dtypes: float64(3), int32(4), int64(6)\n",
      "memory usage: 935.6 KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(bike_df_drop.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 753,
   "id": "74d6ee08",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "season        0\n",
       "holiday       0\n",
       "workingday    0\n",
       "weather       0\n",
       "temp          0\n",
       "atemp         0\n",
       "humidity      0\n",
       "windspeed     0\n",
       "count         0\n",
       "year          0\n",
       "month         0\n",
       "day           0\n",
       "hour          0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 753,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#3) 결측치 확인\n",
    "bike_df_drop.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 755,
   "id": "3e2f1392",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(10886,)"
      ]
     },
     "execution_count": 755,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#4) 변수 분할\n",
    "# 종속변수 분할\n",
    "Y=bike_df_drop['count']\n",
    "Y.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 757,
   "id": "8601d29d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(10886, 12)"
      ]
     },
     "execution_count": 757,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X=bike_df_drop.drop(['count'],axis=1)\n",
    "X.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 759,
   "id": "d5cf3812",
   "metadata": {},
   "outputs": [],
   "source": [
    "#5)모델 학습 및 평가"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 761,
   "id": "07e78fb4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LinearRegression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 763,
   "id": "937244f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.3,\n",
    "                                              random_state=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 765,
   "id": "a388b1b2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(7620, 12)"
      ]
     },
     "execution_count": 765,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_train.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 767,
   "id": "b1b1a909",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3266, 12)"
      ]
     },
     "execution_count": 767,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 769,
   "id": "c2577fe5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(7620,)"
      ]
     },
     "execution_count": 769,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_train.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 771,
   "id": "69dd9271",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3266,)"
      ]
     },
     "execution_count": 771,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 773,
   "id": "3cdac321",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 선형회귀모형 \n",
    "reg=LinearRegression()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 775,
   "id": "c6e6ef2e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-6 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-6 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-6 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-6 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-6 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-6 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-6 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-6 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-6 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-6 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-6 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-6 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-6 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-6 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-6\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>LinearRegression()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-6\" type=\"checkbox\" checked><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;LinearRegression<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.linear_model.LinearRegression.html\">?<span>Documentation for LinearRegression</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>LinearRegression()</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "LinearRegression()"
      ]
     },
     "execution_count": 775,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "reg.fit(x_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 777,
   "id": "255be543",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred=reg.predict(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 779,
   "id": "e4ba7496",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[320.78637463 251.1873687  241.70971289 ... 315.23151252 181.92737435\n",
      " 166.29021343]\n"
     ]
    }
   ],
   "source": [
    "print(y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 781,
   "id": "046cad92",
   "metadata": {},
   "outputs": [],
   "source": [
    "#6) 모형평가"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 783,
   "id": "f43cd262",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import mean_squared_error,mean_absolute_error,mean_squared_error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 785,
   "id": "dbb8a17f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "105.92444835101183\n"
     ]
    }
   ],
   "source": [
    "# MAE\n",
    "print(mean_absolute_error(y_test,y_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 787,
   "id": "e90ff505",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "140.89958867165572\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\emhu8\\anaconda3\\Lib\\site-packages\\sklearn\\metrics\\_regression.py:492: FutureWarning: 'squared' is deprecated in version 1.4 and will be removed in 1.6. To calculate the root mean squared error, use the function'root_mean_squared_error'.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "# RMSE, 디폴트 squared=True 일때 MSE\n",
    "print(mean_squared_error(y_test,y_pred,squared=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 789,
   "id": "72826bc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예측값(y_pred),실제값(y_test) 차이가 큰 순서대로 정렬"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 791,
   "id": "2bbd8f4c",
   "metadata": {},
   "outputs": [],
   "source": [
    "result_df=pd.DataFrame(y_test.values,columns=['real_count'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 793,
   "id": "f4148d0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "result_df['predict_count']=np.round(y_pred)# 디폴트 1이 자릿수"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 795,
   "id": "ad9df365",
   "metadata": {},
   "outputs": [],
   "source": [
    "result_df['diff']=np.abs(result_df['real_count']-result_df['predict_count'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 797,
   "id": "077d149f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      real_count  predict_count   diff\n",
      "1618         890          322.0  568.0\n",
      "3151         798          241.0  557.0\n",
      "966          884          327.0  557.0\n",
      "412          745          194.0  551.0\n",
      "2817         856          310.0  546.0\n",
      "2277         813          267.0  546.0\n",
      "2314         766          222.0  544.0\n",
      "454          721          177.0  544.0\n",
      "1003         713          171.0  542.0\n",
      "2394         684          142.0  542.0\n"
     ]
    }
   ],
   "source": [
    "# count 분포가 정규분포가 아닐 가능성이 높음\n",
    "print(result_df.sort_values('diff',ascending=False).head(10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 237,
   "id": "d2fbcaaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "#7)인코딩 추가후에 모형 평가"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 238,
   "id": "a2b869c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 숫자형 카테고리 값을 선형 회귀에 사용할 경우 회귀 계수를 연산할 때 숫자형 값에 영향을\n",
    "# 받는 경우가 발생할 수 있음\n",
    "# 회귀모형에서는 원-핫 인코딩을 적용해 변환함"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 799,
   "id": "f47de150",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 'year','month','day','hour' 변수들을 One Hot Encoding\n",
    "bike_df_drop_one=pd.get_dummies(bike_df_drop,columns=['year','month','day','hour','holiday',\n",
    "                                                     'workingday','season','weather'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 801,
   "id": "8e7e3ffc",
   "metadata": {},
   "outputs": [],
   "source": [
    "Y=bike_df_drop_one['count']\n",
    "X=bike_df_drop_one.drop(['count'],axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 803,
   "id": "5dca4c0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LinearRegression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 805,
   "id": "f43f8f18",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.3,\n",
    "                                              random_state=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 807,
   "id": "800b5156",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "reg=LinearRegression()\n",
    "reg.fit(x_train,y_train)\n",
    "y_pred=reg.predict(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 809,
   "id": "3ddde171",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "74.88937215343692\n"
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import mean_squared_error,mean_absolute_error,mean_squared_error\n",
    "# MAE\n",
    "print(mean_absolute_error(y_test,y_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 811,
   "id": "8a45cbfa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "101.62070644935623\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\emhu8\\anaconda3\\Lib\\site-packages\\sklearn\\metrics\\_regression.py:492: FutureWarning: 'squared' is deprecated in version 1.4 and will be removed in 1.6. To calculate the root mean squared error, use the function'root_mean_squared_error'.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "# RMSE\n",
    "print(mean_squared_error(y_test,y_pred,squared=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 452,
   "id": "9ebeb7cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 회귀모형에서 원-핫 인코딩 변환 후에 예측 성능이 향상됨"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 244,
   "id": "7e046c2c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#8) 랜덤포레스트 모형"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 813,
   "id": "0c888944",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestRegressor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 815,
   "id": "47f27f20",
   "metadata": {},
   "outputs": [],
   "source": [
    "rf_reg=RandomForestRegressor(n_estimators=500)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 817,
   "id": "6a474f8e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-7 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-7 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-7 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-7 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-7 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-7 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-7 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-7 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-7 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-7 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-7 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-7 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-7 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-7 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-7\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestRegressor(n_estimators=500)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-7\" type=\"checkbox\" checked><label for=\"sk-estimator-id-7\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;RandomForestRegressor<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.ensemble.RandomForestRegressor.html\">?<span>Documentation for RandomForestRegressor</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestRegressor(n_estimators=500)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestRegressor(n_estimators=500)"
      ]
     },
     "execution_count": 817,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rf_reg.fit(x_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 818,
   "id": "790fb410",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred=rf_reg.predict(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 819,
   "id": "069911e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "34.921418860992034\n"
     ]
    }
   ],
   "source": [
    "# MAE\n",
    "print(mean_absolute_error(y_test,y_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 820,
   "id": "2caeacae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "55.746122917116516\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\emhu8\\anaconda3\\Lib\\site-packages\\sklearn\\metrics\\_regression.py:492: FutureWarning: 'squared' is deprecated in version 1.4 and will be removed in 1.6. To calculate the root mean squared error, use the function'root_mean_squared_error'.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "# RMSE\n",
    "print(mean_squared_error(y_test,y_pred,squared=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 251,
   "id": "f3f329d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 선형회귀 모델보다 회귀 예측 성능이 더 향상됨\n",
    "# 회귀트리가 선형회귀보다 우수한 성능을 의미하지는 않음\n",
    "# 데이터의 유형에 따라 회귀 예측 성능을 달라질 수 있음"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 825,
   "id": "f0bbc488-b712-4865-a672-983ca19075fb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 기출문제\n",
    "# 04. 중고차 가격(price)에 대한 학습용 데이터(x_train,y_train)를 이용하여 중고차 가격 예측 모형\n",
    "# 구축을 하고 이를 평가용 데이터(x_test)에 적용하여 예측값을 csv 파일로 제출하시오.(제출한 \n",
    "# 모델의 성능은 RMSE 평가지표에 따라 채점"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 827,
   "id": "c6b3fd33-0694-4dbb-b658-fb0c22d939d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1)데이터 불러오기\n",
    "import pandas as pd\n",
    "x_train=pd.read_csv(\"c:/data/6_x_train.csv\")\n",
    "x_test=pd.read_csv(\"c:/data/6_x_test.csv\")\n",
    "y_train=pd.read_csv(\"c:/data/6_y_train.csv\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 829,
   "id": "7a241cd2-9c5a-48a2-b840-6423f677b4a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>carID</th>\n",
       "      <th>brand</th>\n",
       "      <th>model</th>\n",
       "      <th>year</th>\n",
       "      <th>transmission</th>\n",
       "      <th>mileage</th>\n",
       "      <th>fuelType</th>\n",
       "      <th>tax</th>\n",
       "      <th>mpg</th>\n",
       "      <th>engineSize</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>13207</td>\n",
       "      <td>hyundi</td>\n",
       "      <td>Santa Fe</td>\n",
       "      <td>2019</td>\n",
       "      <td>Semi-Auto</td>\n",
       "      <td>4223</td>\n",
       "      <td>Diesel</td>\n",
       "      <td>145</td>\n",
       "      <td>39.8</td>\n",
       "      <td>2.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>17314</td>\n",
       "      <td>vauxhall</td>\n",
       "      <td>GTC</td>\n",
       "      <td>2015</td>\n",
       "      <td>Manual</td>\n",
       "      <td>47870</td>\n",
       "      <td>Diesel</td>\n",
       "      <td>125</td>\n",
       "      <td>60.1</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12342</td>\n",
       "      <td>audi</td>\n",
       "      <td>RS4</td>\n",
       "      <td>2019</td>\n",
       "      <td>Automatic</td>\n",
       "      <td>5151</td>\n",
       "      <td>Petrol</td>\n",
       "      <td>145</td>\n",
       "      <td>29.1</td>\n",
       "      <td>2.9</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   carID     brand      model  year transmission  mileage fuelType  tax   mpg  \\\n",
       "0  13207    hyundi   Santa Fe  2019    Semi-Auto     4223   Diesel  145  39.8   \n",
       "1  17314  vauxhall        GTC  2015       Manual    47870   Diesel  125  60.1   \n",
       "2  12342      audi        RS4  2019    Automatic     5151   Petrol  145  29.1   \n",
       "\n",
       "   engineSize  \n",
       "0         2.2  \n",
       "1         2.0  \n",
       "2         2.9  "
      ]
     },
     "execution_count": 829,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2)데이터 탐색\n",
    "x_train.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 831,
   "id": "11274c73-a032-4d05-b901-d21562dc502f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>carID</th>\n",
       "      <th>brand</th>\n",
       "      <th>model</th>\n",
       "      <th>year</th>\n",
       "      <th>transmission</th>\n",
       "      <th>mileage</th>\n",
       "      <th>fuelType</th>\n",
       "      <th>tax</th>\n",
       "      <th>mpg</th>\n",
       "      <th>engineSize</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>12000</td>\n",
       "      <td>merc</td>\n",
       "      <td>GLS Class</td>\n",
       "      <td>2017</td>\n",
       "      <td>Automatic</td>\n",
       "      <td>12046</td>\n",
       "      <td>Diesel</td>\n",
       "      <td>150</td>\n",
       "      <td>37.2</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>12001</td>\n",
       "      <td>vw</td>\n",
       "      <td>Amarok</td>\n",
       "      <td>2017</td>\n",
       "      <td>Automatic</td>\n",
       "      <td>37683</td>\n",
       "      <td>Diesel</td>\n",
       "      <td>260</td>\n",
       "      <td>36.2</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12004</td>\n",
       "      <td>merc</td>\n",
       "      <td>GLS Class</td>\n",
       "      <td>2019</td>\n",
       "      <td>Automatic</td>\n",
       "      <td>10000</td>\n",
       "      <td>Diesel</td>\n",
       "      <td>145</td>\n",
       "      <td>34.0</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   carID brand       model  year transmission  mileage fuelType  tax   mpg  \\\n",
       "0  12000  merc   GLS Class  2017    Automatic    12046   Diesel  150  37.2   \n",
       "1  12001    vw      Amarok  2017    Automatic    37683   Diesel  260  36.2   \n",
       "2  12004  merc   GLS Class  2019    Automatic    10000   Diesel  145  34.0   \n",
       "\n",
       "   engineSize  \n",
       "0         3.0  \n",
       "1         3.0  \n",
       "2         3.0  "
      ]
     },
     "execution_count": 831,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_test.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 833,
   "id": "9c8e3d9c-c053-4c22-8e96-efadcda4ea06",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>carID</th>\n",
       "      <th>price</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>13207</td>\n",
       "      <td>31995</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>17314</td>\n",
       "      <td>7700</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12342</td>\n",
       "      <td>58990</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   carID  price\n",
       "0  13207  31995\n",
       "1  17314   7700\n",
       "2  12342  58990"
      ]
     },
     "execution_count": 833,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_train.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 835,
   "id": "01f9c375-ab75-42a4-883d-9ec2d9c574e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 4960 entries, 0 to 4959\n",
      "Data columns (total 10 columns):\n",
      " #   Column        Non-Null Count  Dtype  \n",
      "---  ------        --------------  -----  \n",
      " 0   carID         4960 non-null   int64  \n",
      " 1   brand         4960 non-null   object \n",
      " 2   model         4960 non-null   object \n",
      " 3   year          4960 non-null   int64  \n",
      " 4   transmission  4960 non-null   object \n",
      " 5   mileage       4960 non-null   int64  \n",
      " 6   fuelType      4960 non-null   object \n",
      " 7   tax           4960 non-null   int64  \n",
      " 8   mpg           4960 non-null   float64\n",
      " 9   engineSize    4960 non-null   float64\n",
      "dtypes: float64(2), int64(4), object(4)\n",
      "memory usage: 387.6+ KB\n"
     ]
    }
   ],
   "source": [
    "x_train.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 837,
   "id": "a54bf11d-9565-4953-bbac-8e111ce2c1f5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 2672 entries, 0 to 2671\n",
      "Data columns (total 10 columns):\n",
      " #   Column        Non-Null Count  Dtype  \n",
      "---  ------        --------------  -----  \n",
      " 0   carID         2672 non-null   int64  \n",
      " 1   brand         2672 non-null   object \n",
      " 2   model         2672 non-null   object \n",
      " 3   year          2672 non-null   int64  \n",
      " 4   transmission  2672 non-null   object \n",
      " 5   mileage       2672 non-null   int64  \n",
      " 6   fuelType      2672 non-null   object \n",
      " 7   tax           2672 non-null   int64  \n",
      " 8   mpg           2672 non-null   float64\n",
      " 9   engineSize    2672 non-null   float64\n",
      "dtypes: float64(2), int64(4), object(4)\n",
      "memory usage: 208.9+ KB\n"
     ]
    }
   ],
   "source": [
    " x_test.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 839,
   "id": "4b1ec55b-be33-4cf9-bd9f-d32a29080635",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "carID           0\n",
       "brand           0\n",
       "model           0\n",
       "year            0\n",
       "transmission    0\n",
       "mileage         0\n",
       "fuelType        0\n",
       "tax             0\n",
       "mpg             0\n",
       "engineSize      0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 839,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 3)결측치 확인\n",
    "x_train.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 841,
   "id": "3b948c56-9b1f-4b67-89bf-53cee4f5606c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "carID           0\n",
       "brand           0\n",
       "model           0\n",
       "year            0\n",
       "transmission    0\n",
       "mileage         0\n",
       "fuelType        0\n",
       "tax             0\n",
       "mpg             0\n",
       "engineSize      0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 841,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_test.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 843,
   "id": "1fcf2eec-11bf-421a-ae66-f03ac6984971",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "carID    0\n",
       "price    0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 843,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_train.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 845,
   "id": "c8f191cf-566b-4ed9-a786-01718bdc4816",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   carID  year  mileage  tax   mpg  engineSize  brand_audi  brand_bmw  \\\n",
      "0  13207  2019     4223  145  39.8         2.2       False      False   \n",
      "1  17314  2015    47870  125  60.1         2.0       False      False   \n",
      "2  12342  2019     5151  145  29.1         2.9        True      False   \n",
      "3  13426  2016    20423   30  57.6         2.0       False      False   \n",
      "4  16004  2020     3569  145  47.1         1.0       False      False   \n",
      "\n",
      "   brand_ford  brand_hyundi  ...  brand_vw  transmission_Automatic  \\\n",
      "0       False          True  ...     False                   False   \n",
      "1       False         False  ...     False                   False   \n",
      "2       False         False  ...     False                    True   \n",
      "3       False         False  ...      True                    True   \n",
      "4       False         False  ...     False                   False   \n",
      "\n",
      "   transmission_Manual  transmission_Other  transmission_Semi-Auto  \\\n",
      "0                False               False                    True   \n",
      "1                 True               False                   False   \n",
      "2                False               False                   False   \n",
      "3                False               False                   False   \n",
      "4                False               False                    True   \n",
      "\n",
      "   fuelType_Diesel  fuelType_Electric  fuelType_Hybrid  fuelType_Other  \\\n",
      "0             True              False            False           False   \n",
      "1             True              False            False           False   \n",
      "2            False              False            False           False   \n",
      "3             True              False            False           False   \n",
      "4            False              False            False           False   \n",
      "\n",
      "   fuelType_Petrol  \n",
      "0            False  \n",
      "1            False  \n",
      "2             True  \n",
      "3            False  \n",
      "4             True  \n",
      "\n",
      "[5 rows x 24 columns]\n"
     ]
    }
   ],
   "source": [
    "# 4)인코딩 변환 및 불필요한 변수 제거\n",
    "x_train=pd.get_dummies(x_train, columns=['brand', 'transmission', 'fuelType'])\n",
    "x_train=x_train.drop(columns=['model'])\n",
    "print(x_train.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 847,
   "id": "2b516a18-2806-483e-aedb-ed30c008155a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   carID  brand  year transmission  mileage fuelType  tax   mpg  engineSize\n",
      "0  12000   merc  2017    Automatic    12046   Diesel  150  37.2         3.0\n",
      "1  12001     vw  2017    Automatic    37683   Diesel  260  36.2         3.0\n",
      "2  12004   merc  2019    Automatic    10000   Diesel  145  34.0         3.0\n",
      "3  12013  skoda  2019       Manual     3257   Petrol  145  49.6         1.0\n",
      "4  12017   audi  2015    Semi-Auto    20982   Petrol  325  29.4         4.0\n"
     ]
    }
   ],
   "source": [
    "x_test=x_test.drop(columns=['model'])\n",
    "print(x_test.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 849,
   "id": "9aa8f710-d833-4fbb-92b6-6e1c273ae968",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_test=pd.get_dummies(x_test, columns=['brand', 'transmission', 'fuelType'])\n",
    "x_test = x_test.reindex(columns=x_train.columns, fill_value=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 851,
   "id": "9c6f8853-3603-413d-aaba-0c7b6a9d2510",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5) Min-Max 변환\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "scaler = MinMaxScaler()\n",
    "carID_column = x_train['carID']\n",
    "x_train_without_carID = x_train.drop(columns=['carID'])\n",
    "x_train_normal = pd.DataFrame(scaler.fit_transform(x_train_without_carID),\n",
    "columns=x_train_without_carID.columns)\n",
    "x_train_normal['carID'] = carID_column\n",
    "carID_column_test = x_test['carID']\n",
    "x_test_without_carID = x_test.drop(columns=['carID'])\n",
    "x_test_normal = pd.DataFrame(scaler.transform(x_test_without_carID),\n",
    "columns=x_test_without_carID.columns)\n",
    "x_test_normal['carID'] = carID_column_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 853,
   "id": "efa20da6-9c90-4d6c-87ed-6ab42bd66994",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>mileage</th>\n",
       "      <th>tax</th>\n",
       "      <th>mpg</th>\n",
       "      <th>engineSize</th>\n",
       "      <th>brand_audi</th>\n",
       "      <th>brand_bmw</th>\n",
       "      <th>brand_ford</th>\n",
       "      <th>brand_hyundi</th>\n",
       "      <th>brand_merc</th>\n",
       "      <th>...</th>\n",
       "      <th>transmission_Automatic</th>\n",
       "      <th>transmission_Manual</th>\n",
       "      <th>transmission_Other</th>\n",
       "      <th>transmission_Semi-Auto</th>\n",
       "      <th>fuelType_Diesel</th>\n",
       "      <th>fuelType_Electric</th>\n",
       "      <th>fuelType_Hybrid</th>\n",
       "      <th>fuelType_Other</th>\n",
       "      <th>fuelType_Petrol</th>\n",
       "      <th>carID</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.956522</td>\n",
       "      <td>0.016301</td>\n",
       "      <td>0.250000</td>\n",
       "      <td>0.079060</td>\n",
       "      <td>0.333333</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>...</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>13207</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.782609</td>\n",
       "      <td>0.184823</td>\n",
       "      <td>0.215517</td>\n",
       "      <td>0.122436</td>\n",
       "      <td>0.303030</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>...</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>17314</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.956522</td>\n",
       "      <td>0.019884</td>\n",
       "      <td>0.250000</td>\n",
       "      <td>0.056197</td>\n",
       "      <td>0.439394</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>...</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>12342</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 24 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "       year   mileage       tax       mpg  engineSize  brand_audi  brand_bmw  \\\n",
       "0  0.956522  0.016301  0.250000  0.079060    0.333333         0.0        0.0   \n",
       "1  0.782609  0.184823  0.215517  0.122436    0.303030         0.0        0.0   \n",
       "2  0.956522  0.019884  0.250000  0.056197    0.439394         1.0        0.0   \n",
       "\n",
       "   brand_ford  brand_hyundi  brand_merc  ...  transmission_Automatic  \\\n",
       "0         0.0           1.0         0.0  ...                     0.0   \n",
       "1         0.0           0.0         0.0  ...                     0.0   \n",
       "2         0.0           0.0         0.0  ...                     1.0   \n",
       "\n",
       "   transmission_Manual  transmission_Other  transmission_Semi-Auto  \\\n",
       "0                  0.0                 0.0                     1.0   \n",
       "1                  1.0                 0.0                     0.0   \n",
       "2                  0.0                 0.0                     0.0   \n",
       "\n",
       "   fuelType_Diesel  fuelType_Electric  fuelType_Hybrid  fuelType_Other  \\\n",
       "0              1.0                0.0              0.0             0.0   \n",
       "1              1.0                0.0              0.0             0.0   \n",
       "2              0.0                0.0              0.0             0.0   \n",
       "\n",
       "   fuelType_Petrol  carID  \n",
       "0              0.0  13207  \n",
       "1              0.0  17314  \n",
       "2              1.0  12342  \n",
       "\n",
       "[3 rows x 24 columns]"
      ]
     },
     "execution_count": 853,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " x_train_normal.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 855,
   "id": "cff701c7-2561-4f08-97a5-8214c4f13511",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>mileage</th>\n",
       "      <th>tax</th>\n",
       "      <th>mpg</th>\n",
       "      <th>engineSize</th>\n",
       "      <th>brand_audi</th>\n",
       "      <th>brand_bmw</th>\n",
       "      <th>brand_ford</th>\n",
       "      <th>brand_hyundi</th>\n",
       "      <th>brand_merc</th>\n",
       "      <th>...</th>\n",
       "      <th>transmission_Automatic</th>\n",
       "      <th>transmission_Manual</th>\n",
       "      <th>transmission_Other</th>\n",
       "      <th>transmission_Semi-Auto</th>\n",
       "      <th>fuelType_Diesel</th>\n",
       "      <th>fuelType_Electric</th>\n",
       "      <th>fuelType_Hybrid</th>\n",
       "      <th>fuelType_Other</th>\n",
       "      <th>fuelType_Petrol</th>\n",
       "      <th>carID</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.869565</td>\n",
       "      <td>0.046506</td>\n",
       "      <td>0.258621</td>\n",
       "      <td>0.073504</td>\n",
       "      <td>0.454545</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>...</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>12000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.869565</td>\n",
       "      <td>0.145491</td>\n",
       "      <td>0.448276</td>\n",
       "      <td>0.071368</td>\n",
       "      <td>0.454545</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>...</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>12001</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.956522</td>\n",
       "      <td>0.038606</td>\n",
       "      <td>0.250000</td>\n",
       "      <td>0.066667</td>\n",
       "      <td>0.454545</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>...</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>12004</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3 rows × 24 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "       year   mileage       tax       mpg  engineSize  brand_audi  brand_bmw  \\\n",
       "0  0.869565  0.046506  0.258621  0.073504    0.454545         0.0        0.0   \n",
       "1  0.869565  0.145491  0.448276  0.071368    0.454545         0.0        0.0   \n",
       "2  0.956522  0.038606  0.250000  0.066667    0.454545         0.0        0.0   \n",
       "\n",
       "   brand_ford  brand_hyundi  brand_merc  ...  transmission_Automatic  \\\n",
       "0         0.0           0.0         1.0  ...                     1.0   \n",
       "1         0.0           0.0         0.0  ...                     1.0   \n",
       "2         0.0           0.0         1.0  ...                     1.0   \n",
       "\n",
       "   transmission_Manual  transmission_Other  transmission_Semi-Auto  \\\n",
       "0                  0.0                 0.0                     0.0   \n",
       "1                  0.0                 0.0                     0.0   \n",
       "2                  0.0                 0.0                     0.0   \n",
       "\n",
       "   fuelType_Diesel  fuelType_Electric  fuelType_Hybrid  fuelType_Other  \\\n",
       "0              1.0                0.0              0.0             0.0   \n",
       "1              1.0                0.0              0.0             0.0   \n",
       "2              1.0                0.0              0.0             0.0   \n",
       "\n",
       "   fuelType_Petrol  carID  \n",
       "0              0.0  12000  \n",
       "1              0.0  12001  \n",
       "2              0.0  12004  \n",
       "\n",
       "[3 rows x 24 columns]"
      ]
     },
     "execution_count": 855,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " x_test_normal.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 857,
   "id": "c74389a3-1a51-4c52-ab81-b51d858d1901",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 6) 데이터프레임 병합"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 351,
   "id": "63ab86c4-5b29-4c19-91c3-16bae7c0c143",
   "metadata": {},
   "outputs": [],
   "source": [
    "train=pd.merge(x_train_normal, y_train, on=\"carID\", how=\"left\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 353,
   "id": "61189724-9d87-4c85-94bc-9384aa9274db",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 7) 모델 학습\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.metrics import mean_squared_error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 355,
   "id": "9c331c18-d116-4c8c-8e0a-a3afe85cac07",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data, valid_data=train_test_split(train, test_size=0.3, random_state=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 359,
   "id": "513f8b20-65aa-4705-842b-819ce28f99a4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-1 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-1 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-1 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-1 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-1 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-1 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestRegressor()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;RandomForestRegressor<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.ensemble.RandomForestRegressor.html\">?<span>Documentation for RandomForestRegressor</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestRegressor()</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestRegressor()"
      ]
     },
     "execution_count": 359,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model_rf1=RandomForestRegressor()\n",
    "model_rf1.fit(train_data.drop(columns=['price','carID']),train_data['price'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 361,
   "id": "e367b0ea-4059-4ab9-8243-29360798385d",
   "metadata": {},
   "outputs": [],
   "source": [
    " pred_rf1=model_rf1.predict(valid_data.drop(columns=['price', 'carID']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 363,
   "id": "a2d64cdf-086a-4f4b-82fa-d1d9bffaaa01",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3826.9036565112515\n"
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import root_mean_squared_error\n",
    "rmse = root_mean_squared_error(valid_data['price'], pred_rf1)\n",
    "print(rmse)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 365,
   "id": "0cba9f59-52b9-4f89-8af0-24ba696531bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 8) 모델 예측\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "model_rf2=RandomForestRegressor(random_state=42)\n",
    "model_rf2.fit(train.drop(columns=['price', 'carID']), train['price'])\n",
    "pred = model_rf2.predict(x_test_normal.drop(columns=['carID']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 367,
   "id": "edc23123-6012-4e07-8a33-9f275b296b50",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>carID</th>\n",
       "      <th>price</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>12000</td>\n",
       "      <td>38731.02</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>12001</td>\n",
       "      <td>24079.26</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12004</td>\n",
       "      <td>57411.84</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   carID     price\n",
       "0  12000  38731.02\n",
       "1  12001  24079.26\n",
       "2  12004  57411.84"
      ]
     },
     "execution_count": 367,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 9) 답안 제출\n",
    "import pandas as pd\n",
    "result = pd.DataFrame({'carID': x_test_normal['carID'], 'price': pred})\n",
    "result.to_csv('000001.csv', index=False)\n",
    "result_read = pd.read_csv('000001.csv')\n",
    "result_read.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad31bde0-8b0f-43e9-8057-415979a88b33",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 05.train data를 활용하여 선호하는 메타버스 유형(preferred metaverse type)을 분류하는 모델을 구축하고 \n",
    "# test data를 대상으로 분류한 예측 결과를 result.csv 파일로 제출하시오(제출한 모델의 성능은 Macro-F1 평가지표에 따라 채점)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 369,
   "id": "04accd02-22cf-439e-bf66-24a31f000167",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "import xgboost as xgb\n",
    "import lightgbm as lgb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 371,
   "id": "580ec6b4-6977-49ea-85f5-75edcddb1a9f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1)데이터 불러오기\n",
    "train=pd.read_csv('c:/data/train_meta.csv')\n",
    "test=pd.read_csv('c:/data/test_meta.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 373,
   "id": "4c467481-25cf-40e8-868a-812d47065a67",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1400 entries, 0 to 1399\n",
      "Data columns (total 9 columns):\n",
      " #   Column                      Non-Null Count  Dtype \n",
      "---  ------                      --------------  ----- \n",
      " 0   Gender                      1400 non-null   object\n",
      " 1   Age                         1400 non-null   int64 \n",
      " 2   Education                   1400 non-null   object\n",
      " 3   Occupation                  1400 non-null   object\n",
      " 4   Type Residence              1400 non-null   object\n",
      " 5   Experience Using Metaverse  1400 non-null   int64 \n",
      " 6   Annual Salary               1400 non-null   int64 \n",
      " 7   Using Metaverse             1400 non-null   object\n",
      " 8   Preferred Metaverse Type    1400 non-null   int64 \n",
      "dtypes: int64(4), object(5)\n",
      "memory usage: 98.6+ KB\n"
     ]
    }
   ],
   "source": [
    "# 2)데이터 탐색\n",
    "train.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 375,
   "id": "3c769768-2956-4577-90bf-773b58e057c3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 600 entries, 0 to 599\n",
      "Data columns (total 8 columns):\n",
      " #   Column                      Non-Null Count  Dtype \n",
      "---  ------                      --------------  ----- \n",
      " 0   Gender                      600 non-null    object\n",
      " 1   Age                         600 non-null    int64 \n",
      " 2   Education                   600 non-null    object\n",
      " 3   Occupation                  600 non-null    object\n",
      " 4   Type Residence              600 non-null    object\n",
      " 5   Experience Using Metaverse  600 non-null    int64 \n",
      " 6   Annual Salary               600 non-null    int64 \n",
      " 7   Using Metaverse             600 non-null    object\n",
      "dtypes: int64(3), object(5)\n",
      "memory usage: 37.6+ KB\n"
     ]
    }
   ],
   "source": [
    "test.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 377,
   "id": "86698218-9260-4fbf-9958-d68eac6fb840",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3) 타겟 컬럼 분리\n",
    "Y = train['Preferred Metaverse Type']\n",
    "X = train.drop(columns=['Preferred Metaverse Type'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 379,
   "id": "e42d686a-0b78-4f99-8003-83ac330c8dc8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4) 인코딩 변환\n",
    "for column in X.select_dtypes(include=['object']).columns:\n",
    "    le=LabelEncoder()\n",
    "    combined = pd.concat([X[column].astype(str), test[column].astype(str)])\n",
    "    le.fit(combined)\n",
    "    X[column] = le.transform(X[column].astype(str))\n",
    "    test[column] = le.transform(test[column].astype(str))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 381,
   "id": "c5027144-a1ea-4583-8f92-526605e0391c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5) Min-Max 정규화\n",
    "numeric_cols=X.select_dtypes(include=['int64', 'float64']).columns\n",
    "scaler=MinMaxScaler()\n",
    "X[numeric_cols] = scaler.fit_transform(X[numeric_cols])\n",
    "test[numeric_cols] = scaler.transform(test[numeric_cols])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 383,
   "id": "68bffea0-8326-4608-a2c3-cfc80f23cd73",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-2 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-2 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-2 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-2 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-2 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-2 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-2 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-2 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-2 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier(random_state=42)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" checked><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;RandomForestClassifier<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.ensemble.RandomForestClassifier.html\">?<span>Documentation for RandomForestClassifier</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestClassifier(random_state=42)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestClassifier(random_state=42)"
      ]
     },
     "execution_count": 383,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 6) 모델 학습 및 평가\n",
    "rf_model=RandomForestClassifier(random_state=42)\n",
    "rf_model.fit(X, Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 385,
   "id": "bcec4e43-2d62-4947-ac4f-d36b60ac2b32",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.0"
      ]
     },
     "execution_count": 385,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.metrics import f1_score\n",
    "rf_f1=f1_score(Y, rf_model.predict(X), average='macro')\n",
    "rf_f1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 391,
   "id": "a856310d-914b-4fcf-8f07-703e97a14a05",
   "metadata": {},
   "outputs": [],
   "source": [
    "xgb_model=xgb.XGBClassifier(\n",
    "eval_metric='mlogloss',\n",
    "random_state=42\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 393,
   "id": "014ee656-8e73-4458-bd51-1b4d687cda39",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9985700849976462"
      ]
     },
     "execution_count": 393,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xgb_model.fit(X, Y)\n",
    "xgb_f1=f1_score(Y, xgb_model.predict(X), average='macro')\n",
    "xgb_f1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 395,
   "id": "f6e48c56-0af6-4d0d-a768-a8aee5d95973",
   "metadata": {},
   "outputs": [],
   "source": [
    "lgb_model=lgb.LGBMClassifier(\n",
    "random_state=42,\n",
    "verbose=-1,\n",
    "n_jobs=-1\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 397,
   "id": "a9367d55-aa0e-4913-bbae-cbac0064431b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9878898081454197"
      ]
     },
     "execution_count": 397,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lgb_model.fit(X, Y)\n",
    "lgb_f1=f1_score(Y, lgb_model.predict(X), average='macro')\n",
    "lgb_f1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 399,
   "id": "1a27f79b-899e-4a1f-a445-b6f691f62186",
   "metadata": {},
   "outputs": [],
   "source": [
    "rf_test_preds=rf_model.predict(test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 401,
   "id": "33bb8517-c7d5-4709-a7cd-789158091cb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "rf_predictions_df=pd.DataFrame({\n",
    "'pred': rf_test_preds\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 403,
   "id": "24a053f6-4127-4976-b7b5-8117004cb57c",
   "metadata": {},
   "outputs": [],
   "source": [
    "rf_predictions_df.to_csv('result.csv', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de4870a6-6aae-4a45-a283-040a5f44e891",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 06 학생 성적 데이터셋(Student Performance Dataset)은 학생들의 학업 성취도에 영향을 미치는 요인을 분석하기 위해 설계된 데이터셋이다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 429,
   "id": "27515992-ca10-4dad-bb75-1ce18369c219",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1) 데이터 불러오기\n",
    "import pandas as pd\n",
    "train=pd.read_csv(\"c:/data/train_performance.csv\")\n",
    "test=pd.read_csv(\"c:/data/test_performance.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 431,
   "id": "8e842bac-bd13-4f13-a921-a242ebcf2fb2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2)필요한 라이브러리 가져오기\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 433,
   "id": "15ac11be-c561-455f-b2c1-ebe93a70d671",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(7000, 6)"
      ]
     },
     "execution_count": 433,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 3)데이터 탐색\n",
    "train.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 435,
   "id": "b9b762fd-6713-4689-89b2-c6667c9ebd6f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3000, 5)"
      ]
     },
     "execution_count": 435,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 437,
   "id": "9be80709-bd59-4edf-a622-3cfddd49525c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 7000 entries, 0 to 6999\n",
      "Data columns (total 6 columns):\n",
      " #   Column                            Non-Null Count  Dtype \n",
      "---  ------                            --------------  ----- \n",
      " 0   Hours Studied                     7000 non-null   int64 \n",
      " 1   Previous Scores                   7000 non-null   int64 \n",
      " 2   Extracurricular Activities        7000 non-null   object\n",
      " 3   Sleep Hours                       7000 non-null   int64 \n",
      " 4   Sample Question Papers Practiced  7000 non-null   int64 \n",
      " 5   Performance Index                 7000 non-null   int64 \n",
      "dtypes: int64(5), object(1)\n",
      "memory usage: 328.3+ KB\n"
     ]
    }
   ],
   "source": [
    "train.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 439,
   "id": "67b2d4ad-2073-47f6-8c5d-20836f647dd6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Hours Studied                       0\n",
       "Previous Scores                     0\n",
       "Extracurricular Activities          0\n",
       "Sleep Hours                         0\n",
       "Sample Question Papers Practiced    0\n",
       "Performance Index                   0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 439,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 441,
   "id": "1fc42117-1378-40a9-ba51-64f260dfccc2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 3000 entries, 0 to 2999\n",
      "Data columns (total 5 columns):\n",
      " #   Column                            Non-Null Count  Dtype \n",
      "---  ------                            --------------  ----- \n",
      " 0   Hours Studied                     3000 non-null   int64 \n",
      " 1   Previous Scores                   3000 non-null   int64 \n",
      " 2   Extracurricular Activities        3000 non-null   object\n",
      " 3   Sleep Hours                       3000 non-null   int64 \n",
      " 4   Sample Question Papers Practiced  3000 non-null   int64 \n",
      "dtypes: int64(4), object(1)\n",
      "memory usage: 117.3+ KB\n"
     ]
    }
   ],
   "source": [
    "test.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 443,
   "id": "4079b851-b736-4f17-a597-d34a18d0e04f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4) 인코딩 변환\n",
    "le = LabelEncoder()\n",
    "train['Extracurricular Activities'] = le.fit_transform(train['Extracurricular Activities'])\n",
    "test['Extracurricular Activities'] = le.transform(test['Extracurricular Activities'])\n",
    "# 인코딩 완료 후 X, Y 분리\n",
    "X = train.drop(columns=['Performance Index'])\n",
    "Y = train['Performance Index']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 445,
   "id": "8dab9513-e193-4c61-a9ad-e8e54afaec84",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5) 모델 학습\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.metrics import mean_squared_error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 447,
   "id": "00a2e532-7140-4696-b751-544b08b7d175",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-4 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-4 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-4 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-4 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-4 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-4 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-4 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-4 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-4 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-4 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-4 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-4 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-4 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-4 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-4 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-4 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-4 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-4 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-4 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-4\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestRegressor(random_state=42)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" checked><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;RandomForestRegressor<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.ensemble.RandomForestRegressor.html\">?<span>Documentation for RandomForestRegressor</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestRegressor(random_state=42)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestRegressor(random_state=42)"
      ]
     },
     "execution_count": 447,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model = RandomForestRegressor(random_state=42)\n",
    "model.fit(X,Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 448,
   "id": "1b4cf0ee-7683-494e-a56f-d692f4ca2363",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 6)모델 예측\n",
    "y_pred=model.predict(test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 451,
   "id": "67d4ab8a-971c-4d61-9923-d7c0bebace8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 7)모델 평가\n",
    "from sklearn.model_selection import train_test_split\n",
    "X_train,X_valid,Y_train,Y_valid= train_test_split(X, Y, test_size=0.2, random_state=42)\n",
    "model = RandomForestRegressor(random_state=42)\n",
    "model.fit(X_train, Y_train)\n",
    "Y_pred_valid=model.predict(X_valid)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 453,
   "id": "e76d1c35-a941-44b6-9628-e4e05b170033",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.380415486716489\n"
     ]
    }
   ],
   "source": [
    "# RMSE 계산\n",
    "rmse=np.sqrt(mean_squared_error(Y_valid, Y_pred_valid))\n",
    "print(rmse)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 455,
   "id": "130537c6-270e-4161-be0f-22d805759399",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([55.96      , 21.49      , 46.51      , ..., 32.72      ,\n",
       "       67.81083333, 28.32      ])"
      ]
     },
     "execution_count": 455,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 8) 답안 제출\n",
    "y_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 457,
   "id": "3e2d6cb8-af67-459d-8c8c-9bc482a1af24",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>pred</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>55.960000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>21.490000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>46.510000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>28.671667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>42.214167</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        pred\n",
       "0  55.960000\n",
       "1  21.490000\n",
       "2  46.510000\n",
       "3  28.671667\n",
       "4  42.214167"
      ]
     },
     "execution_count": 457,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " # 예측 결과를 데이터프레임으로 저장\n",
    "result_df=pd.DataFrame({\"pred\": y_pred})\n",
    "result_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 459,
   "id": "f3ea0366-3495-4e11-a42c-fc5f87846770",
   "metadata": {},
   "outputs": [],
   "source": [
    "# CSV 파일로 저장\n",
    "result_df.to_csv('result.csv', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e23abc9-a2f0-4b2f-b780-fd26c1455812",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 07. 학습용 데이터를 이용하여 총 청구액을 예측하는 모델을 만든 후 이를 평가용 데이터에 적용해 \n",
    "# 얻는 예측값을 아래와 같은 형식의 csv 파일로 생성하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 461,
   "id": "806d0c72-7d0c-478b-8c2a-a560cb3087c0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: lightgbm in c:\\users\\emhu8\\anaconda3\\lib\\site-packages (4.6.0)\n",
      "Requirement already satisfied: numpy>=1.17.0 in c:\\users\\emhu8\\anaconda3\\lib\\site-packages (from lightgbm) (1.26.4)\n",
      "Requirement already satisfied: scipy in c:\\users\\emhu8\\anaconda3\\lib\\site-packages (from lightgbm) (1.13.1)\n",
      "Requirement already satisfied: xgboost in c:\\users\\emhu8\\anaconda3\\lib\\site-packages (2.1.4)\n",
      "Requirement already satisfied: numpy in c:\\users\\emhu8\\anaconda3\\lib\\site-packages (from xgboost) (1.26.4)\n",
      "Requirement already satisfied: scipy in c:\\users\\emhu8\\anaconda3\\lib\\site-packages (from xgboost) (1.13.1)\n"
     ]
    }
   ],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn.metrics import mean_absolute_error\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "! pip install lightgbm\n",
    "! pip install xgboost\n",
    "from xgboost import XGBRegressor\n",
    "from lightgbm import LGBMRegressor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 463,
   "id": "b9a3ebe9-4398-47b0-ae94-9de5f02e26f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2) 데이터 탐색\n",
    "import pandas as pd\n",
    "train=pd.read_csv(\"c:/data/train_churn.csv\")\n",
    "test=pd.read_csv(\"c:/data/test_churn.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 465,
   "id": "f3418fec-4a3d-417d-9035-442589a50b6c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(210, 20)\n",
      "(90, 20)\n"
     ]
    }
   ],
   "source": [
    "print(train.shape)\n",
    "print(test.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 467,
   "id": "086ee4af-2ed8-44c7-9ad0-82eec62a0cdc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 210 entries, 0 to 209\n",
      "Data columns (total 20 columns):\n",
      " #   Column            Non-Null Count  Dtype  \n",
      "---  ------            --------------  -----  \n",
      " 0   customerID        210 non-null    object \n",
      " 1   gender            210 non-null    object \n",
      " 2   SeniorCitizen     210 non-null    int64  \n",
      " 3   Partner           210 non-null    object \n",
      " 4   Dependents        210 non-null    object \n",
      " 5   tenure            210 non-null    int64  \n",
      " 6   PhoneService      210 non-null    object \n",
      " 7   MultipleLines     210 non-null    object \n",
      " 8   InternetService   210 non-null    object \n",
      " 9   OnlineSecurity    210 non-null    object \n",
      " 10  OnlineBackup      210 non-null    object \n",
      " 11  DeviceProtection  210 non-null    object \n",
      " 12  TechSupport       210 non-null    object \n",
      " 13  StreamingTV       210 non-null    object \n",
      " 14  StreamingMovies   210 non-null    object \n",
      " 15  Contract          210 non-null    object \n",
      " 16  PaperlessBilling  210 non-null    object \n",
      " 17  PaymentMethod     210 non-null    object \n",
      " 18  TotalCharges      210 non-null    float64\n",
      " 19  Churn             210 non-null    object \n",
      "dtypes: float64(1), int64(2), object(17)\n",
      "memory usage: 32.9+ KB\n"
     ]
    }
   ],
   "source": [
    "train.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 469,
   "id": "75dfd655-d862-4765-a2a2-19ed021a3d0b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "customerID          0\n",
       "gender              0\n",
       "SeniorCitizen       0\n",
       "Partner             0\n",
       "Dependents          0\n",
       "tenure              0\n",
       "PhoneService        0\n",
       "MultipleLines       0\n",
       "InternetService     0\n",
       "OnlineSecurity      0\n",
       "OnlineBackup        0\n",
       "DeviceProtection    0\n",
       "TechSupport         0\n",
       "StreamingTV         0\n",
       "StreamingMovies     0\n",
       "Contract            0\n",
       "PaperlessBilling    0\n",
       "PaymentMethod       0\n",
       "TotalCharges        0\n",
       "Churn               0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 469,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 471,
   "id": "6a200f27-cce0-439f-958a-95fb687dbbdc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 90 entries, 0 to 89\n",
      "Data columns (total 20 columns):\n",
      " #   Column            Non-Null Count  Dtype  \n",
      "---  ------            --------------  -----  \n",
      " 0   customerID        90 non-null     object \n",
      " 1   gender            90 non-null     object \n",
      " 2   SeniorCitizen     90 non-null     int64  \n",
      " 3   Partner           90 non-null     object \n",
      " 4   Dependents        90 non-null     object \n",
      " 5   tenure            90 non-null     int64  \n",
      " 6   PhoneService      90 non-null     object \n",
      " 7   MultipleLines     90 non-null     object \n",
      " 8   InternetService   90 non-null     object \n",
      " 9   OnlineSecurity    90 non-null     object \n",
      " 10  OnlineBackup      90 non-null     object \n",
      " 11  DeviceProtection  90 non-null     object \n",
      " 12  TechSupport       90 non-null     object \n",
      " 13  StreamingTV       90 non-null     object \n",
      " 14  StreamingMovies   90 non-null     object \n",
      " 15  Contract          90 non-null     object \n",
      " 16  PaperlessBilling  90 non-null     object \n",
      " 17  PaymentMethod     90 non-null     object \n",
      " 18  TotalCharges      90 non-null     float64\n",
      " 19  Churn             90 non-null     object \n",
      "dtypes: float64(1), int64(2), object(17)\n",
      "memory usage: 14.2+ KB\n"
     ]
    }
   ],
   "source": [
    " test.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 473,
   "id": "68c10203-6dcc-49de-9691-45b2aced6f3c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "customerID          0\n",
       "gender              0\n",
       "SeniorCitizen       0\n",
       "Partner             0\n",
       "Dependents          0\n",
       "tenure              0\n",
       "PhoneService        0\n",
       "MultipleLines       0\n",
       "InternetService     0\n",
       "OnlineSecurity      0\n",
       "OnlineBackup        0\n",
       "DeviceProtection    0\n",
       "TechSupport         0\n",
       "StreamingTV         0\n",
       "StreamingMovies     0\n",
       "Contract            0\n",
       "PaperlessBilling    0\n",
       "PaymentMethod       0\n",
       "TotalCharges        0\n",
       "Churn               0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 473,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e841ae4c-2fce-4dcb-8b45-9d0880f5f371",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3)타겟 변수 분할"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 475,
   "id": "f8b98b50-71f6-47f6-b057-e201869d70e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "Y = train['TotalCharges']\n",
    "X = train.drop(columns=['TotalCharges', 'customerID'])\n",
    "test_customer_ids = test['customerID'].copy()\n",
    "X_test = test.drop(columns=['customerID', 'TotalCharges'], errors='ignore')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 477,
   "id": "8145578d-2f2f-4be9-b16f-767b492247b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4) 인코딩 변환\n",
    "categorical_cols=X.select_dtypes(include=['object']).columns\n",
    "for col in categorical_cols:\n",
    "    le = LabelEncoder()\n",
    "    combined = pd.concat([X[col].astype(str), X_test[col].astype(str)])\n",
    "    le.fit(combined)\n",
    "    X[col] = le.transform(X[col].astype(str))\n",
    "    X_test[col] = le.transform(X_test[col].astype(str))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 479,
   "id": "d9059b4e-89f6-4d60-9190-5506724832f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5) 학습 & 검증 데이터 분할 (80% 학습, 20% 검증(\n",
    "X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.2, random_state=42)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 481,
   "id": "f4a310bb-f866-4f13-b0a3-05c9c4d42af2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-5 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-5 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-5 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-5 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-5 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-5 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-5 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-5 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-5 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-5 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-5 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-5 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-5 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-5 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-5 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-5 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-5 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-5 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-5 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-5\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestRegressor(random_state=42)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" checked><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;RandomForestRegressor<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.ensemble.RandomForestRegressor.html\">?<span>Documentation for RandomForestRegressor</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestRegressor(random_state=42)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestRegressor(random_state=42)"
      ]
     },
     "execution_count": 481,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 6) 랜덤 포레스트 모델 학습\n",
    "model=RandomForestRegressor(random_state=42)\n",
    "model.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 483,
   "id": "f2e7798f-c53f-4e31-a4fe-c7737d1f7359",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2299.780822893681\n"
     ]
    }
   ],
   "source": [
    "# 7) 검증 데이터 예측 및 성능 평가(MAE)\n",
    "y_pred=model.predict(X_val)\n",
    "mae = mean_absolute_error(y_val, y_pred)\n",
    "print(mae)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 485,
   "id": "5be7004d-5f9a-41c9-b50c-c83d980ed873",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred_test = model.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 487,
   "id": "93762c1e-2813-4cd3-81cc-73b810e47e50",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예측 결과를 'pred' 컬럼으로 CSV 저장\n",
    "result = pd.DataFrame({'pred': y_pred_test})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0bf307e-8083-44c6-b066-a2f44eea0e55",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 8) 답안 제출"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 489,
   "id": "52a2a27d-0fa1-4333-9cf2-e72d9424d38d",
   "metadata": {},
   "outputs": [],
   "source": [
    "result.to_csv(\"result.csv\", index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f328f049-4d46-4792-8615-c79f6e70b25d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 1067,
   "id": "628e1c89-e235-416a-b450-c3e8a3f9503c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# CHAPTER 04. 작업형 3유형\n",
    "# 01 통계적 가설검정\n",
    "# 02 평균차이 검정\n",
    "# 03 분산분석\n",
    "# 04 범주형 자료분석\n",
    "# 6장 다중회귀분석(Multiple Linear Regression)\n",
    "# 7장 로지스틱 회귀분석(Logistic Regression)\n",
    "# 8장 기출문제"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "287daf85-8c5c-4771-8925-cff49de882dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3장  평균차이 검정"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1069,
   "id": "d09a9b6f-4687-4d64-b914-aeb25f621cb1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 32 entries, 0 to 31\n",
      "Data columns (total 12 columns):\n",
      " #   Column      Non-Null Count  Dtype  \n",
      "---  ------      --------------  -----  \n",
      " 0   Unnamed: 0  32 non-null     object \n",
      " 1   mpg         32 non-null     float64\n",
      " 2   cyl         32 non-null     int64  \n",
      " 3   disp        32 non-null     float64\n",
      " 4   hp          32 non-null     int64  \n",
      " 5   drat        32 non-null     float64\n",
      " 6   wt          32 non-null     float64\n",
      " 7   qsec        32 non-null     float64\n",
      " 8   vs          32 non-null     int64  \n",
      " 9   am          32 non-null     int64  \n",
      " 10  gear        32 non-null     int64  \n",
      " 11  carb        32 non-null     int64  \n",
      "dtypes: float64(5), int64(6), object(1)\n",
      "memory usage: 3.1+ KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "# 예제 1\n",
    "import pandas as pd\n",
    "mtcars=pd.read_csv(\"c:/data/mtcars.csv\")\n",
    "print(mtcars.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1071,
   "id": "ef181e43-6a81-47cb-9605-d35a3b9133a2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(13,)"
      ]
     },
     "execution_count": 1071,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df=mtcars.mpg[mtcars.am==1]\n",
    "df.shape\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1073,
   "id": "bfbc2f34-6ce7-4c3d-bcda-4445a4b18508",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ShapiroResult(statistic=0.9458036604933976, pvalue=0.536272885248448)\n"
     ]
    }
   ],
   "source": [
    "from scipy import stats\n",
    "shapiro_test=stats.shapiro(df)\n",
    "print(shapiro_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1075,
   "id": "f2b37c09-56e2-4c20-930e-d361e9e08618",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "TtestResult(statistic=2.5681798133667297, pvalue=0.012313979231529106, df=12)"
      ]
     },
     "execution_count": 1075,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 예제 2\n",
    "from scipy import stats\n",
    "df=mtcars[mtcars['am']==1]\n",
    "stats.ttest_1samp(df['mpg'],20,alternative= 'greater')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19edab10-2189-4b23-8655-8a3051510cd6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1077,
   "id": "fe364d98-4560-4c98-9130-33aee52bb133",
   "metadata": {},
   "outputs": [],
   "source": [
    "before=[59,72,85,69,78,82,55]\n",
    "after=[54,65,84,63,72,83,51]\n",
    "diff = np.array(before) - np.array(after)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1079,
   "id": "fbeef360-6952-4270-b846-b25e38845093",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ShapiroResult(statistic=0.8845842062280572, pvalue=0.24758674976543332)"
      ]
     },
     "execution_count": 1079,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " stats.shapiro(diff)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1081,
   "id": "ad9b9448-3b6f-484b-a09b-c3d0aedc4e3c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "TtestResult(statistic=3.594868137091668, pvalue=0.00571838952266157, df=6)"
      ]
     },
     "execution_count": 1081,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stats.ttest_rel(before, after,alternative= 'greater')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1083,
   "id": "f8e756bd-bb90-4f59-bf7f-528b902311bb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.0"
      ]
     },
     "execution_count": 1083,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.DataFrame (\n",
    "{'before':[59,72,85,69,78,82,55],\n",
    " 'after':[54,65,84,63,72,83,51]})\n",
    "df1=df['before']-df['after']\n",
    "df1.mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1085,
   "id": "7563470e-4e1d-4b08-9868-eb8e87a32f76",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.1126972805283735"
      ]
     },
     "execution_count": 1085,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2=df1.var()\n",
    "import math\n",
    "math.sqrt(df2/7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1087,
   "id": "c9170e65-4863-450c-b387-93b4e4b58017",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제 4\n",
    "tre=[10,16,27,15,21,14,16,21,22,23,25,28,27,13,\n",
    "15,16,21,22,25,28]\n",
    "con=[23,26,27,23,16,18,31,33,28,36,18,21,26,28,29,\n",
    "33,32,16,18,23]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1089,
   "id": "212d2cab-b6f6-4601-918d-dc5e0cb3e23c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ShapiroResult(statistic=0.9347494567202286, pvalue=0.19049492458197126)"
      ]
     },
     "execution_count": 1089,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from scipy import stats\n",
    "stats.shapiro(tre)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1091,
   "id": "36fa5f83-f869-4085-851b-de47943bd1bf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ShapiroResult(statistic=0.9511457293050639, pvalue=0.38481703380566723)"
      ]
     },
     "execution_count": 1091,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from scipy import stats\n",
    "stats.shapiro(con)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1093,
   "id": "cba214b9-2c35-48d8-b45d-14eba61b7e97",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LeveneResult(statistic=0.24617776626068932, pvalue=0.6226372407136405)"
      ]
     },
     "execution_count": 1093,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from scipy import stats\n",
    "stats.levene(tre,con)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1095,
   "id": "448cb246-5626-4000-b116-a7f026818f4a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "TtestResult(statistic=-2.716365361415697, pvalue=0.004939798032514886, df=38.0)"
      ]
     },
     "execution_count": 1095,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stats.ttest_ind(tre,con,equal_var=True,alternative=\"less\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c09a2e43-51c6-4150-aa74-6a9c56599d19",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4장 분산분석(ANOVA, Analysis of Variance)\n",
    "# 01 분산분석(ANOVA, Analysis of Variance)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1101,
   "id": "0250849f-ddb8-4513-8c16-457d7303d881",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>weight</th>\n",
       "      <th>group</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4.17</td>\n",
       "      <td>ctrl</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5.58</td>\n",
       "      <td>ctrl</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>5.18</td>\n",
       "      <td>ctrl</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   weight group\n",
       "0    4.17  ctrl\n",
       "1    5.58  ctrl\n",
       "2    5.18  ctrl"
      ]
     },
     "execution_count": 1101,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv(\"c:/data/PlantGrowth.csv\")\n",
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1103,
   "id": "0b2716f6-f502-4f40-878a-0175809ac4c0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 30 entries, 0 to 29\n",
      "Data columns (total 2 columns):\n",
      " #   Column  Non-Null Count  Dtype  \n",
      "---  ------  --------------  -----  \n",
      " 0   weight  30 non-null     float64\n",
      " 1   group   30 non-null     object \n",
      "dtypes: float64(1), object(1)\n",
      "memory usage: 612.0+ bytes\n"
     ]
    }
   ],
   "source": [
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1105,
   "id": "f78bf4d6-5db4-441c-90aa-07ee3681935d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "group\n",
       "ctrl    10\n",
       "trt1    10\n",
       "trt2    10\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 1105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['group'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1107,
   "id": "e5822e03-810e-4198-b1b0-2a2caab76b8d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from statsmodels.stats.anova import anova_lm\n",
    "from statsmodels.formula.api import ols"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1109,
   "id": "5b12a8f3-6c21-4cee-b78f-6a3ee2a5bb26",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>df</th>\n",
       "      <th>sum_sq</th>\n",
       "      <th>mean_sq</th>\n",
       "      <th>F</th>\n",
       "      <th>PR(&gt;F)</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>C(group)</th>\n",
       "      <td>2.0</td>\n",
       "      <td>3.76634</td>\n",
       "      <td>1.883170</td>\n",
       "      <td>4.846088</td>\n",
       "      <td>0.01591</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Residual</th>\n",
       "      <td>27.0</td>\n",
       "      <td>10.49209</td>\n",
       "      <td>0.388596</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            df    sum_sq   mean_sq         F   PR(>F)\n",
       "C(group)   2.0   3.76634  1.883170  4.846088  0.01591\n",
       "Residual  27.0  10.49209  0.388596       NaN      NaN"
      ]
     },
     "execution_count": 1109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model=ols('weight ~ C(group)', df).fit()\n",
    "anova_lm(model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1111,
   "id": "a8f85c2c-93d7-4287-8191-2e4f092c4b51",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table class=\"simpletable\">\n",
       "<caption>Multiple Comparison of Means - Tukey HSD, FWER=0.05</caption>\n",
       "<tr>\n",
       "  <th>group1</th> <th>group2</th> <th>meandiff</th>  <th>p-adj</th>  <th>lower</th>   <th>upper</th> <th>reject</th>\n",
       "</tr>\n",
       "<tr>\n",
       "   <td>ctrl</td>   <td>trt1</td>   <td>-0.371</td>  <td>0.3909</td> <td>-1.0622</td> <td>0.3202</td>  <td>False</td>\n",
       "</tr>\n",
       "<tr>\n",
       "   <td>ctrl</td>   <td>trt2</td>    <td>0.494</td>   <td>0.198</td> <td>-0.1972</td> <td>1.1852</td>  <td>False</td>\n",
       "</tr>\n",
       "<tr>\n",
       "   <td>trt1</td>   <td>trt2</td>    <td>0.865</td>   <td>0.012</td> <td>0.1738</td>  <td>1.5562</td>  <td>True</td> \n",
       "</tr>\n",
       "</table>"
      ],
      "text/latex": [
       "\\begin{center}\n",
       "\\begin{tabular}{ccccccc}\n",
       "\\toprule\n",
       "\\textbf{group1} & \\textbf{group2} & \\textbf{meandiff} & \\textbf{p-adj} & \\textbf{lower} & \\textbf{upper} & \\textbf{reject}  \\\\\n",
       "\\midrule\n",
       "      ctrl      &       trt1      &       -0.371      &     0.3909     &    -1.0622     &     0.3202     &      False       \\\\\n",
       "      ctrl      &       trt2      &       0.494       &     0.198      &    -0.1972     &     1.1852     &      False       \\\\\n",
       "      trt1      &       trt2      &       0.865       &     0.012      &     0.1738     &     1.5562     &       True       \\\\\n",
       "\\bottomrule\n",
       "\\end{tabular}\n",
       "%\\caption{Multiple Comparison of Means - Tukey HSD, FWER=0.05}\n",
       "\\end{center}"
      ],
      "text/plain": [
       "<class 'statsmodels.iolib.table.SimpleTable'>"
      ]
     },
     "execution_count": 1111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from statsmodels.stats.multicomp import pairwise_tukeyhsd\n",
    "hsd=pairwise_tukeyhsd(df['weight'], df['group'], alpha=0.05)\n",
    "hsd.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96de47e9-7e9f-442c-baec-9e0497745c4f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 02 이원 분산분석(Two-Way ANOVA)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab6c7be2-f054-45a1-93d9-d61ee21a3f21",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1123,
   "id": "35884cde-8183-42cd-bf3c-d3fbc7c73653",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import statsmodels.api as sm\n",
    "import statsmodels.formula.api as smf\n",
    "from statsmodels.multivariate.manova import MANOVA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1115,
   "id": "4c73448e-e6f7-4e20-8dce-2628a8da945a",
   "metadata": {},
   "outputs": [],
   "source": [
    "df=pd.read_csv(\"c:/data/two_anova.csv\")\n",
    "model=smf.ols(\"체중감소 ~ C(운동) + C(식단) + C(운동):C(식단)\", data=df).fit()\n",
    "anova_table=sm.stats.anova_lm(model, typ=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1117,
   "id": "9f84d409-fc08-4c13-9654-e0b88d40dad1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                 sum_sq    df          F        PR(>F)\n",
      "C(운동)        158.050915   2.0  87.252408  6.222718e-21\n",
      "C(식단)         28.297318   2.0  15.621606  1.828773e-06\n",
      "C(운동):C(식단)    3.446546   4.0   0.951337  4.388687e-01\n",
      "Residual      73.362584  81.0        NaN           NaN\n"
     ]
    }
   ],
   "source": [
    "print(anova_table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5454264a-2a98-4a21-8aa7-b94a10f35d10",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 03 다변량 분산분석(MANOVA)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1125,
   "id": "99e94ba2-7f88-4a1a-a8b0-d99db3b222a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                  Multivariate linear model\n",
      "==============================================================\n",
      "                                                              \n",
      "--------------------------------------------------------------\n",
      "       Intercept         Value  Num DF  Den DF F Value  Pr > F\n",
      "--------------------------------------------------------------\n",
      "          Wilks' lambda  0.0378 3.0000 79.0000 670.4452 0.0000\n",
      "         Pillai's trace  0.9622 3.0000 79.0000 670.4452 0.0000\n",
      " Hotelling-Lawley trace 25.4599 3.0000 79.0000 670.4452 0.0000\n",
      "    Roy's greatest root 25.4599 3.0000 79.0000 670.4452 0.0000\n",
      "--------------------------------------------------------------\n",
      "                                                              \n",
      "--------------------------------------------------------------\n",
      "          C(운동)          Value  Num DF  Den DF  F Value Pr > F\n",
      "--------------------------------------------------------------\n",
      "           Wilks' lambda 0.3496 6.0000 158.0000 18.2063 0.0000\n",
      "          Pillai's trace 0.6710 6.0000 160.0000 13.4633 0.0000\n",
      "  Hotelling-Lawley trace 1.8020 6.0000 103.5745 23.5809 0.0000\n",
      "     Roy's greatest root 1.7688 3.0000  80.0000 47.1671 0.0000\n",
      "--------------------------------------------------------------\n",
      "                                                              \n",
      "--------------------------------------------------------------\n",
      "          C(식단)          Value  Num DF  Den DF  F Value Pr > F\n",
      "--------------------------------------------------------------\n",
      "           Wilks' lambda 0.7767 6.0000 158.0000  3.5458 0.0025\n",
      "          Pillai's trace 0.2301 6.0000 160.0000  3.4662 0.0030\n",
      "  Hotelling-Lawley trace 0.2787 6.0000 103.5745  3.6468 0.0025\n",
      "     Roy's greatest root 0.2426 3.0000  80.0000  6.4695 0.0006\n",
      "--------------------------------------------------------------\n",
      "                                                              \n",
      "--------------------------------------------------------------\n",
      "      C(운동):C(식단)       Value   Num DF  Den DF  F Value Pr > F\n",
      "--------------------------------------------------------------\n",
      "          Wilks' lambda 0.8351 12.0000 209.3059  1.2295 0.2644\n",
      "         Pillai's trace 0.1718 12.0000 243.0000  1.2304 0.2625\n",
      " Hotelling-Lawley trace 0.1892 12.0000 134.0000  1.2324 0.2674\n",
      "    Roy's greatest root 0.1216  4.0000  81.0000  2.4631 0.0516\n",
      "==============================================================\n",
      "\n"
     ]
    }
   ],
   "source": [
    "df=pd.read_csv(\"c:/data/manova.csv\")\n",
    "manova=MANOVA.from_formula(\"체중감소 + 근육량증가 + 체지방감소 ~ C(운동) + C(식단) + C(운동):C(식단)\", data=df)\n",
    "manova_results=manova.mv_test()\n",
    "print(manova_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d6e2de0-a23b-4a15-8c6f-b1ded8fd35bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 04 공분산분석(ANCOVA)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1127,
   "id": "c94969d1-36b7-4b37-8cea-24bcb79a3acd",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import statsmodels.api as sm\n",
    "import statsmodels.formula.api as smf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1129,
   "id": "235dd3c5-6dcd-4c9a-8d0a-63069e174d54",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                sum_sq    df             F    PR(>F)\n",
      "C(운동)     2.592567e-27   2.0  3.747241e-03  0.996260\n",
      "C(식단)     6.000000e+01   2.0  8.672269e+25  0.000000\n",
      "초기체중      4.436570e-26   1.0  1.282504e-01  0.721151\n",
      "Residual  2.905814e-23  84.0           NaN       NaN\n"
     ]
    }
   ],
   "source": [
    "df=pd.read_csv('c:/data/ancova.csv')\n",
    "model=smf.ols(\"체중감소 ~ C(운동) + C(식단) + 초기체중\", data=df).fit()\n",
    "anova_table = sm.stats.anova_lm(model, typ=2)\n",
    "print(anova_table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da226e2d-46f4-40c6-9109-8d76a517a841",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5장 범주형 자료분석(Categorical data analysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c422214-81e9-471f-a411-04f5e3f849f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1131,
   "id": "e74a2e7c-fe2a-4e7d-851f-e666b21e0e56",
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import chisquare\n",
    "import numpy as np\n",
    "x=np.array([90,30,35,55,40])  # 관찰도수\n",
    "e_x=np.array([0.3,0.15,0.1,0.25,0.2])*250 # 기대도수"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1133,
   "id": "03f41648-76e2-4511-8b2a-2726368bfbfd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Power_divergenceResult(statistic=11.4, pvalue=0.02241796856505753)\n"
     ]
    }
   ],
   "source": [
    "print(chisquare(x,e_x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71913398-550f-4346-b04e-a1e1a62390ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1135,
   "id": "d5f95c61-5455-41b2-ae03-51e82fda7a6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "xf, xm=[269, 83, 215], [155, 57, 181]\n",
    "x=pd.DataFrame([xf, xm], columns=['상품A', '상품B', '상품C'],\n",
    "index=['Female', 'Male'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1137,
   "id": "cbf437db-5edc-4bce-b4cc-5eab72f0b9c6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>상품A</th>\n",
       "      <th>상품B</th>\n",
       "      <th>상품C</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Female</th>\n",
       "      <td>269</td>\n",
       "      <td>83</td>\n",
       "      <td>215</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Male</th>\n",
       "      <td>155</td>\n",
       "      <td>57</td>\n",
       "      <td>181</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        상품A  상품B  상품C\n",
       "Female  269   83  215\n",
       "Male    155   57  181"
      ]
     },
     "execution_count": 1137,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1139,
   "id": "53361fc4-9cb5-4f7e-9912-83ca813d9a15",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7.094264414804222 0.028807134195296135\n"
     ]
    }
   ],
   "source": [
    "from scipy.stats import chi2_contingency\n",
    "chi,p,df,expected=chi2_contingency(x,correction=False)\n",
    "# correction=False는 예이츠 연속성 보정을 적용하지 않도록 설정한 것이다.\n",
    "# 시험 문제에는 옵션 조건을 명시됨 \n",
    "print(chi,p)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc3aa040-0860-4075-8369-7d48db02206a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1141,
   "id": "8c5e2d30-1fed-4374-ac52-197f99bda40e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "time=np.tile([\"day\",\"evening\",\"night\"],2)\n",
    "count=np.array([905,890,870,45,55,70])\n",
    "goods=np.repeat([\"불량\",\"양호\"],3)\n",
    "data={\"time\":time,\"goods\":goods,\"count\":count}\n",
    "d_table=pd.crosstab(index=data[\"goods\"],columns=data[\"time\"],\n",
    "values=data[\"count\"],aggfunc='sum')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1143,
   "id": "f94a59a3-88c6-4664-aee3-5421998a99a9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>col_0</th>\n",
       "      <th>day</th>\n",
       "      <th>evening</th>\n",
       "      <th>night</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>row_0</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>불량</th>\n",
       "      <td>905</td>\n",
       "      <td>890</td>\n",
       "      <td>870</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>양호</th>\n",
       "      <td>45</td>\n",
       "      <td>55</td>\n",
       "      <td>70</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "col_0  day  evening  night\n",
       "row_0                     \n",
       "불량     905      890    870\n",
       "양호      45       55     70"
      ]
     },
     "execution_count": 1143,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d_table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1147,
   "id": "86f40ec5-2bef-4179-9bce-468898d99362",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Chi2ContingencyResult(statistic=6.233920047684764, pvalue=0.044291609404034316, dof=2, expected_freq=array([[893.0335097 , 888.33333333, 883.63315697],\n",
       "       [ 56.9664903 ,  56.66666667,  56.36684303]]))"
      ]
     },
     "execution_count": 1147,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from scipy.stats import chi2_contingency\n",
    "chi2_contingency(d_table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99815483-47b6-497c-8672-854167f11226",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 6장 다중회귀분석(Multiple Linear Regression)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1149,
   "id": "c7053a9c-dd10-494d-adc3-c1bc4ce17107",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제1 \n",
    "import pandas as pd\n",
    "import statsmodels.api as sm\n",
    "trees=sm.datasets.get_rdataset(\"trees\").data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1151,
   "id": "a3e8ed09-85f9-4b97-89b1-4a52882e789f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 31 entries, 0 to 30\n",
      "Data columns (total 3 columns):\n",
      " #   Column  Non-Null Count  Dtype  \n",
      "---  ------  --------------  -----  \n",
      " 0   Girth   31 non-null     float64\n",
      " 1   Height  31 non-null     int64  \n",
      " 2   Volume  31 non-null     float64\n",
      "dtypes: float64(2), int64(1)\n",
      "memory usage: 876.0 bytes\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(trees.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1153,
   "id": "e6307c4b-052d-4799-851a-d81e3f129441",
   "metadata": {},
   "outputs": [],
   "source": [
    "model=sm.formula.ols(formula='Volume ~ Girth + Height', \n",
    "data=trees).fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1155,
   "id": "6e0377bb-9210-4ffe-9174-1674b4f60cb3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                            OLS Regression Results                            \n",
      "==============================================================================\n",
      "Dep. Variable:                 Volume   R-squared:                       0.948\n",
      "Model:                            OLS   Adj. R-squared:                  0.944\n",
      "Method:                 Least Squares   F-statistic:                     255.0\n",
      "Date:                Mon, 01 Jun 2026   Prob (F-statistic):           1.07e-18\n",
      "Time:                        07:18:20   Log-Likelihood:                -84.455\n",
      "No. Observations:                  31   AIC:                             174.9\n",
      "Df Residuals:                      28   BIC:                             179.2\n",
      "Df Model:                           2                                         \n",
      "Covariance Type:            nonrobust                                         \n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "Intercept    -57.9877      8.638     -6.713      0.000     -75.682     -40.293\n",
      "Girth          4.7082      0.264     17.816      0.000       4.167       5.249\n",
      "Height         0.3393      0.130      2.607      0.014       0.073       0.606\n",
      "==============================================================================\n",
      "Omnibus:                        0.923   Durbin-Watson:                   1.266\n",
      "Prob(Omnibus):                  0.630   Jarque-Bera (JB):                0.950\n",
      "Skew:                           0.310   Prob(JB):                        0.622\n",
      "Kurtosis:                       2.408   Cond. No.                         959.\n",
      "==============================================================================\n",
      "\n",
      "Notes:\n",
      "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n"
     ]
    }
   ],
   "source": [
    "print(model.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69246752-8a18-4845-bdf7-2bdf9b0ba43f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1157,
   "id": "e1ca7576-b8ba-41c9-89f4-260c07a70fde",
   "metadata": {},
   "outputs": [],
   "source": [
    "new_data=pd.DataFrame({'Girth': [8.5, 13.0, 19.0],\n",
    "'Height': [72, 86, 85]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1159,
   "id": "426cc71d-3a69-4fd9-b87a-e945f5b5fb29",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0     6.457794\n",
      "1    32.394034\n",
      "2    60.303746\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "predictions=model.predict(new_data)\n",
    "print(predictions)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08877470-e150-43d4-b5ea-235ed912da93",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 7장 로지스틱 회귀분석(Logistic Regression)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1161,
   "id": "ea76d10b-d2cc-4177-b10f-2a7dc358776a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예제 1\n",
    "import statsmodels.api as sm\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1163,
   "id": "3b9ed662-d7bf-4f35-8d43-579416e0c44b",
   "metadata": {},
   "outputs": [],
   "source": [
    "mtcars=sm.datasets.get_rdataset('mtcars').data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1165,
   "id": "95796d4d-9644-41bc-9492-ebf32a48fddb",
   "metadata": {},
   "outputs": [],
   "source": [
    "glm_vs=sm.GLM(mtcars['vs'], sm.add_constant(mtcars[['mpg', 'am']]), \n",
    "family=sm.families.Binomial()).fit()\n",
    "# smf 방식\n",
    "# import statsmodels.formula.api as smf\n",
    "# glm_vs = smf.glm(\n",
    "#    formula='vs ~ mpg + am',\n",
    "#    data=mtcars,\n",
    "#    family=sm.families.Binomial()).fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1167,
   "id": "5b2e549f-0a43-42c7-a420-a58058467aa6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                 Generalized Linear Model Regression Results                  \n",
      "==============================================================================\n",
      "Dep. Variable:                     vs   No. Observations:                   32\n",
      "Model:                            GLM   Df Residuals:                       29\n",
      "Model Family:                Binomial   Df Model:                            2\n",
      "Link Function:                  Logit   Scale:                          1.0000\n",
      "Method:                          IRLS   Log-Likelihood:                -10.323\n",
      "Date:                Mon, 01 Jun 2026   Deviance:                       20.646\n",
      "Time:                        07:19:31   Pearson chi2:                     20.2\n",
      "No. Iterations:                     6   Pseudo R-squ. (CS):             0.5159\n",
      "Covariance Type:            nonrobust                                         \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const        -12.7051      4.625     -2.747      0.006     -21.770      -3.640\n",
      "mpg            0.6809      0.252      2.698      0.007       0.186       1.176\n",
      "am            -3.0073      1.599     -1.880      0.060      -6.142       0.128\n",
      "==============================================================================\n"
     ]
    }
   ],
   "source": [
    "print(glm_vs.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1169,
   "id": "795fee7f-6cfc-4462-93c5-3eacf501bbeb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.9756550218498166"
      ]
     },
     "execution_count": 1169,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "math.exp(0.6809)\n",
    "# import numpy as np\n",
    "# np.exp(0.6809)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1171,
   "id": "c0a595fe-a671-43a8-bf44-0d06028a8feb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.04942494612309506"
      ]
     },
     "execution_count": 1171,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "math.exp(-3.0073)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1173,
   "id": "1f0b7bde-07cd-438f-92a9-9833718544bb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.681"
      ]
     },
     "execution_count": 1173,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "round(glm_vs.params['mpg'], 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53da7b31-8aa8-4a17-a023-8dbeb1752086",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 8장 기출문제"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "905bc814-66c3-40fd-b450-84e7c1c85527",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(1) 위약 샘플 데이터가 ‘부작용 없음’인 데이터를 0~1 사이의 확률로 출력하시오. (반올림\n",
    "#하여 소수점 셋째 자리로 출력)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 491,
   "id": "731ac4d6-2c02-4dee-85a4-3ccd1caf667a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv('c:/data/cold.csv', encoding='euc-kr')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 493,
   "id": "2a460813-90d5-4af4-aa8f-4a13f5823746",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>코드</th>\n",
       "      <th>count</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4</td>\n",
       "      <td>199</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>24</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3</td>\n",
       "      <td>15</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   코드  count\n",
       "0   4    199\n",
       "1   2     24\n",
       "2   1     15\n",
       "3   3     15"
      ]
     },
     "execution_count": 493,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['코드'].value_counts().reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 495,
   "id": "077b556c-b827-4f3e-94d1-2183fd4ca549",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "코드\n",
       "4    0.786561\n",
       "2    0.094862\n",
       "1    0.059289\n",
       "3    0.059289\n",
       "Name: proportion, dtype: float64"
      ]
     },
     "execution_count": 495,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['코드'].value_counts(normalize=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 497,
   "id": "4cfd0122-5eea-4761-87fd-b2ab1ff09b65",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "253"
      ]
     },
     "execution_count": 497,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " len(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 499,
   "id": "49a996b1-3ae5-4a11-9efd-999e2181dbdd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.787\n"
     ]
    }
   ],
   "source": [
    "result=round(199 / 253, 3)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e9496bc-88d2-4652-89b4-ee6893806acf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) 카이제곱 검정을 수행하여 검정 통계량(Chi-square statistic)을 계산하고, 소수점 셋째 \n",
    "# 자리에서 반올림하여 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 501,
   "id": "c87cddbd-317d-4d20-8be0-1269bf67b4c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from scipy.stats import chisquare"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 503,
   "id": "38190a5e-1bb5-45cb-acba-0e6867f8932d",
   "metadata": {},
   "outputs": [],
   "source": [
    "observed_counts = np.array([15, 24, 15, 199])\n",
    "expected_proportions = np.array([0.05, 0.1, 0.05, 0.8])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 505,
   "id": "38f00ef7-4dc4-4d0f-8a92-14ed141385ef",
   "metadata": {},
   "outputs": [],
   "source": [
    "total_observed = np.sum(observed_counts)\n",
    "expected_proportions = expected_proportions * total_observed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 507,
   "id": "85ffe695-dd6e-4f54-b93c-aadfd29fd7ce",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Power_divergenceResult(statistic=0.9970355731225298, pvalue=0.801969260894451)"
      ]
     },
     "execution_count": 507,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chisquare(observed_counts, f_exp=expected_proportions)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 509,
   "id": "f3ecab99-a573-4c6a-8412-bcb66bfd3629",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.997\n"
     ]
    }
   ],
   "source": [
    "chi2_stat, p_val=chisquare(observed_counts, f_exp=expected_proportions)\n",
    "print(round(chi2_stat, 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea7c99f0-e7d9-4e44-b81a-80a8bb81cda5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (3) 카이제곱 검정을 수행한 후, 유의확률(p-value)을 소수점 셋째 자리에서 \n",
    "# 반올림하여 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 511,
   "id": "6708c749-e48b-46cf-9aa1-4ce48ae274dc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.802\n"
     ]
    }
   ],
   "source": [
    "print(round(p_val, 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d45bee1-6cd8-4d6f-a54a-81d9da0dba30",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 02 airquality 데이터에서 결측치를 제거한 후, 오존(Ozone), 일사량(Solar.R), 풍속(Wind) 변수를 사용하여 \n",
    "# 온도(Temp)를 예측하는 다중 선형 회귀 모델을 생성하시오.\n",
    "# (1)오존 농도(Ozone) 변수의 회귀 계수 추정값을 소수점 셋째 자리에서 반올림하여 출력하시오"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 513,
   "id": "6190dd40-926a-4066-90bd-7af679fe976d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Ozone      37\n",
       "Solar.R     7\n",
       "Wind        0\n",
       "Temp        0\n",
       "Month       0\n",
       "Day         0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 513,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "import statsmodels.api as sm\n",
    "import pandas as pd\n",
    "df=pd.read_csv(\"c:/data/airquality.csv\")\n",
    "df.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 515,
   "id": "bee4d891-07ae-4a00-8578-de0fac039ffe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 111 entries, 0 to 152\n",
      "Data columns (total 6 columns):\n",
      " #   Column   Non-Null Count  Dtype  \n",
      "---  ------   --------------  -----  \n",
      " 0   Ozone    111 non-null    float64\n",
      " 1   Solar.R  111 non-null    float64\n",
      " 2   Wind     111 non-null    float64\n",
      " 3   Temp     111 non-null    int64  \n",
      " 4   Month    111 non-null    int64  \n",
      " 5   Day      111 non-null    int64  \n",
      "dtypes: float64(3), int64(3)\n",
      "memory usage: 6.1 KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "df=df.dropna()\n",
    "print(df.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 517,
   "id": "b0830e4e-3345-4ed1-a40c-e63544c5b206",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=df[['Ozone', 'Solar.R', 'Wind']]\n",
    "y=df['Temp']\n",
    "model=LinearRegression().fit(X, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 519,
   "id": "7900e272-c4a7-4718-86ad-c2573df9ef15",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.17196604,  0.00727564, -0.32294455])"
      ]
     },
     "execution_count": 519,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " model.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 521,
   "id": "07b7d022-1b7c-4de7-b1ab-235e89c02e8e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.172\n"
     ]
    }
   ],
   "source": [
    "ozone_coef=round(model.coef_[0], 3)\n",
    "print(ozone_coef)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fc916fa-aeba-43ac-90fb-6c58131a9b4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(2)Solar.R과 Ozone을 고정한 상태에서 Wind가 증가할 때 Temp가 감소하는지 검증하기 \n",
    "#위해 다중 회귀 분석을 수행하고, Wind의 회귀 계수에 대한 p-value를 소수점 셋째 \n",
    "# 자리까지 반올림하여 구하시오(유의수준 0.05)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 523,
   "id": "16f6a73d-f456-491c-a788-c9da4c7b51ae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                            OLS Regression Results                            \n",
      "==============================================================================\n",
      "Dep. Variable:                   Temp   R-squared:                       0.500\n",
      "Model:                            OLS   Adj. R-squared:                  0.486\n",
      "Method:                 Least Squares   F-statistic:                     35.65\n",
      "Date:                Sun, 31 May 2026   Prob (F-statistic):           4.73e-16\n",
      "Time:                        18:15:27   Log-Likelihood:                -368.79\n",
      "No. Observations:                 111   AIC:                             745.6\n",
      "Df Residuals:                     107   BIC:                             756.4\n",
      "Df Model:                           3                                         \n",
      "Covariance Type:            nonrobust                                         \n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const         72.4186      3.216     22.522      0.000      66.044      78.793\n",
      "Ozone          0.1720      0.026      6.516      0.000       0.120       0.224\n",
      "Solar.R        0.0073      0.008      0.948      0.345      -0.008       0.022\n",
      "Wind          -0.3229      0.233     -1.384      0.169      -0.785       0.139\n",
      "==============================================================================\n",
      "Omnibus:                        6.409   Durbin-Watson:                   1.170\n",
      "Prob(Omnibus):                  0.041   Jarque-Bera (JB):                6.615\n",
      "Skew:                          -0.591   Prob(JB):                       0.0366\n",
      "Kurtosis:                       2.817   Cond. No.                     1.05e+03\n",
      "==============================================================================\n",
      "\n",
      "Notes:\n",
      "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n",
      "[2] The condition number is large, 1.05e+03. This might indicate that there are\n",
      "strong multicollinearity or other numerical problems.\n"
     ]
    }
   ],
   "source": [
    "X=df[['Ozone', 'Solar.R', 'Wind']]\n",
    "y=df['Temp']\n",
    "X=sm.add_constant(X)\n",
    "model=sm.OLS(y, X).fit()\n",
    "print(model.summary())\n",
    "wind_p_value=model.pvalues['Wind']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 525,
   "id": "1ad347d4-07f9-48a0-9a05-a7b94bd4d126",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.169\n"
     ]
    }
   ],
   "source": [
    "print(round(model.pvalues['Wind'], 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "816f47f4-bab3-48fa-8de0-f86b8a603c62",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (3) Ozone이 10, Solar.R이 90, Wind가 20일 때 온도(Temp)의 예측값을 소수점 셋째 자리까지 반올림하여 출력하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 527,
   "id": "31665df0-17ef-484a-969a-99a77e804b9a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "68.334\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "df1 = LinearRegression().fit(df[['Ozone', 'Solar.R', 'Wind']], \n",
    "df['Temp'])\n",
    "dd=pd.DataFrame({'Ozone': [10], 'Solar.R': [90], 'Wind': [20]})\n",
    "predictions = df1.predict(dd)\n",
    "print(round(predictions[0], 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a280c8d8-e13a-4d48-8f70-a748dd58f162",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 03. 이 데이터는 슈퍼마켓 몰(Mall)의 고객 정보를 포함하고 있으며, 마케팅 전략 수립에 활용될 예정이다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23ecbeea-07a2-4b09-836a-573e75bf19be",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(1)다중 로지스틱 회귀 분석을 수행하여 성별(Gender)을 예측하되, 패널티를 부과하지 않는다. \n",
    "# 독립 변수는 Annual Income, 종속 변수는 Gender(0=Female, 1=Male)로 설정하여 \n",
    "# 로지스틱 회귀 모델을 생성한다. 이때, Annual Income이 한 단위 증가할 때 1(Male)에 \n",
    "# 대한 오즈비(odds ratio) 값을 구하시오. (반올림하여 소수 넷째 자리까지 계산"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b117fa39-97c2-41cb-985f-971fefde8816",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "train=pd.read_csv(\"c:/data/train_logi.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "103ce737-d8e4-4fb0-b89d-ee327f1c7364",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Gender\n",
       "F    76\n",
       "M    64\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " train['Gender'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a3c279b1-28cb-45e3-ae94-ccc668444dab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 140 entries, 0 to 139\n",
      "Data columns (total 6 columns):\n",
      " #   Column                  Non-Null Count  Dtype \n",
      "---  ------                  --------------  ----- \n",
      " 0   Gender                  140 non-null    object\n",
      " 1   Age                     140 non-null    int64 \n",
      " 2   Education               140 non-null    object\n",
      " 3   Marital Status          140 non-null    object\n",
      " 4   Annual Income (k$)      140 non-null    int64 \n",
      " 5   Spending Score (1-100)  140 non-null    int64 \n",
      "dtypes: int64(3), object(3)\n",
      "memory usage: 6.7+ KB\n"
     ]
    }
   ],
   "source": [
    "train.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "056dc479-a965-4288-9856-917c66ed75ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "import statsmodels.api as sm\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ad497547-c573-49a5-9ce6-24c5ee05b6bc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Gender                    0\n",
       "Age                       0\n",
       "Education                 0\n",
       "Marital Status            0\n",
       "Annual Income (k$)        0\n",
       "Spending Score (1-100)    0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train.isna().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3842d926-eee9-4207-aab9-cd67b09faa02",
   "metadata": {},
   "outputs": [],
   "source": [
    "train['Gender']=train['Gender'].map({'F': 0, 'M': 1})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "338a6567-a559-4ac2-b63f-67004ebf4c7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=train[['Annual Income (k$)']]\n",
    "y=train['Gender']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c797cb38-709f-45b1-b4fb-0c630c684c7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=sm.add_constant(X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "44f9e918-0285-49e8-9c60-0548b9916398",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Optimization terminated successfully.\n",
      "         Current function value: 0.689250\n",
      "         Iterations 4\n"
     ]
    }
   ],
   "source": [
    "# 로지스틱 회귀 모델 적합\n",
    "logit_model=sm.Logit(y, X)\n",
    "result=logit_model.fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "f696ca58-ff31-4960-ad38-d7998a5b2403",
   "metadata": {},
   "outputs": [],
   "source": [
    "coef=result.params['Annual Income (k$)']\n",
    "# logit_model = smf.logit(\n",
    "#    formula='Gender ~ Q(\"Annual Income (k$)\")',\n",
    "#    data=train)\n",
    "#  result = logit_model.fit()\n",
    "#  coef = result.params['Q(\"Annual Income (k$)\")']\n",
    "# smf.logit()처럼 수식 기반 방식으로 작성하면 절편을 따로 추가할 필요가 없습니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c5a4eeeb-b6ce-42bb-aa08-e71c6c7a5eb9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0015480942626176727\n"
     ]
    }
   ],
   "source": [
    "print(coef)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "82a72ca0-5d4d-45a5-9825-37a55da9c42e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table class=\"simpletable\">\n",
       "<caption>Logit Regression Results</caption>\n",
       "<tr>\n",
       "  <th>Dep. Variable:</th>        <td>Gender</td>      <th>  No. Observations:  </th>  <td>   140</td>  \n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Model:</th>                 <td>Logit</td>      <th>  Df Residuals:      </th>  <td>   138</td>  \n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Method:</th>                 <td>MLE</td>       <th>  Df Model:          </th>  <td>     1</td>  \n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Date:</th>            <td>Wed, 03 Jun 2026</td> <th>  Pseudo R-squ.:     </th> <td>0.0003185</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Time:</th>                <td>15:53:50</td>     <th>  Log-Likelihood:    </th> <td> -96.495</td> \n",
       "</tr>\n",
       "<tr>\n",
       "  <th>converged:</th>             <td>True</td>       <th>  LL-Null:           </th> <td> -96.526</td> \n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Covariance Type:</th>     <td>nonrobust</td>    <th>  LLR p-value:       </th>  <td>0.8042</td>  \n",
       "</tr>\n",
       "</table>\n",
       "<table class=\"simpletable\">\n",
       "<tr>\n",
       "           <td></td>             <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n",
       "</tr>\n",
       "<tr>\n",
       "  <th>const</th>              <td>   -0.2653</td> <td>    0.413</td> <td>   -0.642</td> <td> 0.521</td> <td>   -1.076</td> <td>    0.545</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Annual Income (k$)</th> <td>    0.0015</td> <td>    0.006</td> <td>    0.248</td> <td> 0.804</td> <td>   -0.011</td> <td>    0.014</td>\n",
       "</tr>\n",
       "</table>"
      ],
      "text/latex": [
       "\\begin{center}\n",
       "\\begin{tabular}{lclc}\n",
       "\\toprule\n",
       "\\textbf{Dep. Variable:}      &      Gender      & \\textbf{  No. Observations:  } &      140    \\\\\n",
       "\\textbf{Model:}              &      Logit       & \\textbf{  Df Residuals:      } &      138    \\\\\n",
       "\\textbf{Method:}             &       MLE        & \\textbf{  Df Model:          } &        1    \\\\\n",
       "\\textbf{Date:}               & Wed, 03 Jun 2026 & \\textbf{  Pseudo R-squ.:     } & 0.0003185   \\\\\n",
       "\\textbf{Time:}               &     15:53:50     & \\textbf{  Log-Likelihood:    } &   -96.495   \\\\\n",
       "\\textbf{converged:}          &       True       & \\textbf{  LL-Null:           } &   -96.526   \\\\\n",
       "\\textbf{Covariance Type:}    &    nonrobust     & \\textbf{  LLR p-value:       } &   0.8042    \\\\\n",
       "\\bottomrule\n",
       "\\end{tabular}\n",
       "\\begin{tabular}{lcccccc}\n",
       "                             & \\textbf{coef} & \\textbf{std err} & \\textbf{z} & \\textbf{P$> |$z$|$} & \\textbf{[0.025} & \\textbf{0.975]}  \\\\\n",
       "\\midrule\n",
       "\\textbf{const}               &      -0.2653  &        0.413     &    -0.642  &         0.521        &       -1.076    &        0.545     \\\\\n",
       "\\textbf{Annual Income (k\\$)} &       0.0015  &        0.006     &     0.248  &         0.804        &       -0.011    &        0.014     \\\\\n",
       "\\bottomrule\n",
       "\\end{tabular}\n",
       "%\\caption{Logit Regression Results}\n",
       "\\end{center}"
      ],
      "text/plain": [
       "<class 'statsmodels.iolib.summary.Summary'>\n",
       "\"\"\"\n",
       "                           Logit Regression Results                           \n",
       "==============================================================================\n",
       "Dep. Variable:                 Gender   No. Observations:                  140\n",
       "Model:                          Logit   Df Residuals:                      138\n",
       "Method:                           MLE   Df Model:                            1\n",
       "Date:                Wed, 03 Jun 2026   Pseudo R-squ.:               0.0003185\n",
       "Time:                        15:53:50   Log-Likelihood:                -96.495\n",
       "converged:                       True   LL-Null:                       -96.526\n",
       "Covariance Type:            nonrobust   LLR p-value:                    0.8042\n",
       "======================================================================================\n",
       "                         coef    std err          z      P>|z|      [0.025      0.975]\n",
       "--------------------------------------------------------------------------------------\n",
       "const                 -0.2653      0.413     -0.642      0.521      -1.076       0.545\n",
       "Annual Income (k$)     0.0015      0.006      0.248      0.804      -0.011       0.014\n",
       "======================================================================================\n",
       "\"\"\""
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "7e2a596f-0a31-4b84-852e-00617c018934",
   "metadata": {},
   "outputs": [],
   "source": [
    "odds_ratio_exp=round(np.exp(coef), 4)\n",
    "# odds_ratio_exp=round(float(np.exp(coef)), 4)\n",
    "# float()는 NumPy의 실수형 값을 파이썬 기본 실수형으로 변환하여 출력 결과를 깔끔하게 만들기 위해 사용"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "1a749908-d816-43f9-aa38-89ff3d28a1dd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.0015\n"
     ]
    }
   ],
   "source": [
    "print(odds_ratio_exp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 885,
   "id": "f9903227-be44-4ab0-8072-4988a31bb0eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(2) Gender를 종속 변수로 하고, Age, Education, Marital Status, Annual Income (k$), \n",
    "#Spending Score (1-100)을 독립 변수로 설정하여 로지스틱 회귀 모델을 적합하시오. \n",
    "#모델 적합 후, 잔차 이탈도(residual deviance)를 계산하고, 소수점 둘째 자리까지 반올\n",
    "#림하여 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 949,
   "id": "f8b04940-d380-4e2b-a599-6b37be5ac67c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "import statsmodels.api as sm\n",
    "import numpy as np\n",
    "from sklearn.preprocessing import LabelEncoder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 951,
   "id": "5799d0d8-836a-45be-a63e-19d0e696428e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "train=pd.read_csv(\"c:/data/train_logi.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 953,
   "id": "776cbde7-64b1-4ce4-9ee7-9a76b4dd7a34",
   "metadata": {},
   "outputs": [],
   "source": [
    "train['Gender'] = train['Gender'].map({'F': 0, 'M': 1})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 955,
   "id": "f740d90f-5a06-427d-9688-a6ef8810e73e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['Gender', 'Age', 'Education ', 'Marital Status', 'Annual Income (k$)',\n",
       "       'Spending Score (1-100)'],\n",
       "      dtype='object')"
      ]
     },
     "execution_count": 955,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 957,
   "id": "36d4d19d-5c83-476b-a256-866e31b9b139",
   "metadata": {},
   "outputs": [],
   "source": [
    "X =train[['Age','Education ', 'Marital Status', 'Annual Income (k$)', 'Spending Score (1-100)']]\n",
    "y= train['Gender']\n",
    "#  'Education ' 컬럼명에 공백이 있음"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 933,
   "id": "3b9a3c3f-9396-43d2-b901-d34c96439ee5",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=pd.get_dummies(X, drop_first=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 917,
   "id": "b64378be-bd79-4db6-8d64-a4c0a9e888a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=X.astype(int)\n",
    "# get_dummies() 적용 후 생성된 더미변수가 bool 타입일 수 있으므로, statsmodels의 Logit 모델에 입력하기 \n",
    "# 위해 전체 X를 숫자형(float 또는 int)으로 변환한다.\n",
    "# X=X.astype(int) 사용하지 않고, X = pd.get_dummies(X, drop_first=True, dtype=int) 코딩을 하셔도 됩니다.\n",
    "# from sklearn.linear_model import LogisticRegression\n",
    "# X = pd.get_dummies(X, drop_first=True)\n",
    "# model = LogisticRegression()\n",
    "# model.fit(X, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 961,
   "id": "e8e0291b-ef8b-4e48-b891-14574b0968de",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=sm.add_constant(X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 963,
   "id": "06a1a5e3-fc8a-45a0-8a41-5d1985e15a96",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Optimization terminated successfully.\n",
      "         Current function value: 0.604820\n",
      "         Iterations 62\n"
     ]
    }
   ],
   "source": [
    "logit_model=sm.Logit(y, X)\n",
    "result=logit_model.fit(maxiter=100)  # 최대 반복 횟수 증가"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 965,
   "id": "14fcc43b-2f30-4729-9359-cd3eba893791",
   "metadata": {},
   "outputs": [],
   "source": [
    " residual_deviance=round(-2 * result.llf, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 967,
   "id": "8b52a5c5-9e20-4766-b1f3-efeb236f57ba",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "169.35\n"
     ]
    }
   ],
   "source": [
    " print(residual_deviance)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed8296cb-ae40-4794-a575-85a6f53f3736",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(3) Annual Income을 독립변수로, Gender를 종속변수로 설정하여 로지스틱 회귀 모델을 \n",
    "#생성하고, test 데이터의 Gender를 예측하여 Error Rate(오류율)를 구하시오(반올림하여 소수 세째 자리까지 계산)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 969,
   "id": "fe51314a-555f-4800-bdb5-0eeeecdf22b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import statsmodels.api as sm\n",
    "from sklearn.metrics import accuracy_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 971,
   "id": "cb6c2a8d-9f04-4ed0-a53d-d2dd05337dfa",
   "metadata": {},
   "outputs": [],
   "source": [
    "train=pd.read_csv(\"c:/data/train_logi.csv\")\n",
    "test=pd.read_csv(\"c:/data/test_logi.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 973,
   "id": "36e106bc-3b35-41c7-8b70-c00628502a10",
   "metadata": {},
   "outputs": [],
   "source": [
    "train['Gender']=train['Gender'].map({'F': 0, 'M': 1})\n",
    "test['Gender']=test['Gender'].map({'F': 0, 'M': 1})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 975,
   "id": "26b7c4f8-cb15-4507-b031-508e8f8cb6ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train=train[['Annual Income (k$)']]\n",
    "y_train=train['Gender']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 977,
   "id": "816727a5-0d29-442f-95db-bdab5be0e4d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_test=test[['Annual Income (k$)']]\n",
    "y_test=test['Gender']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 979,
   "id": "5b6f0313-6c2e-47ba-879a-ae4d308d2242",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train=sm.add_constant(X_train)\n",
    "X_test=sm.add_constant(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 981,
   "id": "811a272d-3d87-462b-9fa9-a0dd632ef52d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Optimization terminated successfully.\n",
      "         Current function value: 0.689250\n",
      "         Iterations 4\n"
     ]
    }
   ],
   "source": [
    "logit_model=sm.Logit(y_train, X_train)\n",
    "result=logit_model.fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 983,
   "id": "7f7736bd-f77b-4f78-9bd1-4efe12e39925",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred_prob=result.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 985,
   "id": "61777972-a2d6-4c93-be97-25d326d9f5de",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred=(y_pred_prob >= 0.5).astype(int)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 987,
   "id": "ea869026-5c45-42f9-8455-5e6df9ec574a",
   "metadata": {},
   "outputs": [],
   "source": [
    "error_rate=round(1 - accuracy_score(y_test, y_pred), 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 989,
   "id": "1a34aa43-8fd7-47f2-9840-81225d2c1f09",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.4\n"
     ]
    }
   ],
   "source": [
    "print(error_rate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e45ca80-d8ac-40be-aacc-b745c953b6f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 04. Advertising 데이터셋은 TV, 라디오, 신문 광고비를 바탕으로 매출(Sales)을 예측하는 데 사용\n",
    "# 되는 데이터이다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "498ae2fb-9b43-4a28-ab35-36a5a62252a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (1)Sales와 가장 상관관계가 높은 값을 구하시오(반올림하여 소수 셋째 자리까지 계산)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 991,
   "id": "c3253fcf-acb1-4dd1-a4ac-f9109ac8d8f3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 200 entries, 0 to 199\n",
      "Data columns (total 4 columns):\n",
      " #   Column                   Non-Null Count  Dtype  \n",
      "---  ------                   --------------  -----  \n",
      " 0   TV Ad Budget ($)         200 non-null    float64\n",
      " 1   Radio Ad Budget ($)      200 non-null    float64\n",
      " 2   Newspaper Ad Budget ($)  200 non-null    float64\n",
      " 3   Sales                    200 non-null    float64\n",
      "dtypes: float64(4)\n",
      "memory usage: 6.4 KB\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv(\"c:/data/7_type3_2.csv\")\n",
    "df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 993,
   "id": "d05d06c7-fecb-47cf-92e1-137853a77109",
   "metadata": {},
   "outputs": [],
   "source": [
    "corr_matrix=df.corr()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 995,
   "id": "e4b30afc-004d-4707-b964-110e1162f117",
   "metadata": {},
   "outputs": [],
   "source": [
    "highest_corr_value=corr_matrix[\"Sales\"].drop(\"Sales\").abs().max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 997,
   "id": "94a22ebc-1a38-4802-9594-8ba863c9c6f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "highest_corr_value_rounded=round(highest_corr_value, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 999,
   "id": "5aab46f7-c317-4d22-a121-ae7a5d6a7290",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.782\n"
     ]
    }
   ],
   "source": [
    "print(highest_corr_value_rounded)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dffdf1df-7c95-44b9-a7f7-1a8cbe8979b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) Radio Ad Budget ($) 컬럼 값이 23 미만인 데이터를 찾아, Sales를 종속 변수로, 나머지 \n",
    "# 변수들을 독립 변수로 설정하여 선형 회귀 모델을 생성하고, 결정 계수를 구하시오. (반\n",
    "# 올림하여 소수 셋째 자리까지 계산)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1001,
   "id": "fb8b9749-b71d-4384-b6e0-1416e42b95f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import statsmodels.api as sm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1003,
   "id": "21e1ef31-bd11-4964-afce-cd1516011287",
   "metadata": {},
   "outputs": [],
   "source": [
    " filtered_df=df[df[\"Radio Ad Budget ($)\"] < 23]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1005,
   "id": "545f17cd-bc28-4b69-b765-a061d55b79bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "y=filtered_df[\"Sales\"]\n",
    "X=filtered_df.drop(columns=[\"Sales\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1007,
   "id": "1f524a1e-cc9e-4696-92e7-f60036d50f6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=sm.add_constant(X)\n",
    "model=sm.OLS(y, X).fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1009,
   "id": "4895a714-494e-4ece-acb8-c98ac7eb6e67",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.884\n"
     ]
    }
   ],
   "source": [
    "r_squared=round(model.rsquared, 3)\n",
    "print(r_squared)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc470db9-9a7f-42e2-9a13-49be9469577e",
   "metadata": {},
   "outputs": [],
   "source": [
    "#import pandas as pd\n",
    "#import statsmodels.formula.api as smf\n",
    "\n",
    "#filtered_df = df[df[\"Radio Ad Budget ($)\"] < 23]\n",
    "\n",
    "#model = smf.ols(\n",
    "#    formula='Sales ~ Q(\"TV Ad Budget ($)\") + Q(\"Radio Ad Budget ($)\") + Q(\"Newspaper Ad Budget ($)\")',\n",
    "#    data=filtered_df.fit()\n",
    "#r_squared = round(model.rsquared, 3)\n",
    "#print(r_squared)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da478352-b496-4dd0-ae53-19b8e8473b37",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (3) 문제 (2)에서 만든 모델에서 독립변수 중 p-value가 가장 높은 값을 구하시오(반올림하여 \n",
    "# 소수 셋째 자리까지 계산)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1011,
   "id": "e9695065-27b2-4dc1-8bbb-4d64c9e4c737",
   "metadata": {},
   "outputs": [],
   "source": [
    "highest_p_value=round(model.pvalues.drop(\"const\").max(), 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1013,
   "id": "d9bb2a9e-5457-4b58-b265-355baeba8faf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.397\n"
     ]
    }
   ],
   "source": [
    " print(highest_p_value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e58f5372-20a8-429f-a648-606addecfefc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 05 이 데이터는 고객 이탈 여부를 예측하기 위해 로지스틱 회귀분석에 활용된다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4767cb76-7766-448f-979b-063c3668f69b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (1)로지스틱 회귀분석을 수행하여 유의확률(p-value)이 0.05 이상인 유의하지 않은 독립 \n",
    "# 변수의 개수를 구하시오."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1015,
   "id": "a7aea69c-cd32-4450-8261-8343d449da9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "df=pd.read_csv(\"c:/data/churn.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1017,
   "id": "fe5a3ecc-3b87-44c8-951e-5fd1d1fbedc8",
   "metadata": {},
   "outputs": [],
   "source": [
    " import statsmodels.api as sm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1019,
   "id": "2357e0a3-57e6-40d1-ab36-e2079049470f",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=df.drop(columns=['Churn'])\n",
    "y=df['Churn']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1021,
   "id": "127855be-10d7-4fff-8b0f-2a6368829fc1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Optimization terminated successfully.\n",
      "         Current function value: 0.393603\n",
      "         Iterations 6\n"
     ]
    }
   ],
   "source": [
    "X=sm.add_constant(X)\n",
    "logit_model=sm.Logit(y, X)\n",
    "result=logit_model.fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1023,
   "id": "aea73423-8df5-4c3f-95c9-5d7b10de6dd2",
   "metadata": {},
   "outputs": [],
   "source": [
    "p_values=result.pvalues"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1025,
   "id": "a7e4844c-e3f2-4905-a6fd-690ff7eac41e",
   "metadata": {},
   "outputs": [],
   "source": [
    "insignificant_count=(p_values >= 0.05).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1027,
   "id": "8309b083-b50e-48ab-a43b-e8bdcf6ffb2e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n"
     ]
    }
   ],
   "source": [
    "print(insignificant_count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a67c32e-10aa-4728-998c-df493a859e6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) 유의확률(p-value)이 0.05미만인 유의한 변수만을 사용해 로지스틱 회귀분석을 수행하시오. \n",
    "# 회귀식의 유의한 회귀계수(상수항 포함)의 합계를 구하시오.(반올림하여 소수 셋째 자리까지 계산)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1029,
   "id": "0fd29614-a882-4c22-a713-c7d1779f4d77",
   "metadata": {},
   "outputs": [],
   "source": [
    "significant_vars = p_values[p_values < 0.05].index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1031,
   "id": "21f29420-50ff-4b36-931c-2472170b5e0e",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_significant = X[significant_vars]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1033,
   "id": "d3d66161-8029-470f-9cff-a69775c891f8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Optimization terminated successfully.\n",
      "         Current function value: 0.397599\n",
      "         Iterations 6\n"
     ]
    }
   ],
   "source": [
    "logit_model_sig = sm.Logit(y, X_significant)\n",
    "result_sig = logit_model_sig.fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1035,
   "id": "59ba4620-7cf6-4aaa-b785-fa3e1e4894ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "significant_coef_sum = round(result_sig.params.sum(), 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1037,
   "id": "50f340ea-7495-40ce-9abb-157e96e0ff16",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-1.213\n"
     ]
    }
   ],
   "source": [
    " print(significant_coef_sum)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84cbe808-82fa-42a6-90f3-3163375078c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "#(3)5-1에 수행한 로지스틱 회귀식에서 'DataUsage'변수가 5만큼 증가할 때 오즈비(Odds Ratio)를 \n",
    "# 구하시오(반올림하여 소수 셋째 자리까지 계산)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1039,
   "id": "6f66f9a3-92bb-4e17-a9f5-b8f9c0bfa841",
   "metadata": {},
   "outputs": [],
   "source": [
    " datausage_coef = result_sig.params.get('DataUsage', None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1041,
   "id": "52cc7810-ca2f-498d-8d7c-43ee84b16e3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1043,
   "id": "a9d5445a-9a8e-42a8-8193-e1e7e7ff19bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "if 'DataUsage' in result_sig.params:\n",
    "    odds_ratio_rounded = round(np.exp(result_sig.params['DataUsage'] * 5), 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1045,
   "id": "24ea2887-09b0-4da6-a706-30c154181180",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.428\n"
     ]
    }
   ],
   "source": [
    "print(odds_ratio_rounded)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d56c9429-124c-4f0d-871d-5bfc7edfb467",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 06. 이 데이터는  PIQ(Performance IQ,성취 지능지수)에 관한 데이터를 포함하고 있다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "377eaf71-e27e-4c1c-96b9-eeccde87495c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (1)주어진 데이터를 이용해 종속 변수(PIQ)와 독립 변수(Brain, Height, Weight)로 다중 선형 \n",
    "# 회귀분석을 수행하고, 유의확률(p-value)이 가장 작은 변수의 회귀 계수 값을 구하시오. \n",
    "# (반올림하여 소수 셋째 자리까지 계산)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1047,
   "id": "a30a8d01-12a3-495e-8b34-a585c859b2b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import statsmodels.api as sm\n",
    "# PIQ(Performance IQ) 데이터 로드\n",
    "df = pd.read_csv(\"c:/data/piq.csv\")\n",
    "# 독립 변수(Brain, Height, Weight), 종속 변수(PIQ) 분리\n",
    "X = df[['Brain', 'Height', 'Weight']]\n",
    "y = df['PIQ']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1049,
   "id": "7c481d8e-69bb-4ea4-be92-a05f87b1ec56",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=sm.add_constant(X)\n",
    "model=sm.OLS(y, X)\n",
    "result=model.fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1053,
   "id": "4ffc7722-832e-494f-8f12-bf43ad7638f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "p_values=result.pvalues.drop('const', errors='ignore')\n",
    "# const가 반드시 존재한다는 확신이 있으면 errors 옵션을 사용하지 않아도 됨\n",
    "min_p_value_var=p_values.idxmin()\n",
    "# idxmin() 메서드는 Series에서 최솟값을 갖는 인덱스 이름을 반환"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1055,
   "id": "7a558678-b7cd-4d69-a24a-8ebdc7d3ee9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "min_p_value_coef=round(result.params[min_p_value_var], 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1057,
   "id": "435fbc05-8ce4-43cd-a940-f831cd8767b6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.343\n"
     ]
    }
   ],
   "source": [
    "print(min_p_value_coef)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f95b198e-4a88-45d3-8b9f-06699a312e2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (2) 적합된 모델의 결정 계수 값을 구하시오. (반올림하여 소수 둘째 자리까지 계산)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1059,
   "id": "4e2c6ea1-5e4a-41ad-a7bc-33df0a5e9630",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.37\n"
     ]
    }
   ],
   "source": [
    "r_squared = round(result.rsquared, 2)\n",
    "print(r_squared)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57c7d930-bf9e-4679-9e0d-da0003366300",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3) 뇌크기(Brain)가 90, 키(Height)가 70, 몸무게(Weight)가 150일 때의 PIQ를 예측하시오(반올림하여 정수로 계산).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1061,
   "id": "cbaedf93-3447-4a00-911f-7b08b8fceeea",
   "metadata": {},
   "outputs": [],
   "source": [
    " new_data = pd.DataFrame({\n",
    "'const': [1],\n",
    "'Brain': [90],\n",
    "'Height': [70],\n",
    "'Weight': [150]\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1063,
   "id": "0c99d6bd-343f-4ceb-871d-5a5327b2b82d",
   "metadata": {},
   "outputs": [],
   "source": [
    "predicted_piq = result.predict(new_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1065,
   "id": "7b8b7219-ea15-4aa6-8ef9-42a87ff950e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "106\n"
     ]
    }
   ],
   "source": [
    "predicted_piq_rounded = round(predicted_piq.values[0])\n",
    "print(predicted_piq_rounded)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41346eb1-6f14-4f4e-93db-51737429e8e8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:base] *",
   "language": "python",
   "name": "conda-base-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
