{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "0170be5e-5bb1-4ff0-975b-2b6d053d9821", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": 2, "id": "2d38887d-fe19-418f-92cf-e99f5e314b2f", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
\n", "
" ], "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": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_df = pd.read_csv('C:/Users/niceq/Documents/DataScience/Python ML Guide/Data/01. titanic_train.csv')\n", "titanic_df.head(3) #파일이 잘 불러왔는지 확인" ] }, { "cell_type": "code", "execution_count": 12, "id": "068b6bda-6a97-40de-9906-762f0c80464a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DataFrame 크기: (891, 12)\n" ] } ], "source": [ "print('DataFrame 크기:', titanic_df.shape)" ] }, { "cell_type": "code", "execution_count": 13, "id": "2153d383-1795-44da-8850-412f62bad9db", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\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_df.info()" ] }, { "cell_type": "code", "execution_count": 14, "id": "e69e3a86-f07e-4d06-a106-9aee04240682", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassAgeSibSpParchFare
count891.000000891.000000891.000000714.000000891.000000891.000000891.000000
mean446.0000000.3838382.30864229.6991180.5230080.38159432.204208
std257.3538420.4865920.83607114.5264971.1027430.80605749.693429
min1.0000000.0000001.0000000.4200000.0000000.0000000.000000
25%223.5000000.0000002.00000020.1250000.0000000.0000007.910400
50%446.0000000.0000003.00000028.0000000.0000000.00000014.454200
75%668.5000001.0000003.00000038.0000001.0000000.00000031.000000
max891.0000001.0000003.00000080.0000008.0000006.000000512.329200
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Age SibSp \\\n", "count 891.000000 891.000000 891.000000 714.000000 891.000000 \n", "mean 446.000000 0.383838 2.308642 29.699118 0.523008 \n", "std 257.353842 0.486592 0.836071 14.526497 1.102743 \n", "min 1.000000 0.000000 1.000000 0.420000 0.000000 \n", "25% 223.500000 0.000000 2.000000 20.125000 0.000000 \n", "50% 446.000000 0.000000 3.000000 28.000000 0.000000 \n", "75% 668.500000 1.000000 3.000000 38.000000 1.000000 \n", "max 891.000000 1.000000 3.000000 80.000000 8.000000 \n", "\n", " Parch Fare \n", "count 891.000000 891.000000 \n", "mean 0.381594 32.204208 \n", "std 0.806057 49.693429 \n", "min 0.000000 0.000000 \n", "25% 0.000000 7.910400 \n", "50% 0.000000 14.454200 \n", "75% 0.000000 31.000000 \n", "max 6.000000 512.329200 " ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_df.describe()" ] }, { "cell_type": "code", "execution_count": 16, "id": "013d22c3-438c-4cba-8dea-97b123b0c52f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "titanic_pclass = titanic_df['Pclass']\n", "print(type(titanic_pclass))" ] }, { "cell_type": "code", "execution_count": 17, "id": "0ca82993-ff03-440a-bfb4-d699d0d726a5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 3\n", "1 1\n", "2 3\n", "3 1\n", "4 3\n", "Name: Pclass, dtype: int64" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_pclass.head()" ] }, { "cell_type": "code", "execution_count": 15, "id": "80ac349f-f0f4-4522-908d-afb2caf4c7f1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Pclass\n", "3 491\n", "1 216\n", "2 184\n", "Name: count, dtype: int64\n" ] } ], "source": [ "value_counts = titanic_df['Pclass'].value_counts()\n", "print(value_counts)" ] }, { "cell_type": "code", "execution_count": 18, "id": "7d7919d2-6446-4f41-a8d6-20eea9ac6c3a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Pclass\n", "3 491\n", "1 216\n", "2 184\n", "Name: count, dtype: int64\n" ] } ], "source": [ "value_counts = titanic_df['Pclass'].value_counts()\n", "print(type(value_counts))\n", "print(value_counts)" ] }, { "cell_type": "code", "execution_count": 19, "id": "bccafb45-0f99-4877-ac2c-f2a8d32b1ea1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "titanic_df 데이터 건수: 891\n", "기본 설정인 dropna=True로 value_counts()\n", "Embarked\n", "S 644\n", "C 168\n", "Q 77\n", "Name: count, dtype: int64\n", "Embarked\n", "S 644\n", "C 168\n", "Q 77\n", "NaN 2\n", "Name: count, dtype: int64\n" ] } ], "source": [ "print('titanic_df 데이터 건수:', titanic_df.shape[0])\n", "print('기본 설정인 dropna=True로 value_counts()')\n", "\n", "#value_counts()는 기본값으로 dropna=True 이므로 value_counts(dropna=True)와 동일\n", "print(titanic_df['Embarked'].value_counts())\n", "print(titanic_df['Embarked'].value_counts(dropna=False))" ] }, { "cell_type": "code", "execution_count": 21, "id": "984e938b-9be9-41b8-8fb3-064f11e0a9de", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "array1 shape: (3,)\n", "1차원 리스트로 만든 DataFrame:\n", " col1\n", "0 1\n", "1 2\n", "2 3\n", "1차원 ndarray로 만든 DataFrame:\n", " col1\n", "0 1\n", "1 2\n", "2 3\n" ] } ], "source": [ "col_name1=['col1'] #col1 생성\n", "list1 = [1, 2, 3] #리스트 생성\n", "array1 = np.array(list1) #리스트 배열\n", "print('array1 shape:', array1.shape) #array1 형태 표시\n", "#리스트를 이용해 DataFrame 생성\n", "df_list1 = pd.DataFrame(list1, columns=col_name1)\n", "print('1차원 리스트로 만든 DataFrame:\\n', df_list1)\n", "#넘파이 ndarray를 이용해 DataFrame 생성\n", "df_array1 = pd.DataFrame(array1, columns=col_name1)\n", "print('1차원 ndarray로 만든 DataFrame:\\n', df_array1)" ] }, { "cell_type": "code", "execution_count": 22, "id": "2cb03a97-c2d4-482c-9bbe-f67df596288a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "array2 shape: (2, 3)\n", "2차원 리스트로 만든 DataFrame:\n", " col1 col2 col3\n", "0 1 2 3\n", "1 11 12 13\n", "2차원 ndarray로 만든 DataFrame:\n", " col1 col2 col3\n", "0 1 2 3\n", "1 11 12 13\n" ] } ], "source": [ "#3개의 칼럼명 필요\n", "col_name2=['col1', 'col2', 'col3']\n", "\n", "#2행x3열 형태의 리스트와 ndarray 생성한 뒤 이를 DataFrame으로 변환\n", "list2 = [[1, 2, 3],\n", " [11, 12, 13]]\n", "array2 = np.array(list2)\n", "print('array2 shape:', array2.shape)\n", "df_list2 = pd.DataFrame(list2, columns=col_name2)\n", "print('2차원 리스트로 만든 DataFrame:\\n', df_list2)\n", "#넘파이 ndarray를 이용해 DataFrame 생성\n", "df_array2 = pd.DataFrame(array2, columns=col_name2)\n", "print('2차원 ndarray로 만든 DataFrame:\\n', df_array2)" ] }, { "cell_type": "code", "execution_count": 23, "id": "48a6caaa-496d-4413-ac9f-7aec5dabb7b6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "딕셔너리로 만든 DataFrame:\n", " col1 col2 col3\n", "0 1 2 3\n", "1 11 22 33\n" ] } ], "source": [ "# Key는 문자열 칼럼명으로 매핑, Value는 리스트 형 (또는 ndarray) 칼럼 데이터로 매핑\n", "dict = {'col1':[1,11], 'col2':[2, 22], 'col3':[3, 33]} #딕셔너리 생성\n", "df_dict = pd.DataFrame(dict) # 딕셔너리를 DataFrame으로 변환\n", "print('딕셔너리로 만든 DataFrame:\\n', df_dict)" ] }, { "cell_type": "code", "execution_count": 24, "id": "c7603824-5770-403d-b51a-1ea402323dd6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "df_dict.values 타입: df_dict.values shape: (2, 3)\n", "[[ 1 2 3]\n", " [11 22 33]]\n" ] } ], "source": [ "#DataFrame을 ndarray로 변환\n", "array3 = df_dict.values #values를 이용하여 ndarray로 변환\n", "print('df_dict.values 타입:', type(array3), 'df_dict.values shape:', array3.shape)\n", "print(array3)" ] }, { "cell_type": "code", "execution_count": 26, "id": "e18dda42-d2ca-46ca-b862-bbcf1674cb45", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "df_dict.values.tolist() 타입: \n", "[[1, 2, 3], [11, 22, 33]]\n", "\n", " df_dict.to.dict() 타입: \n", "{'col1': [1, 11], 'col2': [2, 22], 'col3': [3, 33]}\n" ] } ], "source": [ "#DataFrame을 리스트로 변환\n", "list3 = df_dict.values.tolist()\n", "print('df_dict.values.tolist() 타입:', type(list3))\n", "print(list3)\n", "\n", "#DataFrame을 딕셔너리로 변환\n", "dict3 = df_dict.to_dict('list')\n", "print('\\n df_dict.to.dict() 타입:', type(dict3))\n", "print(dict3)" ] }, { "cell_type": "code", "execution_count": 27, "id": "22cb20b9-491b-475b-b0f4-d59cf6f2b905", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedAge_0
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS0
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C0
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS0
\n", "
" ], "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 Age_0 \n", "0 0 A/5 21171 7.2500 NaN S 0 \n", "1 0 PC 17599 71.2833 C85 C 0 \n", "2 0 STON/O2. 3101282 7.9250 NaN S 0 " ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 타이타닉 칼럼 생성 및 값 할당\n", "titanic_df['Age_0']=0 #Age_0 이라는 칼럼 생성(값은 모두 0)\n", "titanic_df.head(3)" ] }, { "cell_type": "code", "execution_count": 29, "id": "37cc3680-7e70-4c36-94d5-5a281b485fff", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedAge_0Age_by_10Family_No
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS0220.02
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C0380.02
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS0260.01
\n", "
" ], "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 Age_0 Age_by_10 \\\n", "0 0 A/5 21171 7.2500 NaN S 0 220.0 \n", "1 0 PC 17599 71.2833 C85 C 0 380.0 \n", "2 0 STON/O2. 3101282 7.9250 NaN S 0 260.0 \n", "\n", " Family_No \n", "0 2 \n", "1 2 \n", "2 1 " ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 기존 칼럼 Series의 데이터 이용해 새로운 칼럼 Series 만들기\n", "titanic_df['Age_by_10'] = titanic_df['Age']*10\n", "titanic_df['Family_No'] = titanic_df['SibSp'] + titanic_df['Parch']+1\n", "titanic_df.head(3)" ] }, { "cell_type": "code", "execution_count": 30, "id": "46522785-fcce-4809-8d48-d7f2222cc364", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedAge_0Age_by_10Family_No
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS0320.02
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C0480.02
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS0360.01
\n", "
" ], "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 Age_0 Age_by_10 \\\n", "0 0 A/5 21171 7.2500 NaN S 0 320.0 \n", "1 0 PC 17599 71.2833 C85 C 0 480.0 \n", "2 0 STON/O2. 3101282 7.9250 NaN S 0 360.0 \n", "\n", " Family_No \n", "0 2 \n", "1 2 \n", "2 1 " ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Age_by_10 칼럼 값 업데이트 하기 (일괄적으로 100 추가)\n", "titanic_df['Age_by_10'] = titanic_df['Age_by_10']+100\n", "titanic_df.head(3)" ] }, { "cell_type": "code", "execution_count": 31, "id": "77459e81-5abf-4b44-937c-342678b3c5f0", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedAge_by_10Family_No
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS320.02
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C480.02
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS360.01
\n", "
" ], "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 Age_by_10 Family_No \n", "0 0 A/5 21171 7.2500 NaN S 320.0 2 \n", "1 0 PC 17599 71.2833 C85 C 480.0 2 \n", "2 0 STON/O2. 3101282 7.9250 NaN S 360.0 1 " ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 'Age_0' 칼럼 삭제하기\n", "titanic_drop_df = titanic_df.drop('Age_0', axis=1) #axis=1은 칼럼 방향\n", "titanic_drop_df.head(3)" ] }, { "cell_type": "code", "execution_count": 32, "id": "a1084969-04cd-448e-bc39-17721bd2fb96", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedAge_0Age_by_10Family_No
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS0320.02
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C0480.02
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS0360.01
\n", "
" ], "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 Age_0 Age_by_10 \\\n", "0 0 A/5 21171 7.2500 NaN S 0 320.0 \n", "1 0 PC 17599 71.2833 C85 C 0 480.0 \n", "2 0 STON/O2. 3101282 7.9250 NaN S 0 360.0 \n", "\n", " Family_No \n", "0 2 \n", "1 2 \n", "2 1 " ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_df.head(3)" ] }, { "cell_type": "code", "execution_count": 34, "id": "a9f08d84-cca0-4b93-bf5a-3ee2948e61a1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "inplace=True로 drop 후 반환된 값: None\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
\n", "
" ], "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": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#여러 개의 칼럼 삭제하기\n", "drop_result = titanic_df.drop(['Age_0', 'Age_by_10', 'Family_No'], axis=1, inplace=True)\n", "print('inplace=True로 drop 후 반환된 값:', drop_result)\n", "titanic_df.head(3)" ] }, { "cell_type": "code", "execution_count": 35, "id": "e9d87cfd-2ad4-4a6d-9557-016e81df1019", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "### before axis 0 drop ###\n", " PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n", "0 1 0 3 Braund, Mr.... male 22.0 1 0 A/5 21171 7.2500 NaN S\n", "1 2 1 1 Cumings, Mr... female 38.0 1 0 PC 17599 71.2833 C85 C\n", "2 3 1 3 Heikkinen, ... female 26.0 0 0 STON/O2. 31... 7.9250 NaN S\n", "### after axis 0 drop ###\n", " PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n", "3 4 1 1 Futrelle, M... female 35.0 1 0 113803 53.1000 C123 S\n", "4 5 0 3 Allen, Mr. ... male 35.0 0 0 373450 8.0500 NaN S\n", "5 6 0 3 Moran, Mr. ... male NaN 0 0 330877 8.4583 NaN Q\n" ] } ], "source": [ "# 로우 삭제하기\n", "pd.set_option('display.width', 1000) #DataFrame을 출력할 때 사용되는 콘솔 창의 최대 너비를 1000으로 설정\n", "pd.set_option('display.max_colwidth', 15) #DataFrame을 출력할 때 각 열에 표시되는 최대 문자열 길이를 15자로 설정\n", "print('### before axis 0 drop ###')\n", "print(titanic_df.head(3))\n", "\n", "titanic_df.drop([0, 1, 2], axis=0, inplace=True)\n", "\n", "print('### after axis 0 drop ###')\n", "print(titanic_df.head(3))" ] }, { "cell_type": "code", "execution_count": 3, "id": "99380768-5e6e-434a-ab25-1fd485d832de", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
\n", "
" ], "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": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 기존 데이터가 삭제되었으므로, 원본 데이터 로딩\n", "titanic_df = pd.read_csv('C:/Users/niceq/Documents/DataScience/Python ML Guide/Data/01. titanic_train.csv')\n", "titanic_df.head(3) #파일이 잘 불러왔는지 확인" ] }, { "cell_type": "code", "execution_count": 37, "id": "32577b47-fc42-431e-afae-82e5d0e2ab3b", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "RangeIndex(start=0, stop=891, step=1)\n", "Index 객체 array 값:\n", " [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17\n", " 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35\n", " 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53\n", " 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71\n", " 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89\n", " 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107\n", " 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125\n", " 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143\n", " 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161\n", " 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179\n", " 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197\n", " 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215\n", " 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233\n", " 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251\n", " 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269\n", " 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287\n", " 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305\n", " 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323\n", " 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341\n", " 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359\n", " 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377\n", " 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395\n", " 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413\n", " 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431\n", " 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449\n", " 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467\n", " 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485\n", " 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503\n", " 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521\n", " 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539\n", " 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557\n", " 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575\n", " 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593\n", " 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611\n", " 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629\n", " 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647\n", " 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665\n", " 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683\n", " 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701\n", " 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719\n", " 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737\n", " 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755\n", " 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773\n", " 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791\n", " 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809\n", " 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827\n", " 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845\n", " 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863\n", " 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881\n", " 882 883 884 885 886 887 888 889 890]\n" ] } ], "source": [ "# Index 객체 추출\n", "indexes = titanic_df.index\n", "print(indexes)\n", "\n", "#index 객체를 실제 값 array로 변환\n", "print('Index 객체 array 값:\\n', indexes.values)" ] }, { "cell_type": "code", "execution_count": 38, "id": "a8ac9e1e-517d-49d7-9205-b4721de50439", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "(891,)\n", "[0 1 2 3 4]\n", "[0 1 2 3 4]\n", "6\n" ] } ], "source": [ "print(type(indexes.values)) #indexes.values의 데이터 타입을 출력. values 속성은 인덱스의 값을 NumPy 배열로 반환.\n", "print(indexes.values.shape) #indexes.values의 형태(차원과 크기)를 출력\n", "print(indexes[:5].values) #인덱스의 첫 5개의 값을 NumPy 배열로 출력\n", "print(indexes.values[:5]) #indexes.values 배열의 첫 5개의 값을 출력\n", "print(indexes[6]) #인덱스의 7번째 요소를 출력" ] }, { "cell_type": "code", "execution_count": 39, "id": "c1b4af97-444b-43dd-ad90-177865a73e49", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "Index does not support mutable operations", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[39], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# 한 번 만들어진 인덱스는 변경 불가\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m indexes[\u001b[38;5;241m0\u001b[39m] \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m5\u001b[39m\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:5348\u001b[0m, in \u001b[0;36mIndex.__setitem__\u001b[1;34m(self, key, value)\u001b[0m\n\u001b[0;32m 5346\u001b[0m \u001b[38;5;129m@final\u001b[39m\n\u001b[0;32m 5347\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m__setitem__\u001b[39m(\u001b[38;5;28mself\u001b[39m, key, value) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m-> 5348\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mIndex does not support mutable operations\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n", "\u001b[1;31mTypeError\u001b[0m: Index does not support mutable operations" ] } ], "source": [ "# 한 번 만들어진 인덱스는 변경 불가\n", "indexes[0] = 5" ] }, { "cell_type": "code", "execution_count": 40, "id": "5f6843a7-7009-41b6-ab66-d423635d23fc", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Fair Series Max 값: 512.3292\n", "Fair Series Sum 값: 28693.9493\n", "sum() Fair Series; 28693.949299999967\n", "Fair Series + 3:\n", " 0 10.2500\n", "1 74.2833\n", "2 10.9250\n", "Name: Fare, dtype: float64\n" ] } ], "source": [ "series_fair = titanic_df['Fare'] \n", "print('Fair Series Max 값:', series_fair.max()) #Fair 칼럼 중 최대값\n", "print('Fair Series Sum 값:', series_fair.sum()) #Fair 칼럼 모두 더한 값\n", "print('sum() Fair Series;', sum(series_fair))\n", "print('Fair Series + 3:\\n', (series_fair+3).head(3)) #Fair 계열에 3씩 더하고 앞의 3줄만 출력" ] }, { "cell_type": "code", "execution_count": 41, "id": "5900e84b-4aa3-4fb4-b905-823f68d5af24", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
indexPassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
00103Braund, Mr....male22.010A/5 211717.2500NaNS
11211Cumings, Mr...female38.010PC 1759971.2833C85C
22313Heikkinen, ...female26.000STON/O2. 31...7.9250NaNS
\n", "
" ], "text/plain": [ " index PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n", "0 0 1 0 3 Braund, Mr.... male 22.0 1 0 A/5 21171 7.2500 NaN S\n", "1 1 2 1 1 Cumings, Mr... female 38.0 1 0 PC 17599 71.2833 C85 C\n", "2 2 3 1 3 Heikkinen, ... female 26.0 0 0 STON/O2. 31... 7.9250 NaN S" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#reset_index( )메서드\n", "titanic_rest_df = titanic_df.reset_index(inplace=False)\n", "titanic_rest_df.head(3)" ] }, { "cell_type": "code", "execution_count": 43, "id": "525813b4-364d-49e3-b17c-8d7550ab3c9f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "### before reset_index ###\n", "Pclass\n", "3 491\n", "1 216\n", "2 184\n", "Name: count, dtype: int64\n", "value_counts 객체 변수 타입: \n", "### after reset_index ###\n", " Pclass count\n", "0 3 491\n", "1 1 216\n", "2 2 184\n", "new_value_counts 객체 변수 타입: \n" ] } ], "source": [ "print('### before reset_index ###')\n", "value_counts = titanic_df['Pclass'].value_counts()\n", "print(value_counts)\n", "print('value_counts 객체 변수 타입:', type(value_counts))\n", "\n", "new_value_counts = value_counts.reset_index(inplace=False)\n", "\n", "print('### after reset_index ###')\n", "print(new_value_counts)\n", "print('new_value_counts 객체 변수 타입:', type(new_value_counts))" ] }, { "cell_type": "code", "execution_count": 5, "id": "34c6c6f9-4ac4-4daa-a02a-d38a54430644", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "단일 칼럼 데이터 추출:\n", " 0 3\n", "1 1\n", "2 3\n", "Name: Pclass, dtype: int64\n", "\n", "여러 칼럼의 데이터 추출:\n", " Survived Pclass\n", "0 0 3\n", "1 1 1\n", "2 1 3\n" ] } ], "source": [ "print('단일 칼럼 데이터 추출:\\n', titanic_df['Pclass'].head(3))\n", "print('\\n여러 칼럼의 데이터 추출:\\n', titanic_df[['Survived','Pclass']].head(3))" ] }, { "cell_type": "code", "execution_count": 6, "id": "5747f37f-4dd6-4bbc-8a76-59773149b4ca", "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "incomplete input (316751592.py, line 1)", "output_type": "error", "traceback": [ "\u001b[1;36m Cell \u001b[1;32mIn[6], line 1\u001b[1;36m\u001b[0m\n\u001b[1;33m print('[] 안에 숫자 index는 KeyError 오류 발생:\\n', titanic_df[0]\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m incomplete input\n" ] } ], "source": [ "print('[] 안에 숫자 index는 KeyError 오류 발생:\\n', titanic_df[0]" ] }, { "cell_type": "code", "execution_count": 7, "id": "3daa0d93-f0bb-4685-9603-96d4e46bb1c3", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
\n", "
" ], "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": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_df[0:3] #처음 3개의 데이터 추출" ] }, { "cell_type": "code", "execution_count": 8, "id": "09d027e7-82fb-4dfd-aa0c-20df630166c0", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
91012Nasser, Mrs. Nicholas (Adele Achem)female14.01023773630.0708NaNC
151612Hewlett, Mrs. (Mary D Kingcome)female55.00024870616.0000NaNS
171812Williams, Mr. Charles EugenemaleNaN0024437313.0000NaNS
202102Fynney, Mr. Joseph Jmale35.00023986526.0000NaNS
212212Beesley, Mr. Lawrencemale34.00024869813.0000D56S
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Name \\\n", "9 10 1 2 Nasser, Mrs. Nicholas (Adele Achem) \n", "15 16 1 2 Hewlett, Mrs. (Mary D Kingcome) \n", "17 18 1 2 Williams, Mr. Charles Eugene \n", "20 21 0 2 Fynney, Mr. Joseph J \n", "21 22 1 2 Beesley, Mr. Lawrence \n", "\n", " Sex Age SibSp Parch Ticket Fare Cabin Embarked \n", "9 female 14.0 1 0 237736 30.0708 NaN C \n", "15 female 55.0 0 0 248706 16.0000 NaN S \n", "17 male NaN 0 0 244373 13.0000 NaN S \n", "20 male 35.0 0 0 239865 26.0000 NaN S \n", "21 male 34.0 0 0 248698 13.0000 D56 S " ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 불린 인덱싱 - Plcass 칼럼의 값이 2인 데이터 5개 출력\n", "titanic_df[titanic_df['Pclass'] ==2].head(5)" ] }, { "cell_type": "code", "execution_count": 9, "id": "b0d73e47-c232-4f40-bc24-8efdf67c236c", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NameYearGender
oneChulmin2011Male
twoEunkyung2016Female
threeJinHyuk2015Male
fourSooBeom2015Male
\n", "
" ], "text/plain": [ " Name Year Gender\n", "one Chulmin 2011 Male\n", "two Eunkyung 2016 Female\n", "three JinHyuk 2015 Male\n", "four SooBeom 2015 Male" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Data 입력\n", "data = {'Name': ['Chulmin',' Eunkyung', 'JinHyuk', 'SooBeom'],\n", " 'Year': [2011, 2016, 2015, 2015],\n", " 'Gender': ['Male', 'Female',' Male', 'Male']\n", " }\n", "# 입력된 Data로 DataFrame 생성\n", "data_df = pd.DataFrame(data, index=['one','two','three','four'])\n", "data_df" ] }, { "cell_type": "code", "execution_count": 10, "id": "8ad147a6-b2bc-41ec-a07b-5f4ba483e3c3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Chulmin'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data_df.iloc[0,0]" ] }, { "cell_type": "code", "execution_count": 11, "id": "e180416d-6ef1-481b-8741-202d3995edbf", "metadata": { "scrolled": true }, "outputs": [ { "ename": "ValueError", "evalue": "Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:940\u001b[0m, in \u001b[0;36m_LocationIndexer._validate_tuple_indexer\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m 939\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m--> 940\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_validate_key(k, i)\n\u001b[0;32m 941\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1576\u001b[0m, in \u001b[0;36m_iLocIndexer._validate_key\u001b[1;34m(self, key, axis)\u001b[0m\n\u001b[0;32m 1575\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m-> 1576\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCan only index by location with a [\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_valid_types\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m]\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n", "\u001b[1;31mValueError\u001b[0m: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]", "\nThe above exception was the direct cause of the following exception:\n", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[11], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# 오류 발생 코드\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m data_df\u001b[38;5;241m.\u001b[39miloc[\u001b[38;5;241m0\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mYear\u001b[39m\u001b[38;5;124m'\u001b[39m]\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1147\u001b[0m, in \u001b[0;36m_LocationIndexer.__getitem__\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m 1145\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_is_scalar_access(key):\n\u001b[0;32m 1146\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mobj\u001b[38;5;241m.\u001b[39m_get_value(\u001b[38;5;241m*\u001b[39mkey, takeable\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_takeable)\n\u001b[1;32m-> 1147\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_getitem_tuple(key)\n\u001b[0;32m 1148\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m 1149\u001b[0m \u001b[38;5;66;03m# we by definition only have the 0th axis\u001b[39;00m\n\u001b[0;32m 1150\u001b[0m axis \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39maxis \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;241m0\u001b[39m\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1652\u001b[0m, in \u001b[0;36m_iLocIndexer._getitem_tuple\u001b[1;34m(self, tup)\u001b[0m\n\u001b[0;32m 1651\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_getitem_tuple\u001b[39m(\u001b[38;5;28mself\u001b[39m, tup: \u001b[38;5;28mtuple\u001b[39m):\n\u001b[1;32m-> 1652\u001b[0m tup \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_validate_tuple_indexer(tup)\n\u001b[0;32m 1653\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m suppress(IndexingError):\n\u001b[0;32m 1654\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_getitem_lowerdim(tup)\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:942\u001b[0m, in \u001b[0;36m_LocationIndexer._validate_tuple_indexer\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m 940\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_validate_key(k, i)\n\u001b[0;32m 941\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n\u001b[1;32m--> 942\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[0;32m 943\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mLocation based indexing can only have \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 944\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m[\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_valid_types\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m] types\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 945\u001b[0m ) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01merr\u001b[39;00m\n\u001b[0;32m 946\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m key\n", "\u001b[1;31mValueError\u001b[0m: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types" ] } ], "source": [ "# 오류 발생 코드\n", "data_df.iloc[0, 'Year']" ] }, { "cell_type": "code", "execution_count": 12, "id": "a4d7919c-a7c0-4125-aa9c-6f4d23c4b47f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " 맨 마지막 칼럼 데이터 [:, -1]\n", " one Male\n", "two Female\n", "three Male\n", "four Male\n", "Name: Gender, dtype: object\n", "\n", " 맨 마지막 칼럼을 제외한 모든 데이터 [:, :-1]\n", " Name Year\n", "one Chulmin 2011\n", "two Eunkyung 2016\n", "three JinHyuk 2015\n", "four SooBeom 2015\n" ] } ], "source": [ "# 타깃 값 가져오기\n", "print(\"\\n 맨 마지막 칼럼 데이터 [:, -1]\\n\", data_df.iloc[:, -1])\n", "\n", "# 피처 값 가져오기\n", "print(\"\\n 맨 마지막 칼럼을 제외한 모든 데이터 [:, :-1]\\n\", data_df.iloc[:, :-1])" ] }, { "cell_type": "code", "execution_count": 23, "id": "ea2d314d-6f7d-4593-b24a-a47735b5cb37", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "두번째 행의 첫번째 열 위치에 있는 단일 값 반환:\n", " Eunkyung\n", "세번째 행의 두번째 열 위치에 있는 단일 값 반환:\n", " 2015\n", "0:2 슬라이싱 범위의 첫번째에서 두번째 행과 첫번째와 두번째 열에 해당하는 DataFrame 반환:\n", " Name Year\n", "one Chulmin 2011\n", "two Eunkyung 2016\n", "0:2 슬라이싱 범위의 첫번째에서 두번째 행의 0:3 슬라이싱 범위의 첫번째부터 세번째 열 범위에 해당하는 DataFrame 반환:\n", " Name Year Gender\n", "one Chulmin 2011 Male\n", "two Eunkyung 2016 Female\n", "전체 DataFrame 반환:\n", " Name Year Gender\n", "one Chulmin 2011 Male\n", "two Eunkyung 2016 Female\n", "three JinHyuk 2015 Male\n", "four SooBeom 2015 Male\n", "전체 DataFrame 반환:\n", " Name Year Gender\n", "one Chulmin 2011 Male\n", "two Eunkyung 2016 Female\n", "three JinHyuk 2015 Male\n", "four SooBeom 2015 Male\n" ] } ], "source": [ "# iloc[ ] 연산 유형\n", "print(\"두번째 행의 첫번째 열 위치에 있는 단일 값 반환:\\n\", data_df.iloc[1,0])\n", "print(\"세번째 행의 두번째 열 위치에 있는 단일 값 반환:\\n\", data_df.iloc[2,1])\n", "print(\"0:2 슬라이싱 범위의 첫번째에서 두번째 행과 첫번째와 두번째 열에 해당하는 DataFrame 반환:\\n\", data_df.iloc[0:2,[0,1]])\n", "print(\"0:2 슬라이싱 범위의 첫번째에서 두번째 행의 0:3 슬라이싱 범위의 첫번째부터 세번째 열 범위에 해당하는 DataFrame 반환:\\n\",\n", " data_df.iloc[0:2, 0:3])\n", "print(\"전체 DataFrame 반환:\\n\", data_df.iloc[:])\n", "print(\"전체 DataFrame 반환:\\n\", data_df.iloc[:, :])" ] }, { "cell_type": "code", "execution_count": 24, "id": "4881d5d0-732b-4196-a5e7-b2c5d0756614", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Chulmin'" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# loc (명칭 기반 인덱싱)\n", "data_df.loc['one', 'Name']" ] }, { "cell_type": "code", "execution_count": 25, "id": "fcc20a5d-94d9-488d-a8f1-a268d17bda28", "metadata": { "scrolled": true }, "outputs": [ { "ename": "KeyError", "evalue": "0", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:3791\u001b[0m, in \u001b[0;36mIndex.get_loc\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m 3790\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m-> 3791\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_engine\u001b[38;5;241m.\u001b[39mget_loc(casted_key)\n\u001b[0;32m 3792\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n", "File \u001b[1;32mindex.pyx:152\u001b[0m, in \u001b[0;36mpandas._libs.index.IndexEngine.get_loc\u001b[1;34m()\u001b[0m\n", "File \u001b[1;32mindex.pyx:181\u001b[0m, in \u001b[0;36mpandas._libs.index.IndexEngine.get_loc\u001b[1;34m()\u001b[0m\n", "File \u001b[1;32mpandas\\_libs\\hashtable_class_helper.pxi:7080\u001b[0m, in \u001b[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001b[1;34m()\u001b[0m\n", "File \u001b[1;32mpandas\\_libs\\hashtable_class_helper.pxi:7088\u001b[0m, in \u001b[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001b[1;34m()\u001b[0m\n", "\u001b[1;31mKeyError\u001b[0m: 0", "\nThe above exception was the direct cause of the following exception:\n", "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[25], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# 오류 발생 코드\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m data_df\u001b[38;5;241m.\u001b[39mloc[\u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m0\u001b[39m]\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1146\u001b[0m, in \u001b[0;36m_LocationIndexer.__getitem__\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m 1144\u001b[0m key \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mtuple\u001b[39m(com\u001b[38;5;241m.\u001b[39mapply_if_callable(x, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mobj) \u001b[38;5;28;01mfor\u001b[39;00m x \u001b[38;5;129;01min\u001b[39;00m key)\n\u001b[0;32m 1145\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_is_scalar_access(key):\n\u001b[1;32m-> 1146\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mobj\u001b[38;5;241m.\u001b[39m_get_value(\u001b[38;5;241m*\u001b[39mkey, takeable\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_takeable)\n\u001b[0;32m 1147\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_getitem_tuple(key)\n\u001b[0;32m 1148\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m 1149\u001b[0m \u001b[38;5;66;03m# we by definition only have the 0th axis\u001b[39;00m\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\frame.py:4005\u001b[0m, in \u001b[0;36mDataFrame._get_value\u001b[1;34m(self, index, col, takeable)\u001b[0m\n\u001b[0;32m 4002\u001b[0m series \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_ixs(col, axis\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m1\u001b[39m)\n\u001b[0;32m 4003\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m series\u001b[38;5;241m.\u001b[39m_values[index]\n\u001b[1;32m-> 4005\u001b[0m series \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_get_item_cache(col)\n\u001b[0;32m 4006\u001b[0m engine \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mindex\u001b[38;5;241m.\u001b[39m_engine\n\u001b[0;32m 4008\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mindex, MultiIndex):\n\u001b[0;32m 4009\u001b[0m \u001b[38;5;66;03m# CategoricalIndex: Trying to use the engine fastpath may give incorrect\u001b[39;00m\n\u001b[0;32m 4010\u001b[0m \u001b[38;5;66;03m# results if our categories are integers that dont match our codes\u001b[39;00m\n\u001b[0;32m 4011\u001b[0m \u001b[38;5;66;03m# IntervalIndex: IntervalTree has no get_loc\u001b[39;00m\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\frame.py:4414\u001b[0m, in \u001b[0;36mDataFrame._get_item_cache\u001b[1;34m(self, item)\u001b[0m\n\u001b[0;32m 4409\u001b[0m res \u001b[38;5;241m=\u001b[39m cache\u001b[38;5;241m.\u001b[39mget(item)\n\u001b[0;32m 4410\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m res \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m 4411\u001b[0m \u001b[38;5;66;03m# All places that call _get_item_cache have unique columns,\u001b[39;00m\n\u001b[0;32m 4412\u001b[0m \u001b[38;5;66;03m# pending resolution of GH#33047\u001b[39;00m\n\u001b[1;32m-> 4414\u001b[0m loc \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcolumns\u001b[38;5;241m.\u001b[39mget_loc(item)\n\u001b[0;32m 4415\u001b[0m res \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_ixs(loc, axis\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m1\u001b[39m)\n\u001b[0;32m 4417\u001b[0m cache[item] \u001b[38;5;241m=\u001b[39m res\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:3798\u001b[0m, in \u001b[0;36mIndex.get_loc\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m 3793\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(casted_key, \u001b[38;5;28mslice\u001b[39m) \u001b[38;5;129;01mor\u001b[39;00m (\n\u001b[0;32m 3794\u001b[0m \u001b[38;5;28misinstance\u001b[39m(casted_key, abc\u001b[38;5;241m.\u001b[39mIterable)\n\u001b[0;32m 3795\u001b[0m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;28many\u001b[39m(\u001b[38;5;28misinstance\u001b[39m(x, \u001b[38;5;28mslice\u001b[39m) \u001b[38;5;28;01mfor\u001b[39;00m x \u001b[38;5;129;01min\u001b[39;00m casted_key)\n\u001b[0;32m 3796\u001b[0m ):\n\u001b[0;32m 3797\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m InvalidIndexError(key)\n\u001b[1;32m-> 3798\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m(key) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01merr\u001b[39;00m\n\u001b[0;32m 3799\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m:\n\u001b[0;32m 3800\u001b[0m \u001b[38;5;66;03m# If we have a listlike key, _check_indexing_error will raise\u001b[39;00m\n\u001b[0;32m 3801\u001b[0m \u001b[38;5;66;03m# InvalidIndexError. Otherwise we fall through and re-raise\u001b[39;00m\n\u001b[0;32m 3802\u001b[0m \u001b[38;5;66;03m# the TypeError.\u001b[39;00m\n\u001b[0;32m 3803\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_indexing_error(key)\n", "\u001b[1;31mKeyError\u001b[0m: 0" ] } ], "source": [ "# 오류 발생 코드\n", "data_df.loc[0, 0]" ] }, { "cell_type": "code", "execution_count": 28, "id": "0356092c-8390-41d1-b052-003eb3e1113f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "위치기반 iloc slicing\n", " one Chulmin\n", "Name: Name, dtype: object \n", "\n", "명칭기반 loc slicing\n", " one Chulmin\n", "two Eunkyung\n", "Name: Name, dtype: object\n" ] } ], "source": [ "print('위치기반 iloc slicing\\n', data_df.iloc[0:1, 0],'\\n')\n", "print('명칭기반 loc slicing\\n', data_df.loc['one':'two', 'Name'])" ] }, { "cell_type": "code", "execution_count": 31, "id": "f0f1e4dd-7a5a-4ad4-b976-49c8830a1d9b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "인덱스 값 three인 행의 Name 칼럼의 단일값 반환:\n", " JinHyuk\n", "인덱스 값 one부터 two까지 행의 Name과 Year 칼럼에 해당하는 DataFrame 반환:\n", " Name Year\n", "one Chulmin 2011\n", "two Eunkyung 2016\n", "인덱스 값 one부터 three까지 행의 Name부터 Gender 칼럼까지의 DataFrame 반환:\n", " Name Year Gender\n", "one Chulmin 2011 Male\n", "two Eunkyung 2016 Female\n", "three JinHyuk 2015 Male\n", "모든 데이터 값:\n", " Name Year Gender\n", "one Chulmin 2011 Male\n", "two Eunkyung 2016 Female\n", "three JinHyuk 2015 Male\n", "four SooBeom 2015 Male\n", "iloc[]와 다르게 loc[]는 불린 인덱싱이 가능\n", " Year 칼럼의 값이 2014 이상인 모든 데이터를 불린 인덱싱으로 추출:\n", " Name Year Gender\n", "two Eunkyung 2016 Female\n", "three JinHyuk 2015 Male\n", "four SooBeom 2015 Male\n" ] } ], "source": [ "# loc[ ] 연산의 수행 사례\n", "print(\"인덱스 값 three인 행의 Name 칼럼의 단일값 반환:\\n\", data_df.loc['three', 'Name'])\n", "print(\"인덱스 값 one부터 two까지 행의 Name과 Year 칼럼에 해당하는 DataFrame 반환:\\n\", data_df.loc['one':'two', ['Name', 'Year']])\n", "print(\"인덱스 값 one부터 three까지 행의 Name부터 Gender 칼럼까지의 DataFrame 반환:\\n\", data_df.loc['one':'three', 'Name':'Gender'])\n", "print(\"모든 데이터 값:\\n\",data_df.loc[:])\n", "print(\"iloc[]와 다르게 loc[]는 불린 인덱싱이 가능\\n Year 칼럼의 값이 2014 이상인 모든 데이터를 불린 인덱싱으로 추출:\\n\",\n", " data_df.loc[data_df.Year>=2014])" ] }, { "cell_type": "code", "execution_count": 32, "id": "a65670a7-b436-44b4-8627-936b4e167392", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
333402Wheadon, Mr. Edward Hmale66.000C.A. 2457910.5000NaNS
545501Ostby, Mr. Engelhart Corneliusmale65.00111350961.9792B30C
969701Goldschmidt, Mr. George Bmale71.000PC 1775434.6542A5C
11611703Connors, Mr. Patrickmale70.5003703697.7500NaNQ
17017101Van der hoef, Mr. Wyckoffmale61.00011124033.5000B19S
25225301Stead, Mr. William Thomasmale62.00011351426.5500C87S
27527611Andrews, Miss. Kornelia Theodosiafemale63.0101350277.9583D7S
28028103Duane, Mr. Frankmale65.0003364397.7500NaNQ
32632703Nysveen, Mr. Johan Hansenmale61.0003453646.2375NaNS
43843901Fortune, Mr. Markmale64.01419950263.0000C23 C25 C27S
45645701Millet, Mr. Francis Davismale65.0001350926.5500E38S
48348413Turkula, Mrs. (Hedwig)female63.00041349.5875NaNS
49349401Artagaveytia, Mr. Ramonmale71.000PC 1760949.5042NaNC
54554601Nicholson, Mr. Arthur Ernestmale64.00069326.0000NaNS
55555601Wright, Mr. Georgemale62.00011380726.5500NaNS
57057112Harris, Mr. Georgemale62.000S.W./PP 75210.5000NaNS
62562601Sutton, Mr. Frederickmale61.0003696332.3208D50S
63063111Barkworth, Mr. Algernon Henry Wilsonmale80.0002704230.0000A23S
67267302Mitchell, Mr. Henry Michaelmale70.000C.A. 2458010.5000NaNS
74574601Crosby, Capt. Edward Giffordmale70.011WE/P 573571.0000B22S
82983011Stone, Mrs. George Nelson (Martha Evelyn)female62.00011357280.0000B28NaN
85185203Svensson, Mr. Johanmale74.0003470607.7750NaNS
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Name \\\n", "33 34 0 2 Wheadon, Mr. Edward H \n", "54 55 0 1 Ostby, Mr. Engelhart Cornelius \n", "96 97 0 1 Goldschmidt, Mr. George B \n", "116 117 0 3 Connors, Mr. Patrick \n", "170 171 0 1 Van der hoef, Mr. Wyckoff \n", "252 253 0 1 Stead, Mr. William Thomas \n", "275 276 1 1 Andrews, Miss. Kornelia Theodosia \n", "280 281 0 3 Duane, Mr. Frank \n", "326 327 0 3 Nysveen, Mr. Johan Hansen \n", "438 439 0 1 Fortune, Mr. Mark \n", "456 457 0 1 Millet, Mr. Francis Davis \n", "483 484 1 3 Turkula, Mrs. (Hedwig) \n", "493 494 0 1 Artagaveytia, Mr. Ramon \n", "545 546 0 1 Nicholson, Mr. Arthur Ernest \n", "555 556 0 1 Wright, Mr. George \n", "570 571 1 2 Harris, Mr. George \n", "625 626 0 1 Sutton, Mr. Frederick \n", "630 631 1 1 Barkworth, Mr. Algernon Henry Wilson \n", "672 673 0 2 Mitchell, Mr. Henry Michael \n", "745 746 0 1 Crosby, Capt. Edward Gifford \n", "829 830 1 1 Stone, Mrs. George Nelson (Martha Evelyn) \n", "851 852 0 3 Svensson, Mr. Johan \n", "\n", " Sex Age SibSp Parch Ticket Fare Cabin Embarked \n", "33 male 66.0 0 0 C.A. 24579 10.5000 NaN S \n", "54 male 65.0 0 1 113509 61.9792 B30 C \n", "96 male 71.0 0 0 PC 17754 34.6542 A5 C \n", "116 male 70.5 0 0 370369 7.7500 NaN Q \n", "170 male 61.0 0 0 111240 33.5000 B19 S \n", "252 male 62.0 0 0 113514 26.5500 C87 S \n", "275 female 63.0 1 0 13502 77.9583 D7 S \n", "280 male 65.0 0 0 336439 7.7500 NaN Q \n", "326 male 61.0 0 0 345364 6.2375 NaN S \n", "438 male 64.0 1 4 19950 263.0000 C23 C25 C27 S \n", "456 male 65.0 0 0 13509 26.5500 E38 S \n", "483 female 63.0 0 0 4134 9.5875 NaN S \n", "493 male 71.0 0 0 PC 17609 49.5042 NaN C \n", "545 male 64.0 0 0 693 26.0000 NaN S \n", "555 male 62.0 0 0 113807 26.5500 NaN S \n", "570 male 62.0 0 0 S.W./PP 752 10.5000 NaN S \n", "625 male 61.0 0 0 36963 32.3208 D50 S \n", "630 male 80.0 0 0 27042 30.0000 A23 S \n", "672 male 70.0 0 0 C.A. 24580 10.5000 NaN S \n", "745 male 70.0 1 1 WE/P 5735 71.0000 B22 S \n", "829 female 62.0 0 0 113572 80.0000 B28 NaN \n", "851 male 74.0 0 0 347060 7.7750 NaN S " ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 불린 인덱스\n", "titanic_boolean = titanic_df[titanic_df['Age'] > 60] #Age 컬럼에서 나이가 60세 이상인 데이터 찾기\n", "print(type(titanic_boolean))\n", "titanic_boolean" ] }, { "cell_type": "code", "execution_count": 33, "id": "ef53c341-110f-403e-a6f6-70e34c8f8286", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NameAge
33Wheadon, Mr. Edward H66.0
54Ostby, Mr. Engelhart Cornelius65.0
96Goldschmidt, Mr. George B71.0
116Connors, Mr. Patrick70.5
170Van der hoef, Mr. Wyckoff61.0
\n", "
" ], "text/plain": [ " Name Age\n", "33 Wheadon, Mr. Edward H 66.0\n", "54 Ostby, Mr. Engelhart Cornelius 65.0\n", "96 Goldschmidt, Mr. George B 71.0\n", "116 Connors, Mr. Patrick 70.5\n", "170 Van der hoef, Mr. Wyckoff 61.0" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_df[titanic_df['Age']>60][['Name', 'Age']].head(5)" ] }, { "cell_type": "code", "execution_count": 34, "id": "bc72c838-9ece-4ac3-9d64-e10d8e8058f0", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NameAge
33Wheadon, Mr. Edward H66.0
54Ostby, Mr. Engelhart Cornelius65.0
96Goldschmidt, Mr. George B71.0
116Connors, Mr. Patrick70.5
170Van der hoef, Mr. Wyckoff61.0
\n", "
" ], "text/plain": [ " Name Age\n", "33 Wheadon, Mr. Edward H 66.0\n", "54 Ostby, Mr. Engelhart Cornelius 65.0\n", "96 Goldschmidt, Mr. George B 71.0\n", "116 Connors, Mr. Patrick 70.5\n", "170 Van der hoef, Mr. Wyckoff 61.0" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_df.loc[titanic_df['Age']>60, ['Name', 'Age']].head(5)" ] }, { "cell_type": "code", "execution_count": 38, "id": "aecd1371-fbdc-4ad4-a934-6aca1f9e9f2c", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
27527611Andrews, Miss. Kornelia Theodosiafemale63.0101350277.9583D7S
82983011Stone, Mrs. George Nelson (Martha Evelyn)female62.00011357280.0000B28NaN
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Name \\\n", "275 276 1 1 Andrews, Miss. Kornelia Theodosia \n", "829 830 1 1 Stone, Mrs. George Nelson (Martha Evelyn) \n", "\n", " Sex Age SibSp Parch Ticket Fare Cabin Embarked \n", "275 female 63.0 1 0 13502 77.9583 D7 S \n", "829 female 62.0 0 0 113572 80.0000 B28 NaN " ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 복합 조건 사용하여 추출하기 (60세 이상 1등급 선실 여성 승객)\n", "titanic_df[(titanic_df['Age']>60) & (titanic_df['Pclass']==1) & (titanic_df['Sex']=='female')]" ] }, { "cell_type": "code", "execution_count": 39, "id": "cf6d6b03-83f8-421e-b7d2-c491c94711b6", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
27527611Andrews, Miss. Kornelia Theodosiafemale63.0101350277.9583D7S
82983011Stone, Mrs. George Nelson (Martha Evelyn)female62.00011357280.0000B28NaN
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Name \\\n", "275 276 1 1 Andrews, Miss. Kornelia Theodosia \n", "829 830 1 1 Stone, Mrs. George Nelson (Martha Evelyn) \n", "\n", " Sex Age SibSp Parch Ticket Fare Cabin Embarked \n", "275 female 63.0 1 0 13502 77.9583 D7 S \n", "829 female 62.0 0 0 113572 80.0000 B28 NaN " ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 개별 조건 결합하여 불린 인덱싱 수행하기\n", "cond1 = titanic_df['Age']>60\n", "cond2 = titanic_df['Pclass']==1\n", "cond3 = titanic_df['Sex']=='female'\n", "titanic_df[cond1 & cond2 & cond3]" ] }, { "cell_type": "code", "execution_count": 4, "id": "1e98e57b-396f-4f69-a6aa-b4b57a251ac4", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
84584603Abbing, Mr. Anthonymale42.000C.A. 55477.55NaNS
74674703Abbott, Mr. Rossmore Edwardmale16.011C.A. 267320.25NaNS
27928013Abbott, Mrs. Stanton (Rosa Hunt)female35.011C.A. 267320.25NaNS
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Name Sex \\\n", "845 846 0 3 Abbing, Mr. Anthony male \n", "746 747 0 3 Abbott, Mr. Rossmore Edward male \n", "279 280 1 3 Abbott, Mrs. Stanton (Rosa Hunt) female \n", "\n", " Age SibSp Parch Ticket Fare Cabin Embarked \n", "845 42.0 0 0 C.A. 5547 7.55 NaN S \n", "746 16.0 1 1 C.A. 2673 20.25 NaN S \n", "279 35.0 1 1 C.A. 2673 20.25 NaN S " ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Name 칼럼으로 오름차순 정렬\n", "titanic_sorted = titanic_df.sort_values(by=['Name'])\n", "titanic_sorted.head(3)" ] }, { "cell_type": "code", "execution_count": 5, "id": "9ba2af35-cfbd-42ab-99dc-509468aba6d6", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
86886903van Melkebeke, Mr. PhilemonmaleNaN003457779.5NaNS
15315403van Billiard, Mr. Austin Blylermale40.502A/5. 85114.5NaNS
28228303de Pelsmaeker, Mr. Alfonsmale16.0003457789.5NaNS
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Name Sex \\\n", "868 869 0 3 van Melkebeke, Mr. Philemon male \n", "153 154 0 3 van Billiard, Mr. Austin Blyler male \n", "282 283 0 3 de Pelsmaeker, Mr. Alfons male \n", "\n", " Age SibSp Parch Ticket Fare Cabin Embarked \n", "868 NaN 0 0 345777 9.5 NaN S \n", "153 40.5 0 2 A/5. 851 14.5 NaN S \n", "282 16.0 0 0 345778 9.5 NaN S " ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Pclass, Name 칼럼으로 내림차순 정렬\n", "titanic_sorted = titanic_df.sort_values(by=['Pclass','Name'], ascending=False) #내림차순 이므로 생략 불가\n", "titanic_sorted.head(3)" ] }, { "cell_type": "code", "execution_count": 6, "id": "9740e17c-7f17-4270-a464-ad3d557df066", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "PassengerId 891\n", "Survived 891\n", "Pclass 891\n", "Name 891\n", "Sex 891\n", "Age 714\n", "SibSp 891\n", "Parch 891\n", "Ticket 891\n", "Fare 891\n", "Cabin 204\n", "Embarked 889\n", "dtype: int64" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# aggregation 함수\n", "titanic_df.count()" ] }, { "cell_type": "code", "execution_count": 7, "id": "3d6488ac-8893-404f-85ef-9a65af82d5e3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Age 29.699118\n", "Fare 32.204208\n", "dtype: float64" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 특정 칼럼에만 aggregation 적용하기\n", "titanic_df[['Age', 'Fare']].mean() #mean은 평균값" ] }, { "cell_type": "code", "execution_count": 8, "id": "6c5e9a73-6d3f-4b9e-aae4-42af4f6d5eab", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# Pclass 칼럼 기준으로 groupby\n", "titanic_groupby = titanic_df.groupby(by='Pclass')\n", "print(type(titanic_groupby))" ] }, { "cell_type": "code", "execution_count": 10, "id": "de8908d4-bb95-4bc9-b202-b8d8cd11394f", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedNameSexAgeSibSpParchTicketFareCabinEmbarked
Pclass
1216216216216186216216216216176214
218418418418417318418418418416184
349149149149135549149149149112491
\n", "
" ], "text/plain": [ " PassengerId Survived Name Sex Age SibSp Parch Ticket Fare \\\n", "Pclass \n", "1 216 216 216 216 186 216 216 216 216 \n", "2 184 184 184 184 173 184 184 184 184 \n", "3 491 491 491 491 355 491 491 491 491 \n", "\n", " Cabin Embarked \n", "Pclass \n", "1 176 214 \n", "2 16 184 \n", "3 12 491 " ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_groupby = titanic_df.groupby('Pclass').count()\n", "titanic_groupby" ] }, { "cell_type": "code", "execution_count": 11, "id": "111d4948-1649-4c3e-9804-f797988d4adf", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvived
Pclass
1216216
2184184
3491491
\n", "
" ], "text/plain": [ " PassengerId Survived\n", "Pclass \n", "1 216 216\n", "2 184 184\n", "3 491 491" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 특정 칼럼만 group by\n", "titanic_groupby = titanic_df.groupby('Pclass')[['PassengerId', 'Survived']].count()\n", "titanic_groupby" ] }, { "cell_type": "code", "execution_count": 12, "id": "0a2e10f2-d819-4e07-8010-b23a1b948d3a", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "C:\\Users\\niceq\\AppData\\Local\\Temp\\ipykernel_21448\\824042513.py:2: FutureWarning: The provided callable 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", " titanic_df.groupby('Pclass')['Age'].agg([max, min])\n", "C:\\Users\\niceq\\AppData\\Local\\Temp\\ipykernel_21448\\824042513.py:2: FutureWarning: The provided callable 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", " titanic_df.groupby('Pclass')['Age'].agg([max, min])\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
maxmin
Pclass
180.00.92
270.00.67
374.00.42
\n", "
" ], "text/plain": [ " max min\n", "Pclass \n", "1 80.0 0.92\n", "2 70.0 0.67\n", "3 74.0 0.42" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 여러 개의 aggregation 함수 사용\n", "titanic_df.groupby('Pclass')['Age'].agg([max, min])" ] }, { "cell_type": "code", "execution_count": 13, "id": "804ee9aa-3e5c-4034-8d6e-133727478fbe", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
AgeSibSpFare
Pclass
180.09084.154687
270.07420.662183
374.030213.675550
\n", "
" ], "text/plain": [ " Age SibSp Fare\n", "Pclass \n", "1 80.0 90 84.154687\n", "2 70.0 74 20.662183\n", "3 74.0 302 13.675550" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "agg_format={'Age':'max', 'SibSp':'sum', 'Fare':'mean'}\n", "titanic_df.groupby('Pclass').agg(agg_format)" ] }, { "cell_type": "code", "execution_count": 3, "id": "6777ecd5-7b4e-491b-91ef-10a6c6910a7f", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseTrueFalse
1FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalse
2FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseTrueFalse
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket \\\n", "0 False False False False False False False False False \n", "1 False False False False False False False False False \n", "2 False False False False False False False False False \n", "\n", " Fare Cabin Embarked \n", "0 False True False \n", "1 False False False \n", "2 False True False " ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 결손 데이터 여부 확인\n", "titanic_df.isna().head(3)" ] }, { "cell_type": "code", "execution_count": 4, "id": "22a66ba0-6d29-41b6-9561-24de1ebfa74c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "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" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "titanic_df.isna().sum()" ] }, { "cell_type": "code", "execution_count": 7, "id": "c9d69005-a6bf-4014-a5c4-1182c7471627", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500C000S
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250C000S
\n", "
" ], "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 C000 S \n", "1 0 PC 17599 71.2833 C85 C \n", "2 0 STON/O2. 3101282 7.9250 C000 S " ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 'Cabin' 칼럼의 NaN 값을 'C000'으로 대체\n", "titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000')\n", "titanic_df.head(3)" ] }, { "cell_type": "code", "execution_count": 8, "id": "195efd69-50b7-4d0f-b3e5-fa5a5e800437", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "PassengerId 0\n", "Survived 0\n", "Pclass 0\n", "Name 0\n", "Sex 0\n", "Age 0\n", "SibSp 0\n", "Parch 0\n", "Ticket 0\n", "Fare 0\n", "Cabin 0\n", "Embarked 0\n", "dtype: int64" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 여러 칼럼의 결손 데이터 처리하기\n", "titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean()) #Age 칼럼 결손값 평균으로 처리\n", "titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S') #Embarked 칼럼 결손값 S로 처리\n", "titanic_df.isna().sum() #결손 데이터의 개수 구하기" ] }, { "cell_type": "code", "execution_count": 9, "id": "bba2b4cf-b851-44ea-8e3c-d33c511ae9f9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3의 제곱은: 9\n" ] } ], "source": [ "def get_square(a):\n", " return a**2 # get_square(a) 함수는 입력값의 제곱 값을 반환\n", "\n", "print('3의 제곱은:', get_square(3))" ] }, { "cell_type": "code", "execution_count": 11, "id": "38b3cfae-cd8a-4713-911e-0997da17f97c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3의 제곱은: 9\n" ] } ], "source": [ "#lambda 식으로 변환\n", "lambda_square = lambda x : x**2\n", "print('3의 제곱은:', lambda_square(3))" ] }, { "cell_type": "code", "execution_count": 12, "id": "7e288afd-66f0-4c2d-be34-16b6d83ae240", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9]" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# lambda + map 함수\n", "a=[1, 2, 3]\n", "squares = map(lambda x: x**2, a)\n", "list(squares)" ] }, { "cell_type": "code", "execution_count": 13, "id": "5a9eac4c-1ba4-45ff-85c2-8639114361f7", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NameName_len
0Braund, Mr. Owen Harris23
1Cumings, Mrs. John Bradley (Florence Briggs Th...51
2Heikkinen, Miss. Laina22
\n", "
" ], "text/plain": [ " Name Name_len\n", "0 Braund, Mr. Owen Harris 23\n", "1 Cumings, Mrs. John Bradley (Florence Briggs Th... 51\n", "2 Heikkinen, Miss. Laina 22" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Name 칼럼 문자열 개수를 Name_len에 표시하기\n", "titanic_df['Name_len'] = titanic_df['Name'].apply(lambda x : len(x))\n", "titanic_df[['Name', 'Name_len']].head(3)" ] }, { "cell_type": "code", "execution_count": 15, "id": "1c92ce14-74c1-453c-82b7-bdefa07cded0", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
AgeChild_Audlt
022.0Adult
138.0Adult
226.0Adult
\n", "
" ], "text/plain": [ " Age Child_Audlt\n", "0 22.0 Adult\n", "1 38.0 Adult\n", "2 26.0 Adult" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 아이와 어른 구분하는 컬럼 만들기\n", "titanic_df['Child_Audlt'] = titanic_df['Age'].apply(lambda x : 'Child' if x <=15 else 'Adult')\n", "titanic_df[['Age', 'Child_Audlt']].head(3)" ] }, { "cell_type": "code", "execution_count": 18, "id": "9f4dcc13-8b2d-43ac-99ff-02aabb4b1d33", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Age_cat\n", "Adult 786\n", "Child 83\n", "Elderly 22\n", "Name: count, dtype: int64" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 여러 조건을 반영한 칼럼 만들기\n", "# 15세 이하는 'Chlld', 15~60세는 'Adult', 61세 이상은 'Elderly'\n", "titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : 'Child' if x<=15 else ('Adult' if x <=60 else 'Elderly'))\n", "titanic_df['Age_cat'].value_counts()" ] }, { "cell_type": "code", "execution_count": 32, "id": "35cd5877-08b7-4e2f-9f47-824a23d074aa", "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
AgeAge_cat
022.0Student
138.0Adult
226.0Young Adult
335.0Young Adult
435.0Young Adult
\n", "
" ], "text/plain": [ " Age Age_cat\n", "0 22.0 Student\n", "1 38.0 Adult\n", "2 26.0 Young Adult\n", "3 35.0 Young Adult\n", "4 35.0 Young Adult" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 나이에 따라 세분화된 분류를 수행하는 함수 생성\n", "def get_category(age):\n", " cat = ''\n", " if age <= 5: cat = 'Baby'\n", " elif age <= 12: cat = 'Child'\n", " elif age <= 18: cat = 'Teenager'\n", " elif age <= 25: cat = 'Student'\n", " elif age <= 35: cat = 'Young Adult'\n", " elif age <= 60: cat = 'Adult'\n", " else: cat = 'Elderly'\n", "\n", " return cat\n", "\n", "# lambda 식에 위에서 생성한 get_category( ) 함수를 반환값으로 지정\n", "# get_category(x)는 입력값으로 'Age' 칼럼 값을 받아서 해당하는 cat 반환\n", "titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : get_category(x))\n", "titanic_df[['Age', 'Age_cat']].head(5)" ] }, { "cell_type": "code", "execution_count": null, "id": "07e872e5-145a-4854-a8e2-d62e5494f334", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "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.11.7" } }, "nbformat": 4, "nbformat_minor": 5 }