diff --git "a/Week1_\353\263\265\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.ipynb" "b/Week1_\353\263\265\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.ipynb" new file mode 100644 index 0000000..b215484 --- /dev/null +++ "b/Week1_\353\263\265\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.ipynb" @@ -0,0 +1,5344 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + } + }, + "cells": [ + { + "cell_type": "markdown", + "source": [ + "# **1주차 복습과제**\n", + "- 1주차 복습과제는 **넘파이/판다스 연습문제**입니다.\n", + "- 코드 작성하시고, 출력 결과까지 나오도록 실행 부탁드립니다.\n", + " - 제출 시 파일명 본인 이름으로 변경해 주세요. ex) Week1_복습과제_OOO\n", + "- 교재에서 다루지 않은 메소드도 다수 포함되어 있지만 구글링이나 챗지피티 등을 활용해서라도 풀어주세요! 한 번씩 사용해 보면 좋을 것 같아 어려워도 문제에 포함했습니다 🤗" + ], + "metadata": { + "id": "jkGNNJY3S65Z" + } + }, + { + "cell_type": "markdown", + "source": [ + "## **넘파이**" + ], + "metadata": { + "id": "WedDHAHPJPIA" + } + }, + { + "cell_type": "markdown", + "source": [ + "### 1. Import the numpy package under the name `np`." + ], + "metadata": { + "id": "7Ue21e0fKFRI" + } + }, + { + "cell_type": "code", + "execution_count": 292, + "metadata": { + "id": "60ACXMoSGe0H" + }, + "outputs": [], + "source": [ + "import numpy as np" + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 2. Print the numpy version and the configuration.\n", + "\n", + "(hint: `np.__version__`, `np.show_config`)" + ], + "metadata": { + "id": "FnHQOUj-KNiT" + } + }, + { + "cell_type": "code", + "source": [ + "np_ver = np.__version__\n", + "print('넘파이 버전: ', np_ver)\n", + "\n", + "\n", + "print('넘파이 설정:')\n", + "np.show_config()" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "mdFSKpU7LuJb", + "outputId": "8adcb836-8862-4a59-ceb8-84fe647542d0" + }, + "execution_count": 293, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "넘파이 버전: 2.1.3\n", + "넘파이 설정:\n", + "Build Dependencies:\n", + " blas:\n", + " detection method: pkgconfig\n", + " found: true\n", + " include directory: /opt/_internal/cpython-3.13.0/lib/python3.13/site-packages/scipy_openblas64/include\n", + " lib directory: /opt/_internal/cpython-3.13.0/lib/python3.13/site-packages/scipy_openblas64/lib\n", + " name: scipy-openblas\n", + " openblas configuration: OpenBLAS 0.3.27 USE64BITINT DYNAMIC_ARCH NO_AFFINITY\n", + " Haswell MAX_THREADS=64\n", + " pc file directory: /project/.openblas\n", + " version: 0.3.27\n", + " lapack:\n", + " detection method: pkgconfig\n", + " found: true\n", + " include directory: /opt/_internal/cpython-3.13.0/lib/python3.13/site-packages/scipy_openblas64/include\n", + " lib directory: /opt/_internal/cpython-3.13.0/lib/python3.13/site-packages/scipy_openblas64/lib\n", + " name: scipy-openblas\n", + " openblas configuration: OpenBLAS 0.3.27 USE64BITINT DYNAMIC_ARCH NO_AFFINITY\n", + " Haswell MAX_THREADS=64\n", + " pc file directory: /project/.openblas\n", + " version: 0.3.27\n", + "Compilers:\n", + " c:\n", + " commands: cc\n", + " linker: ld.bfd\n", + " name: gcc\n", + " version: 10.2.1\n", + " c++:\n", + " commands: c++\n", + " linker: ld.bfd\n", + " name: gcc\n", + " version: 10.2.1\n", + " cython:\n", + " commands: cython\n", + " linker: cython\n", + " name: cython\n", + " version: 3.0.11\n", + "Machine Information:\n", + " build:\n", + " cpu: x86_64\n", + " endian: little\n", + " family: x86_64\n", + " system: linux\n", + " host:\n", + " cpu: x86_64\n", + " endian: little\n", + " family: x86_64\n", + " system: linux\n", + "Python Information:\n", + " path: /tmp/build-env-v_9b5grh/bin/python\n", + " version: '3.13'\n", + "SIMD Extensions:\n", + " baseline:\n", + " - SSE\n", + " - SSE2\n", + " - SSE3\n", + " found:\n", + " - SSSE3\n", + " - SSE41\n", + " - POPCNT\n", + " - SSE42\n", + " - AVX\n", + " - F16C\n", + " - FMA3\n", + " - AVX2\n", + " not found:\n", + " - AVX512F\n", + " - AVX512CD\n", + " - AVX512_KNL\n", + " - AVX512_KNM\n", + " - AVX512_SKX\n", + " - AVX512_CLX\n", + " - AVX512_CNL\n", + " - AVX512_ICL\n", + "\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 3. Create a null vector of size 10.\n", + "\n", + "#### ✅ 출력 예시\n", + "\n", + "\n", + "```\n", + "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + "```\n", + "\n" + ], + "metadata": { + "id": "0lB5hLlTKb1Z" + } + }, + { + "cell_type": "code", + "source": [ + "n3 = np.zeros(10)\n", + "print(n3)" + ], + "metadata": { + "id": "eK4DTjPwS_zU", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "1862fdc8-8070-4280-ffe7-fc61a4f7f9cb" + }, + "execution_count": 294, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 4. Create a null vector of size 10 but the fifth value which is 1.\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]\n", + "```" + ], + "metadata": { + "id": "7lSSfwh6Kj5v" + } + }, + { + "cell_type": "code", + "source": [ + "n4 = np.zeros(10)\n", + "n4[4] = 1\n", + "print(n4)" + ], + "metadata": { + "id": "ofohgzsTTBs6", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "af84504b-4fb9-4499-c666-1688eb74b4a7" + }, + "execution_count": 295, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 5. Create a vector with values ranging from 10 to 49.\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33\n", + " 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]\n", + "```" + ], + "metadata": { + "id": "-NeqvmpLKkdY" + } + }, + { + "cell_type": "code", + "source": [ + "n5 = np.arange(10,50)\n", + "print(n5)" + ], + "metadata": { + "id": "oQ1Mo5W9TC0P", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "24cdca7f-8ff5-4eda-85b9-63f2afd0af9b" + }, + "execution_count": 296, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33\n", + " 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 6. Reverse a vector (first element becomes last).\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[9 8 7 6 5 4 3 2 1 0]\n", + "```" + ], + "metadata": { + "id": "B1dFQzRNLN23" + } + }, + { + "cell_type": "code", + "source": [ + "n6 = np.arange(10)[::-1]\n", + "print(n6)" + ], + "metadata": { + "id": "wrpNYd4jTDsx", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "85ec7855-bb9a-4696-ab69-9cace575910a" + }, + "execution_count": 297, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[9 8 7 6 5 4 3 2 1 0]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 7. Create a 3x3 matrix with values ranging from 0 to 8.\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[[0 1 2]\n", + " [3 4 5]\n", + " [6 7 8]]\n", + "```" + ], + "metadata": { + "id": "doUDUe_NLOhe" + } + }, + { + "cell_type": "code", + "source": [ + "n7 = np.arange(9).reshape(3,3)\n", + "print(n7)" + ], + "metadata": { + "id": "4g8WetkATEnw", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "2de98cab-9429-4cf3-feed-81822603b216" + }, + "execution_count": 298, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[[0 1 2]\n", + " [3 4 5]\n", + " [6 7 8]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 8. Find indices of non-zero elements from [1,2,0,0,4,0].\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "(array([0, 1, 4]),)\n", + "```" + ], + "metadata": { + "id": "s-MtSq2RLzJx" + } + }, + { + "cell_type": "code", + "source": [ + "n8 = np.array([1,2,0,0,4,0])\n", + "print(np.nonzero(n8))" + ], + "metadata": { + "id": "jw9iUP7sTL7D", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "a6c6552f-2a67-4b32-af3a-20fe297dc265" + }, + "execution_count": 299, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "(array([0, 1, 4]),)\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 9. Create a 3x3 identity matrix.\n", + "\n", + "(hint: `np.eye`)\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[[1. 0. 0.]\n", + " [0. 1. 0.]\n", + " [0. 0. 1.]]\n", + "```" + ], + "metadata": { + "id": "ihRWHFUxL6ak" + } + }, + { + "cell_type": "code", + "source": [ + "n9 = np.eye(3)\n", + "print(n9)" + ], + "metadata": { + "id": "fFzDGJT5TNh7", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "d77d5c42-4b82-4cdf-ce82-fd8f057d9895" + }, + "execution_count": 300, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[[1. 0. 0.]\n", + " [0. 1. 0.]\n", + " [0. 0. 1.]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 10. Create a 3x3x3 array with random values.\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[[[0.30742852 0.26458726 0.85474383]\n", + " [0.80234531 0.76268902 0.91286677]\n", + " [0.8804109 0.51011378 0.82103555]]\n", + "\n", + " [[0.403753 0.83120234 0.15202655]\n", + " [0.75782685 0.0732058 0.48148689]\n", + " [0.2089428 0.44968622 0.88134184]]\n", + "\n", + " [[0.52251191 0.10738374 0.86279648]\n", + " [0.26203911 0.42157754 0.68856833]\n", + " [0.58133626 0.31059127 0.71354172]]]\n", + "```" + ], + "metadata": { + "id": "FvkGsY8eLPCG" + } + }, + { + "cell_type": "code", + "source": [ + "n10 = np.random.random((3,3,3))\n", + "print(n10)" + ], + "metadata": { + "id": "084SAfnwTPpt", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "b51c0299-cc11-44bd-f2e1-7ab1c19a442d" + }, + "execution_count": 301, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[[[0.29280939 0.61091433 0.91302739]\n", + " [0.300115 0.24859864 0.6663921 ]\n", + " [0.98753291 0.46827041 0.12328738]]\n", + "\n", + " [[0.91603139 0.94614353 0.27769737]\n", + " [0.51965369 0.154745 0.01462735]\n", + " [0.32424321 0.99089844 0.51314129]]\n", + "\n", + " [[0.87649564 0.06739575 0.28415374]\n", + " [0.46889927 0.76177319 0.92261178]\n", + " [0.39302376 0.92908768 0.49961201]]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 11. Create a 10x10 array with random values and find the minimum and maximum values.\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "0.018360924693465508 0.9990506368595156\n", + "```" + ], + "metadata": { + "id": "4-VynNt5MVYY" + } + }, + { + "cell_type": "code", + "source": [ + "n11 = np.random.random((10,10))\n", + "print(n11.min(), n11.max())" + ], + "metadata": { + "id": "W14PP5x6TRh6", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "66dd83c7-80e2-4af9-d86b-13433102550e" + }, + "execution_count": 302, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "0.025222518201502453 0.9914673999458862\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 12. Create a random vector of size 30 and find the mean value.\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "0.46249036320403636\n", + "```" + ], + "metadata": { + "id": "cQKXmfJBMVQ_" + } + }, + { + "cell_type": "code", + "source": [ + "n12 = np.random.random(30)\n", + "print(n12.mean())" + ], + "metadata": { + "id": "FS6ggiNJTStp", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "ae2c51dc-0282-431b-bbf9-e08821680885" + }, + "execution_count": 303, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "0.45521376102011424\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 13. Create a 2d array with 1 on the border and 0 inside. (size: 10x10)\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]\n", + "```" + ], + "metadata": { + "id": "QZ4h-AddMVJb" + } + }, + { + "cell_type": "code", + "source": [ + "n13 = np.ones((10,10))\n", + "n13[1:-1,1:-1] = 0\n", + "print(n13)" + ], + "metadata": { + "id": "pKEi08edTUMt", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "4830bbb7-0810-4c05-a885-80fd1d0e9e24" + }, + "execution_count": 304, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n", + " [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 14. How to add a border (filled with 0's) around an existing array?\n", + "\n", + "(hint: 인덱싱 사용)\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "# before\n", + "[[1. 1. 1. 1. 1.]\n", + " [1. 1. 1. 1. 1.]\n", + " [1. 1. 1. 1. 1.]\n", + " [1. 1. 1. 1. 1.]\n", + " [1. 1. 1. 1. 1.]]\n", + "\n", + " # after\n", + " [[0. 0. 0. 0. 0.]\n", + " [0. 1. 1. 1. 0.]\n", + " [0. 1. 1. 1. 0.]\n", + " [0. 1. 1. 1. 0.]\n", + " [0. 0. 0. 0. 0.]]\n", + "\n", + "```" + ], + "metadata": { + "id": "BIwX-BiSMUz_" + } + }, + { + "cell_type": "code", + "source": [ + "n14 = np.ones((5,5))\n", + "print('# before\\n',n14)" + ], + "metadata": { + "id": "A4M1huiqTWXy", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "59c3c53a-5a2e-4148-a064-19fd726c342d" + }, + "execution_count": 305, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "# before\n", + " [[1. 1. 1. 1. 1.]\n", + " [1. 1. 1. 1. 1.]\n", + " [1. 1. 1. 1. 1.]\n", + " [1. 1. 1. 1. 1.]\n", + " [1. 1. 1. 1. 1.]]\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "n14[0,:] = 0\n", + "n14[-1,:] = 0\n", + "n14[:,0] = 0\n", + "n14[:,-1] = 0\n", + "\n", + "print('# after\\n',n14)" + ], + "metadata": { + "id": "idWhL4zzTWRO", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "c9235ee1-368d-4132-bb77-f0136be493d7" + }, + "execution_count": 306, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "# after\n", + " [[0. 0. 0. 0. 0.]\n", + " [0. 1. 1. 1. 0.]\n", + " [0. 1. 1. 1. 0.]\n", + " [0. 1. 1. 1. 0.]\n", + " [0. 0. 0. 0. 0.]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 15. What is the result of the following expression?\n", + "\n", + "(실행 후, 결과에 대한 주석 작성해주세요. ex. 출력 결과에 대한 이유)\n", + "\n", + "```python\n", + "0 * np.nan\n", + "np.nan == np.nan\n", + "np.inf > np.nan\n", + "np.nan - np.nan\n", + "np.nan in set([np.nan])\n", + "0.3 == 3 * 0.1\n", + "```" + ], + "metadata": { + "id": "tggOHEUGM9PK" + } + }, + { + "cell_type": "code", + "source": [ + "# nan: nan이 포함된 산술 연산의 결과는 nan이다.\n", + "print(0 * np.nan)\n", + "\n", + "# False: nan은 자기 자신과도 같다고 비교되지 않는다.\n", + "print(np.nan == np.nan)\n", + "\n", + "# False: nan은 크기를 비교할 수 없는 값이다.\n", + "print(np.inf > np.nan)\n", + "\n", + "# nan: nan이 포함된 산술 연산의 결과는 nan이다.\n", + "print(np.nan - np.nan)\n", + "\n", + "# True: set 안에 동일한 np.nan 객체가 존재한다.\n", + "print(np.nan in set([np.nan]))\n", + "\n", + "# False: 부동소수점 표현의 오차 때문에 두 값이 정확히 같지 않다.\n", + "print(0.3 == 3 * 0.1)\n" + ], + "metadata": { + "id": "RmjjLx8_TYNp", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "791be76f-9957-434e-a344-591a18b9d281" + }, + "execution_count": 307, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "nan\n", + "False\n", + "False\n", + "nan\n", + "True\n", + "False\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 16. Normalize a 5x5 random matrix.\n", + "\n", + "(hint: (x - mean) / std)\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[[-1.4765971 0.9582795 -1.29910242 1.0250981 -0.79801651]\n", + " [ 0.57945383 -1.28559078 0.02733238 0.99675052 1.2702088 ]\n", + " [-0.08513084 -1.4686812 -0.78813593 -0.34559303 -1.15052328]\n", + " [ 0.98183813 -1.41255344 0.37190169 1.05697419 -0.02668639]\n", + " [-1.14466851 0.98911205 1.14499256 0.69454882 1.18478886]]\n", + "```" + ], + "metadata": { + "id": "28iOVtXXM8gA" + } + }, + { + "cell_type": "code", + "source": [ + "n16 = np.random.random((5,5))\n", + "n16 = (n16 - np.mean(n16))/np.std(n16)\n", + "print(n16)" + ], + "metadata": { + "id": "0L0IE4qOTZW4", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "f465e762-4f5c-471f-d1bc-86ba59eb720e" + }, + "execution_count": 308, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[[-0.38551319 -0.63616468 0.32497696 1.55735672 -1.30009198]\n", + " [ 0.58511149 0.51210116 1.45029994 0.37174798 -0.1253629 ]\n", + " [ 0.61289858 -1.62659177 0.17325018 -0.91963222 1.23243934]\n", + " [ 1.53660945 1.4210004 -1.18867916 -0.98612995 0.82344032]\n", + " [-0.80372366 -1.47548199 0.2104938 -1.27612804 -0.08822675]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 17. Multiply a 5x3 matrix by a 3x2 matrix. (real matrix product)\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[[3. 3.]\n", + " [3. 3.]\n", + " [3. 3.]\n", + " [3. 3.]\n", + " [3. 3.]]\n", + "```" + ], + "metadata": { + "id": "asOmp4b5M8dx" + } + }, + { + "cell_type": "code", + "source": [ + "n17_1 = np.round(np.random.random((5,3)), 1)\n", + "n17_2 = np.round(np.random.random((3,2)), 1)\n", + "print(np.dot(n17_1,n17_2))" + ], + "metadata": { + "id": "01PxOWW5Te7I", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "2ad006d4-12f0-4717-cffe-8899b3242576" + }, + "execution_count": 309, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[[0.85 1.29]\n", + " [1.04 1.52]\n", + " [1.04 1.53]\n", + " [0.66 1. ]\n", + " [0.47 0.78]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 18. What are the result of the following expressions?\n", + "\n", + "(실행 후, 결과에 대한 주석 작성해주세요. ex. 출력 결과에 대한 이유)\n", + "\n", + "```python\n", + "np.array(0) / np.array(0)\n", + "np.array(0) // np.array(0)\n", + "np.array([np.nan]).astype(int).astype(float)\n", + "```" + ], + "metadata": { + "id": "H9zVpsYuM8aR" + } + }, + { + "cell_type": "code", + "source": [ + "print(np.array(0) / np.array(0))\n", + "# 결과: nan\n", + "# 0/0은 정의되지 않은 연산이므로 nan 반환\n", + "\n", + "print(np.array(0) // np.array(0))\n", + "# 결과: 0\n", + "# 정수형 배열에서 0으로 floor division하여 경고가 발생하고 0 반환\n", + "\n", + "print(np.array([np.nan]).astype(int).astype(float))\n", + "# 결과: [-9.22337204e+18]\n", + "# nan을 int로 변환하면서 nan 정보가 사라지고, 그 정수값을 다시 float로 변환" + ], + "metadata": { + "id": "SLP--cFwTh10", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "0f60bd06-2b53-4d0e-9032-cffe6d3eddc5" + }, + "execution_count": 310, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "nan\n", + "0\n", + "[-9.22337204e+18]\n" + ] + }, + { + "output_type": "stream", + "name": "stderr", + "text": [ + "/tmp/ipykernel_1961/451901601.py:1: RuntimeWarning: invalid value encountered in divide\n", + " print(np.array(0) / np.array(0))\n", + "/tmp/ipykernel_1961/451901601.py:5: RuntimeWarning: divide by zero encountered in floor_divide\n", + " print(np.array(0) // np.array(0))\n", + "/tmp/ipykernel_1961/451901601.py:9: RuntimeWarning: invalid value encountered in cast\n", + " print(np.array([np.nan]).astype(int).astype(float))\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 19. Create a 5x5 matrix with row values ranging from 0 to 4.\n", + "\n", + "#### ✅ 출력 예시\n", + "\n", + "```\n", + "[[0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]]\n", + "```" + ], + "metadata": { + "id": "fbi_T8LIO3yc" + } + }, + { + "cell_type": "code", + "source": [ + "n19 = np.zeros((5,5))\n", + "n19 += np.arange(5)\n", + "print(n19)" + ], + "metadata": { + "id": "XHj8J0pLTjrf", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "f051568d-d59e-4495-dd2a-09dfb67df125" + }, + "execution_count": 311, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[[0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 20. Create a random vector of size 10 and sort it.\n", + "\n", + "#### ✅출력 예시\n", + "\n", + "\n", + "```\n", + "[0.11443045 0.16715169 0.32515597 0.38374227 0.48327044 0.78728921\n", + " 0.80523192 0.85915686 0.96930939 0.99586525]\n", + "\n", + "```" + ], + "metadata": { + "id": "cNRIzEzEO_Ft" + } + }, + { + "cell_type": "code", + "source": [ + "n20 = np.random.random(10)\n", + "n20.sort()\n", + "print(n20)" + ], + "metadata": { + "id": "a3lZxnx-Tngw", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "25bb2225-e36e-4f69-ce64-c77fcdc2cbd3" + }, + "execution_count": 312, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[0.0995161 0.19004084 0.3863881 0.46940399 0.50876749 0.62510003\n", + " 0.64231492 0.72711583 0.91583146 0.92882983]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## **판다스**" + ], + "metadata": { + "id": "fkX-tY1oKDq5" + } + }, + { + "cell_type": "markdown", + "metadata": { + "id": "yl7zlBgszyCS" + }, + "source": [ + "\n", + "### 1. Import pandas under the alias `pd`." + ] + }, + { + "cell_type": "code", + "source": [ + "import pandas as pd" + ], + "metadata": { + "id": "ZiANPeHhz00W" + }, + "execution_count": 313, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "2Hk3SuquzyCU" + }, + "source": [ + "### 2. Print the version of pandas that has been imported." + ] + }, + { + "cell_type": "code", + "source": [ + "pd.__version__" + ], + "metadata": { + "id": "i2NtsBbjz1x2", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "outputId": "1fe3ea08-91a5-40b2-cb89-8c5e7fc42f1f" + }, + "execution_count": 314, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'2.2.3'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 314 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "oOTRFQtFzyCV" + }, + "source": [ + "## 3~20번 문제는 아래 데이터프레임으로 진행됩니다.\n", + "\n", + "Consider the following Python dictionary `data` and Python list `labels`:\n", + "\n", + "``` python\n", + "data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],\n", + " 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],\n", + " 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],\n", + " 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}\n", + "\n", + "labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 3. Create a DataFrame `df` from this dictionary `data` which has the index `labels`.\n" + ], + "metadata": { + "id": "m_8US0jJzyCW" + } + }, + { + "cell_type": "code", + "execution_count": 315, + "metadata": { + "id": "7CbS_gtmzyCW", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 362 + }, + "outputId": "a2bb9d93-a464-4e1d-f1d9-ae4964e6771e" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 yes\n", + "b cat 3.0 3 yes\n", + "c snake 0.5 2 no\n", + "d dog NaN 3 yes\n", + "e dog 5.0 2 no\n", + "f cat 2.0 3 no\n", + "g snake 4.5 1 no\n", + "h cat NaN 1 yes\n", + "i dog 7.0 2 no\n", + "j dog 3.0 1 no" + ], + "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", + "
animalagevisitspriority
acat2.51yes
bcat3.03yes
csnake0.52no
ddogNaN3yes
edog5.02no
fcat2.03no
gsnake4.51no
hcatNaN1yes
idog7.02no
jdog3.01no
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df", + "summary": "{\n \"name\": \"df\",\n \"rows\": 10,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"cat\",\n \"snake\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.0077973005261263,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 2.5,\n 3.0,\n 4.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 3,\n \"samples\": [\n 1,\n 3,\n 2\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"no\",\n \"yes\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 315 + } + ], + "source": [ + "# 문제 풀이 전 numpy 임포트\n", + "import numpy as np\n", + "\n", + "data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],\n", + " 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],\n", + " 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],\n", + " 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}\n", + "\n", + "labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']\n", + "\n", + "df = pd.DataFrame(data, index=labels)\n", + "df" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "f2shsFGyzyCW" + }, + "source": [ + "### 4. Display a summary of the basic information about this DataFrame and its data. \n", + "(hint: there is a single method that can be called on the DataFrame)" + ] + }, + { + "cell_type": "code", + "source": [ + "df.info()" + ], + "metadata": { + "id": "BWZpEuGtz7ky", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "ddabfcd4-7584-4221-cb48-f4c8fbe0d584" + }, + "execution_count": 316, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "Index: 10 entries, a to j\n", + "Data columns (total 4 columns):\n", + " # Column Non-Null Count Dtype \n", + "--- ------ -------------- ----- \n", + " 0 animal 10 non-null object \n", + " 1 age 8 non-null float64\n", + " 2 visits 10 non-null int64 \n", + " 3 priority 10 non-null object \n", + "dtypes: float64(1), int64(1), object(2)\n", + "memory usage: 700.0+ bytes\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### 5. Display a summary of the basic statistics about data of this DataFrame. \n", + "(hint: there is a single method that can be called on the DataFrame)" + ], + "metadata": { + "id": "AfbkaEOyzyCX" + } + }, + { + "cell_type": "code", + "source": [ + "df.describe()" + ], + "metadata": { + "id": "wzzc100Oz8c3", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 300 + }, + "outputId": "de41c60e-f7d6-4707-b2fd-37fcb7209fdd" + }, + "execution_count": 317, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " age visits\n", + "count 8.000000 10.000000\n", + "mean 3.437500 1.900000\n", + "std 2.007797 0.875595\n", + "min 0.500000 1.000000\n", + "25% 2.375000 1.000000\n", + "50% 3.000000 2.000000\n", + "75% 4.625000 2.750000\n", + "max 7.000000 3.000000" + ], + "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", + "
agevisits
count8.00000010.000000
mean3.4375001.900000
std2.0077970.875595
min0.5000001.000000
25%2.3750001.000000
50%3.0000002.000000
75%4.6250002.750000
max7.0000003.000000
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "summary": "{\n \"name\": \"df\",\n \"rows\": 8,\n \"fields\": [\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.5474771307751376,\n \"min\": 0.5,\n \"max\": 8.0,\n \"num_unique_values\": 8,\n \"samples\": [\n 3.4375,\n 3.0,\n 8.0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 3.0122099789789663,\n \"min\": 0.8755950357709131,\n \"max\": 10.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 10.0,\n 1.9,\n 2.75\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 317 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "XJ59aPcrzyCX" + }, + "source": [ + "### 6. Return the first 3 rows of the DataFrame `df`." + ] + }, + { + "cell_type": "code", + "source": [ + "df.head(3)" + ], + "metadata": { + "id": "vZro7sh9z_rY", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 143 + }, + "outputId": "b37997fe-fbbe-4cfb-dd91-7f391bf72ef8" + }, + "execution_count": 318, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 yes\n", + "b cat 3.0 3 yes\n", + "c snake 0.5 2 no" + ], + "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", + "
animalagevisitspriority
acat2.51yes
bcat3.03yes
csnake0.52no
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df", + "summary": "{\n \"name\": \"df\",\n \"rows\": 10,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"cat\",\n \"snake\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.0077973005261263,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 2.5,\n 3.0,\n 4.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 3,\n \"samples\": [\n 1,\n 3,\n 2\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"no\",\n \"yes\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 318 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "KBVp0_3ZzyCY" + }, + "source": [ + "### 7. Select just the 'animal' and 'age' columns from the DataFrame `df`." + ] + }, + { + "cell_type": "code", + "source": [ + "df[['animal', 'age']]" + ], + "metadata": { + "id": "pC6sH-1F0AJo", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 362 + }, + "outputId": "2fa725b6-557f-4b68-da67-2a32b1b8f7f4" + }, + "execution_count": 319, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age\n", + "a cat 2.5\n", + "b cat 3.0\n", + "c snake 0.5\n", + "d dog NaN\n", + "e dog 5.0\n", + "f cat 2.0\n", + "g snake 4.5\n", + "h cat NaN\n", + "i dog 7.0\n", + "j dog 3.0" + ], + "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", + "
animalage
acat2.5
bcat3.0
csnake0.5
ddogNaN
edog5.0
fcat2.0
gsnake4.5
hcatNaN
idog7.0
jdog3.0
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "summary": "{\n \"name\": \"df[['animal', 'age']]\",\n \"rows\": 10,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"cat\",\n \"snake\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.0077973005261263,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 2.5,\n 3.0,\n 4.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 319 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "a1giftRYzyCY" + }, + "source": [ + "### 8. Select the data in rows `[3, 4, 8]` **and** in columns `['animal', 'age']`." + ] + }, + { + "cell_type": "code", + "source": [ + "df.loc[df.index[[3,4,8]], ['animal', 'age']]" + ], + "metadata": { + "id": "tkSynFGH0BLD", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 143 + }, + "outputId": "dd47d4d9-dcf8-4d9b-81a9-66d38ab4762d" + }, + "execution_count": 320, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age\n", + "d dog NaN\n", + "e dog 5.0\n", + "i dog 7.0" + ], + "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", + "
animalage
ddogNaN
edog5.0
idog7.0
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "summary": "{\n \"name\": \"df\",\n \"rows\": 3,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 1,\n \"samples\": [\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1.4142135623730951,\n \"min\": 5.0,\n \"max\": 7.0,\n \"num_unique_values\": 2,\n \"samples\": [\n 7.0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 320 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "67sYTLBqzyCY" + }, + "source": [ + "### 9. Select only the rows where the number of visits is greater than 3." + ] + }, + { + "cell_type": "code", + "source": [ + "df[df['visits'] > 3]" + ], + "metadata": { + "id": "d_G0WeMG0Dgd", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 53 + }, + "outputId": "4bea73e8-9f06-479e-f06b-a987b2caa79f" + }, + "execution_count": 321, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "Empty DataFrame\n", + "Columns: [animal, age, visits, priority]\n", + "Index: []" + ], + "text/html": [ + "\n", + "
\n", + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
animalagevisitspriority
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "repr_error": "Out of range float values are not JSON compliant: nan" + } + }, + "metadata": {}, + "execution_count": 321 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "FXX4YRWgzyCY" + }, + "source": [ + "### 10. Select the rows where the age is missing, i.e. it is `NaN`." + ] + }, + { + "cell_type": "code", + "source": [ + "df[df['age'].isna()]" + ], + "metadata": { + "id": "KaV4Ypkj0Ea2", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 112 + }, + "outputId": "18331dfd-af72-4d2d-aeca-3ecd3cb32806" + }, + "execution_count": 322, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "d dog NaN 3 yes\n", + "h cat NaN 1 yes" + ], + "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", + "
animalagevisitspriority
ddogNaN3yes
hcatNaN1yes
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "summary": "{\n \"name\": \"df[df['age']\",\n \"rows\": 2,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"cat\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": null,\n \"min\": null,\n \"max\": null,\n \"num_unique_values\": 0,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 2,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 1,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 322 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "kMH5n-UBzyCZ" + }, + "source": [ + "### 11. Select the rows where the animal is a cat *and* the age is less than 3." + ] + }, + { + "cell_type": "code", + "source": [ + "df[(df['animal'] =='cat') & (df['age'] < 3)]" + ], + "metadata": { + "id": "8sCDh9Ez0FND", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 112 + }, + "outputId": "5ca46825-8d5d-4cbb-96d3-9dd8afbc2fb9" + }, + "execution_count": 323, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 yes\n", + "f cat 2.0 3 no" + ], + "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", + "
animalagevisitspriority
acat2.51yes
fcat2.03no
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "summary": "{\n \"name\": \"df[(df['animal'] =='cat') & (df['age'] < 3)]\",\n \"rows\": 2,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 1,\n \"samples\": [\n \"cat\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.3535533905932738,\n \"min\": 2.0,\n \"max\": 2.5,\n \"num_unique_values\": 2,\n \"samples\": [\n 2.0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 2,\n \"samples\": [\n 3\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"no\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 323 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "62Y0JsYazyCZ" + }, + "source": [ + "### 12. Select the rows the age is between 2 and 4 (inclusive). \n" + ] + }, + { + "cell_type": "code", + "source": [ + "df[(df['age'] >= 2) & (df['age'] <= 4)]" + ], + "metadata": { + "id": "svjvRtgZ0G76", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 174 + }, + "outputId": "0f3121ca-d48d-4d1b-f756-acac3920589e" + }, + "execution_count": 324, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 yes\n", + "b cat 3.0 3 yes\n", + "f cat 2.0 3 no\n", + "j dog 3.0 1 no" + ], + "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", + "
animalagevisitspriority
acat2.51yes
bcat3.03yes
fcat2.03no
jdog3.01no
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "summary": "{\n \"name\": \"df[(df['age'] >= 2) & (df['age'] <= 4)]\",\n \"rows\": 4,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"dog\",\n \"cat\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.47871355387816905,\n \"min\": 2.0,\n \"max\": 3.0,\n \"num_unique_values\": 3,\n \"samples\": [\n 2.5,\n 3.0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 2,\n \"samples\": [\n 3,\n 1\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"no\",\n \"yes\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 324 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "4lIGMIkPzyCZ" + }, + "source": [ + "### 13. Change the age in row 'f' to 1.5." + ] + }, + { + "cell_type": "code", + "source": [ + "df.loc['f', 'age'] = 1.5\n", + "df" + ], + "metadata": { + "id": "h4U4A6Ai0Hvk", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 362 + }, + "outputId": "2933db0a-7e72-4ed3-8bb1-32f76690d22f" + }, + "execution_count": 325, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 yes\n", + "b cat 3.0 3 yes\n", + "c snake 0.5 2 no\n", + "d dog NaN 3 yes\n", + "e dog 5.0 2 no\n", + "f cat 1.5 3 no\n", + "g snake 4.5 1 no\n", + "h cat NaN 1 yes\n", + "i dog 7.0 2 no\n", + "j dog 3.0 1 no" + ], + "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", + "
animalagevisitspriority
acat2.51yes
bcat3.03yes
csnake0.52no
ddogNaN3yes
edog5.02no
fcat1.53no
gsnake4.51no
hcatNaN1yes
idog7.02no
jdog3.01no
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df", + "summary": "{\n \"name\": \"df\",\n \"rows\": 10,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"cat\",\n \"snake\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.065879266282796,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 2.5,\n 3.0,\n 4.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 3,\n \"samples\": [\n 1,\n 3,\n 2\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"no\",\n \"yes\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 325 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "FZzPr9ObzyCZ" + }, + "source": [ + "### 14. Calculate the sum of all visits in `df` (i.e. the total number of visits)." + ] + }, + { + "cell_type": "code", + "source": [ + "print('총 방문객: ', np.sum(df['visits']))" + ], + "metadata": { + "id": "FXLAUqR40I6C", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "15da51f8-62d3-4bc6-fb85-c186309ad31c" + }, + "execution_count": 326, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "총 방문객: 19\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PO0xpJ_OzyCa" + }, + "source": [ + "### 15. Calculate the mean age for each different animal in `df`." + ] + }, + { + "cell_type": "code", + "source": [ + "print('고양이 평균 나이: ', np.mean(df[df['animal'] == 'cat']['age']))\n", + "print('강아지 평균 나이: ', np.mean(df[df['animal'] == 'dog']['age']))\n", + "print('뱀 평균 나이: ', np.mean(df[df['animal'] == 'snake']['age']))" + ], + "metadata": { + "id": "L63WRx_20Kta", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "a6b02ef1-a58d-433c-c287-14a7703e8222" + }, + "execution_count": 327, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "고양이 평균 나이: 2.3333333333333335\n", + "강아지 평균 나이: 5.0\n", + "뱀 평균 나이: 2.5\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "YfVdzQXIzyCa" + }, + "source": [ + "### 16. Append a new row 'k' to `df` with your choice of values for each column. Then delete that row to return the original DataFrame." + ] + }, + { + "cell_type": "code", + "source": [ + "df.loc['k'] = ['cat', 3.5, 5, 'yes']\n", + "df" + ], + "metadata": { + "id": "Per12Ekp0Mc0", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 394 + }, + "outputId": "fc7079e3-deca-4bb1-f562-4b7af5b79508" + }, + "execution_count": 328, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 yes\n", + "b cat 3.0 3 yes\n", + "c snake 0.5 2 no\n", + "d dog NaN 3 yes\n", + "e dog 5.0 2 no\n", + "f cat 1.5 3 no\n", + "g snake 4.5 1 no\n", + "h cat NaN 1 yes\n", + "i dog 7.0 2 no\n", + "j dog 3.0 1 no\n", + "k cat 3.5 5 yes" + ], + "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", + "
animalagevisitspriority
acat2.51yes
bcat3.03yes
csnake0.52no
ddogNaN3yes
edog5.02no
fcat1.53no
gsnake4.51no
hcatNaN1yes
idog7.02no
jdog3.01no
kcat3.55yes
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df", + "summary": "{\n \"name\": \"df\",\n \"rows\": 11,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"cat\",\n \"snake\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1.9329022507905336,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 8,\n \"samples\": [\n 3.0,\n 4.5,\n 2.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 5,\n \"num_unique_values\": 4,\n \"samples\": [\n 3,\n 5,\n 1\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"no\",\n \"yes\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 328 + } + ] + }, + { + "cell_type": "code", + "source": [ + "df.drop('k', inplace=True)\n", + "df" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 362 + }, + "id": "sb19lMVLADP-", + "outputId": "60c48952-10e4-4524-fe09-c88c27d419dd" + }, + "execution_count": 329, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 yes\n", + "b cat 3.0 3 yes\n", + "c snake 0.5 2 no\n", + "d dog NaN 3 yes\n", + "e dog 5.0 2 no\n", + "f cat 1.5 3 no\n", + "g snake 4.5 1 no\n", + "h cat NaN 1 yes\n", + "i dog 7.0 2 no\n", + "j dog 3.0 1 no" + ], + "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", + "
animalagevisitspriority
acat2.51yes
bcat3.03yes
csnake0.52no
ddogNaN3yes
edog5.02no
fcat1.53no
gsnake4.51no
hcatNaN1yes
idog7.02no
jdog3.01no
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df", + "summary": "{\n \"name\": \"df\",\n \"rows\": 10,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"cat\",\n \"snake\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.065879266282796,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 2.5,\n 3.0,\n 4.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 3,\n \"samples\": [\n 1,\n 3,\n 2\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"no\",\n \"yes\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 329 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "tDkk_tHszyCa" + }, + "source": [ + "### 17. Count the number of each type of animal in `df`." + ] + }, + { + "cell_type": "code", + "source": [ + "df['animal'].value_counts()" + ], + "metadata": { + "id": "v21izXST0NTR", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 209 + }, + "outputId": "fbc85641-e985-4ddf-cc24-927c8dd70d63" + }, + "execution_count": 330, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "animal\n", + "cat 4\n", + "dog 4\n", + "snake 2\n", + "Name: count, dtype: int64" + ], + "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", + "
count
animal
cat4
dog4
snake2
\n", + "

" + ] + }, + "metadata": {}, + "execution_count": 330 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "cwz4s5RYzyCa" + }, + "source": [ + "### 18. Sort `df` first by the values in the 'age' in *decending* order, then by the value in the 'visits' column in *ascending* order (so row `i` should be first, and row `d` should be last).\n", + "#### ✅출력 예시" + ] + }, + { + "cell_type": "markdown", + "source": [ + " index |animal\t| age\t|visits|\tpriority\n", + "---|---|---|---|---\n", + "i|\tdog|\t7.0|\t2|\tno\n", + "e|\tdog|\t5.0|\t2|\tno\n", + "g|\tsnake|\t4.5|\t1|\tno\n", + "j|\tdog|\t3.0|\t1|\tno\n", + "b|\tcat|\t3.0|\t3|\tyes\n", + "a|\tcat|\t2.5|\t1|\tyes\n", + "f|\tcat|\t1.5|\t3|\tno\n", + "c|\tsnake|\t0.5|\t2|\tno\n", + "h|\tcat|\tNaN|\t1|\tyes\n", + "d|\tdog|\tNaN|\t3|\tyes" + ], + "metadata": { + "id": "YILpLKeqzyCa" + } + }, + { + "cell_type": "code", + "source": [ + "df.sort_values(by=['age', 'visits'], ascending=[False, True])" + ], + "metadata": { + "id": "2l6Pb7T10Qpi", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 362 + }, + "outputId": "b3a95f62-e6bb-4e8c-a14c-b2dff06656a3" + }, + "execution_count": 331, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "i dog 7.0 2 no\n", + "e dog 5.0 2 no\n", + "g snake 4.5 1 no\n", + "j dog 3.0 1 no\n", + "b cat 3.0 3 yes\n", + "a cat 2.5 1 yes\n", + "f cat 1.5 3 no\n", + "c snake 0.5 2 no\n", + "h cat NaN 1 yes\n", + "d dog NaN 3 yes" + ], + "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", + "
animalagevisitspriority
idog7.02no
edog5.02no
gsnake4.51no
jdog3.01no
bcat3.03yes
acat2.51yes
fcat1.53no
csnake0.52no
hcatNaN1yes
ddogNaN3yes
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "summary": "{\n \"name\": \"df\",\n \"rows\": 10,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"dog\",\n \"snake\",\n \"cat\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.065879266282796,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 7.0,\n 5.0,\n 1.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 3,\n \"samples\": [\n 2,\n 1,\n 3\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 2,\n \"samples\": [\n \"yes\",\n \"no\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 331 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6hfE99qHzyCb" + }, + "source": [ + "### 19. The 'priority' column contains the values 'yes' and 'no'. Replace this column with a column of boolean values: 'yes' should be `True` and 'no' should be `False`. \n", + "(hint: `map`)" + ] + }, + { + "cell_type": "code", + "source": [ + "df['priority'] = df['priority'].map({'yes': True, 'no': False})\n", + "df" + ], + "metadata": { + "id": "lPLmBRUP0SnR", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 362 + }, + "outputId": "179bd4ec-34c2-40db-d3c9-dfc8a665bcde" + }, + "execution_count": 332, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 True\n", + "b cat 3.0 3 True\n", + "c snake 0.5 2 False\n", + "d dog NaN 3 True\n", + "e dog 5.0 2 False\n", + "f cat 1.5 3 False\n", + "g snake 4.5 1 False\n", + "h cat NaN 1 True\n", + "i dog 7.0 2 False\n", + "j dog 3.0 1 False" + ], + "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", + "
animalagevisitspriority
acat2.51True
bcat3.03True
csnake0.52False
ddogNaN3True
edog5.02False
fcat1.53False
gsnake4.51False
hcatNaN1True
idog7.02False
jdog3.01False
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df", + "summary": "{\n \"name\": \"df\",\n \"rows\": 10,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"cat\",\n \"snake\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.065879266282796,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 2.5,\n 3.0,\n 4.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 3,\n \"samples\": [\n 1,\n 3,\n 2\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"boolean\",\n \"num_unique_values\": 2,\n \"samples\": [\n false,\n true\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 332 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ycaIJncEzyCb" + }, + "source": [ + "### 20. In the 'animal' column, change the 'snake' entries to 'python'. " + ] + }, + { + "cell_type": "code", + "source": [ + "df['animal'] = df['animal'].replace('snake', 'python')" + ], + "metadata": { + "id": "MZelDUlE0Wag" + }, + "execution_count": 333, + "outputs": [] + }, + { + "cell_type": "code", + "source": [ + "# 확인용 df 출력 셀\n", + "df" + ], + "metadata": { + "id": "uYFF5Jew0Xz7", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 362 + }, + "outputId": "68926c6a-e596-478e-aa0b-976c6917bcf4" + }, + "execution_count": 334, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " animal age visits priority\n", + "a cat 2.5 1 True\n", + "b cat 3.0 3 True\n", + "c python 0.5 2 False\n", + "d dog NaN 3 True\n", + "e dog 5.0 2 False\n", + "f cat 1.5 3 False\n", + "g python 4.5 1 False\n", + "h cat NaN 1 True\n", + "i dog 7.0 2 False\n", + "j dog 3.0 1 False" + ], + "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", + "
animalagevisitspriority
acat2.51True
bcat3.03True
cpython0.52False
ddogNaN3True
edog5.02False
fcat1.53False
gpython4.51False
hcatNaN1True
idog7.02False
jdog3.01False
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df", + "summary": "{\n \"name\": \"df\",\n \"rows\": 10,\n \"fields\": [\n {\n \"column\": \"animal\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"cat\",\n \"python\",\n \"dog\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"age\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.065879266282796,\n \"min\": 0.5,\n \"max\": 7.0,\n \"num_unique_values\": 7,\n \"samples\": [\n 2.5,\n 3.0,\n 4.5\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"visits\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 1,\n \"max\": 3,\n \"num_unique_values\": 3,\n \"samples\": [\n 1,\n 3,\n 2\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"priority\",\n \"properties\": {\n \"dtype\": \"boolean\",\n \"num_unique_values\": 2,\n \"samples\": [\n false,\n true\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 334 + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "5YmjKvYizyCb" + }, + "source": [ + "### 21. Given a DataFrame of random numeric values:\n", + "```python\n", + "df = pd.DataFrame(np.random.random(size=(5, 3))) # this is a 5x3 DataFrame of float values\n", + "```\n", + "\n", + "how do you subtract the row mean from each element in the row?" + ] + }, + { + "cell_type": "code", + "source": [ + "# 랜덤 시드 고정\n", + "np.random.seed(2025)\n", + "\n", + "df2 = pd.DataFrame(np.random.random(size=(5, 3)))\n", + "print('# before')\n", + "df2" + ], + "metadata": { + "id": "EeAkDWv40e9J", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 224 + }, + "outputId": "ca2ebb20-d9ac-41a8-ab2f-4f452ffed5df" + }, + "execution_count": 335, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "# before\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " 0 1 2\n", + "0 0.135488 0.887852 0.932606\n", + "1 0.445568 0.388236 0.257596\n", + "2 0.657368 0.492617 0.964238\n", + "3 0.800984 0.455205 0.801058\n", + "4 0.041718 0.769458 0.003171" + ], + "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", + "
012
00.1354880.8878520.932606
10.4455680.3882360.257596
20.6573680.4926170.964238
30.8009840.4552050.801058
40.0417180.7694580.003171
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df2", + "summary": "{\n \"name\": \"df2\",\n \"rows\": 5,\n \"fields\": [\n {\n \"column\": 0,\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.3263890722671568,\n \"min\": 0.041717972818751115,\n \"max\": 0.80098447486944,\n \"num_unique_values\": 5,\n \"samples\": [\n 0.44556816404759514,\n 0.041717972818751115,\n 0.6573675854710377\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": 1,\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.2173169287995258,\n \"min\": 0.3882355461139826,\n \"max\": 0.887851702730378,\n \"num_unique_values\": 5,\n \"samples\": [\n 0.3882355461139826,\n 0.7694578719378116,\n 0.49261693750626245\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": 2,\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.4349780943172552,\n \"min\": 0.0031711167552942454,\n \"max\": 0.9642384192500572,\n \"num_unique_values\": 5,\n \"samples\": [\n 0.25759643530115894,\n 0.0031711167552942454,\n 0.9642384192500572\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 335 + } + ] + }, + { + "cell_type": "code", + "source": [ + "df2 = df2.sub(df2.mean(axis=1), axis=0)\n", + "print('# after')\n", + "df2" + ], + "metadata": { + "id": "Z24qNGpgKEVi", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 224 + }, + "outputId": "e730515c-439e-425e-b299-f675c6e075b4" + }, + "execution_count": 336, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "# after\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " 0 1 2\n", + "0 -0.516494 0.235870 0.280624\n", + "1 0.081768 0.024435 -0.106204\n", + "2 -0.047373 -0.212124 0.259497\n", + "3 0.115235 -0.230544 0.115309\n", + "4 -0.229731 0.498009 -0.268278" + ], + "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", + "
012
0-0.5164940.2358700.280624
10.0817680.024435-0.106204
2-0.047373-0.2121240.259497
30.115235-0.2305440.115309
4-0.2297310.498009-0.268278
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df2", + "summary": "{\n \"name\": \"df2\",\n \"rows\": 5,\n \"fields\": [\n {\n \"column\": 0,\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.2600799877766293,\n \"min\": -0.5164936717536524,\n \"max\": 0.1152351926457702,\n \"num_unique_values\": 5,\n \"samples\": [\n 0.08176811556001623,\n -0.22973101435186788,\n -0.04737339527141471\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": 1,\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.30921884463997473,\n \"min\": -0.230543997014095,\n \"max\": 0.4980088847671926,\n \"num_unique_values\": 5,\n \"samples\": [\n 0.02443549762640368,\n 0.4980088847671926,\n -0.21212404323618994\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": 2,\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.23814416048884277,\n \"min\": -0.26827787041532475,\n \"max\": 0.2806238044548883,\n \"num_unique_values\": 5,\n \"samples\": [\n -0.10620361318641997,\n -0.26827787041532475,\n 0.25949743850760476\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 336 + } + ] + }, + { + "cell_type": "code", + "source": [], + "metadata": { + "id": "2Nk546r4FZj2" + }, + "execution_count": 336, + "outputs": [] + } + ] +} \ No newline at end of file diff --git "a/Week1\354\230\210\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.ipynb" "b/Week1\354\230\210\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.ipynb" new file mode 100644 index 0000000..9a02fd3 --- /dev/null +++ "b/Week1\354\230\210\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.ipynb" @@ -0,0 +1,6309 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "source": [ + "# **PART 3 넘파이**" + ], + "metadata": { + "id": "xq7-fc-nVrgw" + }, + "id": "xq7-fc-nVrgw" + }, + { + "cell_type": "markdown", + "source": [ + "# 넘파이 ndarray 개요\n", + "* 넘파이 기반 데이터 타입 = ndarray -> 다차원배열 생성 및 연산 지원\n", + "* np.array() : ndarray로 변환\n", + "\n", + "* .shape: ndarray의 행,열 크기를 튜플로 표현\n", + "\n", + "* .ndim: 배열의 차원 수 확인\n", + "\n", + "* ** 데이터 값이 같아도 차원 표현이 다르면 다른 형태로 취급 -> 알고리즘 입출력 시 차원 불일치로 오류 발생 가능\n", + "\n" + ], + "metadata": { + "id": "RMTTlGmvQLP5" + }, + "id": "RMTTlGmvQLP5" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "92eda461-7909-4934-8f24-8666f7e5129f", + "metadata": { + "id": "92eda461-7909-4934-8f24-8666f7e5129f", + "outputId": "331c449a-b73c-48da-bea4-9fe3fbdbaf53" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "array1 type: \n", + "array1 array 형태: (3,)\n", + "array2 type: \n", + "array2 array 형태: (2, 3)\n", + "array3 type: \n", + "array3 array 형태: (1, 3)\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "\n", + "array1 = np.array([1,2,3])\n", + "print('array1 type:', type(array1))\n", + "print('array1 array 형태:', array1.shape)\n", + "\n", + "array2 = np.array([[1,2,3],[2,3,4]])\n", + "print('array2 type:', type(array2))\n", + "print('array2 array 형태:', array2.shape)\n", + "\n", + "array3 = np.array([[1,2,3]])\n", + "print('array3 type:', type(array3))\n", + "print('array3 array 형태:', array3.shape)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a741eb3c-ff34-4cd1-912c-8b8d22a8dcae", + "metadata": { + "id": "a741eb3c-ff34-4cd1-912c-8b8d22a8dcae", + "outputId": "72730959-4cac-40eb-c13f-0a2d10234c4f" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "array1: 1차원, array2: 2차원, array3: 2차원\n" + ] + } + ], + "source": [ + "print('array1: {0}차원, array2: {1}차원, array3: {2}차원'.format(array1.ndim, array2.ndim, array3.ndim))" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# ndarray의 데이터 타입\n", + "\n", + "\n", + "* type() : 자료형\n", + "* .dtype : 데이터값의 유형\n", + "* 숫자, 문자열, 불 등 가능\n", + "* 하나의 ndarray 내에는 동일한 데이터 타입만 허용 (서로 다른 타입이 섞인 리스트를 변환하면 더 큰 타입으로 일괄 변환)\n", + "\n" + ], + "metadata": { + "id": "EANaIv7ZRsvH" + }, + "id": "EANaIv7ZRsvH" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b07ae447-fce3-4520-a1d9-7b35d6b3fdc0", + "metadata": { + "id": "b07ae447-fce3-4520-a1d9-7b35d6b3fdc0", + "outputId": "60bf3d17-b71b-4c1f-bde8-efe8c927ba6a" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "[1 2 3] int64\n" + ] + } + ], + "source": [ + "list1 = [1,2,3]\n", + "print(type(list1))\n", + "array1 = np.array(list1)\n", + "print(type(array1))\n", + "print(array1, array1.dtype)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "adc25cf3-f68c-4203-b7e9-09230d3592c8", + "metadata": { + "id": "adc25cf3-f68c-4203-b7e9-09230d3592c8", + "outputId": "dcf7b402-e6f6-48fc-d11d-67444f465bb9" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['1' '2' 'test'] \u001b[39m\u001b[32m1\u001b[39m array1.reshape(\u001b[32m4\u001b[39m, \u001b[32m3\u001b[39m)\n", + "\u001b[31mValueError\u001b[39m: cannot reshape array of size 10 into shape (4,3)" + ] + } + ], + "source": [ + "array1.reshape(4, 3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c59ee65d-a0f3-40d3-92aa-8316f9d1306d", + "metadata": { + "id": "c59ee65d-a0f3-40d3-92aa-8316f9d1306d", + "outputId": "75cdc877-4f4b-445b-98b1-ed148ce81d17" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0 1 2 3 4 5 6 7 8 9]\n", + "array2 shape: (2, 5)\n", + "array3 shape: (5, 2)\n" + ] + } + ], + "source": [ + "array1 = np.arange(10)\n", + "print(array1)\n", + "array2 = array1.reshape(-1,5)\n", + "print('array2 shape:', array2.shape)\n", + "array3 = array1.reshape(5,-1)\n", + "print('array3 shape:', array3.shape)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1ff99710-3d3e-4828-a9aa-e7d25136325f", + "metadata": { + "id": "1ff99710-3d3e-4828-a9aa-e7d25136325f", + "outputId": "24d0bd98-ffed-453a-a2d8-eeec40612094" + }, + "outputs": [ + { + "ename": "AttributeError", + "evalue": "module 'numpy' has no attribute 'arrange'", + "output_type": "error", + "traceback": [ + "\u001b[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[16]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m array1 = np.arrange(\u001b[32m10\u001b[39m)\n\u001b[32m 2\u001b[39m array4 = array1.reshape(-\u001b[32m1\u001b[39m,\u001b[32m4\u001b[39m)\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\numpy\\__init__.py:792\u001b[39m, in \u001b[36m__getattr__\u001b[39m\u001b[34m(attr)\u001b[39m\n\u001b[32m 789\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mnumpy\u001b[39;00m\u001b[34;01m.\u001b[39;00m\u001b[34;01mchar\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mas\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mchar\u001b[39;00m\n\u001b[32m 790\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m char.chararray\n\u001b[32m--> \u001b[39m\u001b[32m792\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mAttributeError\u001b[39;00m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mmodule \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[34m__name__\u001b[39m\u001b[38;5;132;01m!r}\u001b[39;00m\u001b[33m has no attribute \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mattr\u001b[38;5;132;01m!r}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", + "\u001b[31mAttributeError\u001b[39m: module 'numpy' has no attribute 'arrange'" + ] + } + ], + "source": [ + "array1 = np.arrange(10)\n", + "array4 = array1.reshape(-1,4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8d718e2a-c68c-4bb3-8a69-216cbf63f971", + "metadata": { + "id": "8d718e2a-c68c-4bb3-8a69-216cbf63f971", + "outputId": "c07e5c1c-66d1-4661-81fb-1bae8e54cdd0" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "array3d:\n", + " [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]\n", + "array5:\n", + " [[0], [1], [2], [3], [4], [5], [6], [7]]\n", + "array5 shape: (8, 1)\n", + "array6:\n", + " [[0], [1], [2], [3], [4], [5], [6], [7]]\n", + "array6 shape: (8, 1)\n" + ] + } + ], + "source": [ + "array1 = np.arange(8)\n", + "array3d = array1.reshape((2,2,2))\n", + "print('array3d:\\n', array3d.tolist())\n", + "\n", + "# 3차원 ndarray를 2차원 ndarray로 변환\n", + "array5 = array3d.reshape(-1,1)\n", + "print('array5:\\n', array5.tolist())\n", + "print('array5 shape:', array5.shape)\n", + "\n", + "# 1차원 ndarray를 2차원 ndarray로 변환\n", + "array6 = array1.reshape(-1,1)\n", + "print('array6:\\n', array6.tolist())\n", + "print('array6 shape:', array6.shape)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# 인덱싱 (넘파이 ndarray의 데이터 세트 선택하기)\n", + "\n", + "* 단일 값 추출: [] 안에 위치 인덱스 지정\n", + "* 슬라이싱: ':'로 연속 구간 추출\n", + "* 팬시 인덱싱: 인덱스 집합을 지정해 해당 위치들을 한 번에 추출\n", + "* 불린 인덱싱: 조건식을 [] 안에 기재 -> True 위치의 데이터만 반환 (for/if문 없이 조건 필터링)\n", + "* 2차원 이상은 [row, col]로 접근 -- axis 0 = row(행)방향, axis 1 = column(열) 방향" + ], + "metadata": { + "id": "oC-5lyjSV6vU" + }, + "id": "oC-5lyjSV6vU" + }, + { + "cell_type": "markdown", + "source": [ + "**단일 값 추출**" + ], + "metadata": { + "id": "LZ2moqztZX0M" + }, + "id": "LZ2moqztZX0M" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "45b51906-1810-4bb3-993e-7898c9e6af1f", + "metadata": { + "id": "45b51906-1810-4bb3-993e-7898c9e6af1f", + "outputId": "6d0c6fad-9cd0-4bf4-d1f9-efefbd1eb56e" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "array1: [1 2 3 4 5 6 7 8 9]\n", + "value: 3\n", + "\n" + ] + } + ], + "source": [ + "# 1부터 9까지의 1차원 ndarray 생성\n", + "array1 = np.arange(start = 1, stop = 10)\n", + "print('array1:', array1)\n", + "# index는 0부터 시작하므로 array1[2]는 3번째 index 위치의 데이터값을 의미\n", + "value = array1[2]\n", + "print('value:', value)\n", + "print(type(value))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "70b1fd02-958e-4d14-925f-5fddc2c09639", + "metadata": { + "id": "70b1fd02-958e-4d14-925f-5fddc2c09639", + "outputId": "9538f441-3b40-42b9-9d43-34fb87b57251" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "맨 뒤의 값: 9 맨 뒤에서 두 번째 값: 8\n" + ] + } + ], + "source": [ + "print('맨 뒤의 값:', array1[-1], '맨 뒤에서 두 번째 값:', array1[-2])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "78a7a747-091a-4ea7-a145-7acea1fffcba", + "metadata": { + "id": "78a7a747-091a-4ea7-a145-7acea1fffcba", + "outputId": "e375f839-6960-48ec-e39d-09c064db0965" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "array1: [9 2 3 4 5 6 7 8 0]\n" + ] + } + ], + "source": [ + "array1[0] = 9\n", + "array1[8] = 0\n", + "print('array1:', array1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3955c10d-2440-46c7-a921-8ec6265f78c2", + "metadata": { + "id": "3955c10d-2440-46c7-a921-8ec6265f78c2", + "outputId": "7e1d5f20-9779-43f6-bbc1-c185730f15ba" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1 2 3]\n", + " [4 5 6]\n", + " [7 8 9]]\n", + "(row=0, col=0) index 가리키는 값: 1\n", + "(row=0, col=1) index 가리키는 값: 2\n", + "(row=1, col=0) index 가리키는 값: 4\n", + "(row=2, col=2) index 가리키는 값: 9\n" + ] + } + ], + "source": [ + "array1d = np.arange(start = 1, stop = 10)\n", + "array2d = array1d.reshape(3,3)\n", + "print(array2d)\n", + "\n", + "print('(row=0, col=0) index 가리키는 값:', array2d[0,0])\n", + "print('(row=0, col=1) index 가리키는 값:', array2d[0,1])\n", + "print('(row=1, col=0) index 가리키는 값:', array2d[1,0])\n", + "print('(row=2, col=2) index 가리키는 값:', array2d[2,2])" + ] + }, + { + "cell_type": "markdown", + "source": [ + "**슬라이싱**" + ], + "metadata": { + "id": "iEUpmcQeZqAg" + }, + "id": "iEUpmcQeZqAg" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "73501410-754a-4cd4-85d5-42f35f1c8006", + "metadata": { + "id": "73501410-754a-4cd4-85d5-42f35f1c8006", + "outputId": "819e01a1-aa2a-4869-84b9-f0d7363d5355" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1 2 3]\n", + "\n" + ] + } + ], + "source": [ + "array1 = np.arange(start=1, stop=10)\n", + "array3 = array1[0:3]\n", + "print(array3)\n", + "print(type(array3))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6a03557a-f2f2-4145-92a4-7301766e1f49", + "metadata": { + "id": "6a03557a-f2f2-4145-92a4-7301766e1f49", + "outputId": "234081ec-6c3c-4bfa-ae4a-ad9dc77757a5" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1 2 3]\n", + "[4 5 6 7 8 9]\n", + "[1 2 3 4 5 6 7 8 9]\n" + ] + } + ], + "source": [ + "array1 = np.arange(start=1, stop=10)\n", + "array4 = array1[:3]\n", + "print(array4)\n", + "\n", + "array5 = array1[3:]\n", + "print(array5)\n", + "\n", + "array6 = array1[:]\n", + "print(array6)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7d036a3d-7f04-41dc-bf37-6aa829b4b291", + "metadata": { + "id": "7d036a3d-7f04-41dc-bf37-6aa829b4b291", + "outputId": "c3d17265-f94e-491a-897e-447af925f2d4" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "array2d:\n", + " [[1 2 3]\n", + " [4 5 6]\n", + " [7 8 9]]\n", + "array2d[0:2, 0:2] \n", + " [[1 2]\n", + " [4 5]]\n", + "array2d[1:3, 0:3] \n", + " [[4 5 6]\n", + " [7 8 9]]\n", + "array2d[1:3, :] \n", + " [[4 5 6]\n", + " [7 8 9]]\n", + "array2d[:, :] \n", + " [[1 2 3]\n", + " [4 5 6]\n", + " [7 8 9]]\n", + "array2d[:2, 1:] \n", + " [[2 3]\n", + " [5 6]]\n", + "array2d[:2, 0] \n", + " [1 4]\n" + ] + } + ], + "source": [ + "array1d = np.arange(start=1, stop=10)\n", + "array2d = array1d.reshape(3,3)\n", + "print('array2d:\\n', array2d)\n", + "\n", + "print('array2d[0:2, 0:2] \\n', array2d[0:2, 0:2])\n", + "print('array2d[1:3, 0:3] \\n', array2d[1:3, 0:3])\n", + "print('array2d[1:3, :] \\n', array2d[1:3, :])\n", + "print('array2d[:, :] \\n', array2d[:, :])\n", + "print('array2d[:2, 1:] \\n', array2d[:2, 1:])\n", + "print('array2d[:2, 0] \\n', array2d[:2, 0]) # 1차원 ndarray 반환 (단일값 인덱스를 적용했기 때문) 아마??" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "caf8e912-3ca8-4d50-98e3-0398e658ea93", + "metadata": { + "id": "caf8e912-3ca8-4d50-98e3-0398e658ea93", + "outputId": "f04fada6-468b-44a5-b622-701a9f002619" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1 2 3]\n", + "[4 5 6]\n", + "array2d[0] shape: (3,) array2d[1] shape: (3,)\n" + ] + } + ], + "source": [ + "print(array2d[0])\n", + "print(array2d[1])\n", + "print('array2d[0] shape:', array2d[0].shape, 'array2d[1] shape:', array2d[1].shape)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "**팬시 인덱싱**" + ], + "metadata": { + "id": "ynJYoRTiZ2LC" + }, + "id": "ynJYoRTiZ2LC" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e3d14571-18f9-46ae-a95e-c71007d22459", + "metadata": { + "id": "e3d14571-18f9-46ae-a95e-c71007d22459", + "outputId": "dbe1dce5-5f8a-44fb-eced-46de462d17f4" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "array2d[[0,1],2] => [3, 6]\n", + "array2d[[0,1],0:2] => [[1, 2], [4, 5]]\n", + "array2d[[0,1]] => [[1, 2, 3], [4, 5, 6]]\n" + ] + } + ], + "source": [ + "array1d = np.arange(start= 1, stop=10)\n", + "array2d = array1d.reshape(3,3)\n", + "\n", + "array3 = array2d[[0,1],2]\n", + "print('array2d[[0,1],2] =>', array3.tolist())\n", + "\n", + "array4 = array2d[[0,1],0:2]\n", + "print('array2d[[0,1],0:2] =>', array4.tolist())\n", + "\n", + "array5 = array2d[[0,1]]\n", + "print('array2d[[0,1]] =>', array5.tolist())" + ] + }, + { + "cell_type": "markdown", + "source": [ + "**불린 인덱싱**" + ], + "metadata": { + "id": "mnqLnUHGZ97w" + }, + "id": "mnqLnUHGZ97w" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "10163533-86b0-4f21-b5b9-0d2d74952d07", + "metadata": { + "id": "10163533-86b0-4f21-b5b9-0d2d74952d07", + "outputId": "21b78758-19be-4062-b588-de4738a7d7f3" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "array1d > 5 불린 인덱싱 결과 값: [6 7 8 9]\n" + ] + } + ], + "source": [ + "array1d = np.arange(start=1, stop=10)\n", + "#[] 안에 array1d > 5 Boolean indexing을 적용\n", + "array3 = array1d[array1d > 5]\n", + "print('array1d > 5 불린 인덱싱 결과 값:', array3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bef06ae4-c277-474d-9494-10909bb1728e", + "metadata": { + "id": "bef06ae4-c277-474d-9494-10909bb1728e", + "outputId": "22f63c6e-a273-487a-eba8-1fd89f6858a0" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([False, False, False, False, False, True, True, True, True])" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "array1d > 5" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "57847e92-f051-4311-9d9d-62302903323b", + "metadata": { + "id": "57847e92-f051-4311-9d9d-62302903323b", + "outputId": "27b8af3b-d6ae-4c28-8b22-3d69f96ea00a" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "불린 인덱스로 필터링 결과 : [6 7 8 9]\n" + ] + } + ], + "source": [ + "boolean_indexes = np.array([False, False, False, False, False, True, True, True, True])\n", + "array3 = array1d[boolean_indexes]\n", + "print('불린 인덱스로 필터링 결과 :', array3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "adc7360a-4f87-49b1-81ef-7f75e00ec646", + "metadata": { + "id": "adc7360a-4f87-49b1-81ef-7f75e00ec646", + "outputId": "8758957c-b329-4ad7-d9e1-e8e72a8a2683" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "일반 텍스트로 필터링 결과 : [6 7 8 9]\n" + ] + } + ], + "source": [ + "indexes = np.array([5,6,7,8])\n", + "array4 = array1d[indexes]\n", + "print('일반 텍스트로 필터링 결과 :', array4)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# 행렬의 정렬\n", + "* np.sort( ): 원본은 유지, 정렬된 배열은 반환\n", + "* .sort(): 원본 자체를 정렬 (반환값은 None)\n", + "* 기본은 오름차순, [::-1]을 적용하면 내림차순\n", + "* 2차원 이상은 axis 지정으로 row/col 방향 정렬 가능\n", + "* **np.argsort(): 정렬된 결과의 원본 인덱스를 반환 -> ndarray는 메타 데이터를 못 가지므로, 값과 연결된 다른 정보(예: 이름)를 찾을 때 활용**" + ], + "metadata": { + "id": "RJMnKQjzaExb" + }, + "id": "RJMnKQjzaExb" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e075b4ff-f1f6-4216-bfed-6e05bfd5ebf1", + "metadata": { + "id": "e075b4ff-f1f6-4216-bfed-6e05bfd5ebf1", + "outputId": "c23e7e64-9338-480d-8a34-c0cc54edb9ad" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "원본 행렬: [3 1 9 5]\n", + "np.sort() 호출 후 빈환된 정렬 행렬: [1 3 5 9]\n", + "np.sort() 호출 후 원본 행렬: [3 1 9 5]\n", + "org_array.sort() 호출 후 반환된 행렬: None\n", + "org_array.sort() 호출 후 원본 행렬: [1 3 5 9]\n" + ] + } + ], + "source": [ + "org_array = np.array([3,1,9,5])\n", + "print('원본 행렬:', org_array)\n", + "# np.sort()로 정렬\n", + "sort_array1 = np.sort(org_array)\n", + "print('np.sort() 호출 후 빈환된 정렬 행렬:', sort_array1)\n", + "print('np.sort() 호출 후 원본 행렬:', org_array)\n", + "#ndarray.sort()로 정렬\n", + "sort_array2 = org_array.sort()\n", + "print('org_array.sort() 호출 후 반환된 행렬:', sort_array2)\n", + "print('org_array.sort() 호출 후 원본 행렬:', org_array)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "21d8bdcf-f5dd-4cdd-bdd1-1f8054a68abb", + "metadata": { + "id": "21d8bdcf-f5dd-4cdd-bdd1-1f8054a68abb", + "outputId": "acb9abcb-605c-499d-b8a0-439ea57c475d" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "내림차순으로 정렬: [9 5 3 1]\n" + ] + } + ], + "source": [ + "sort_array1_desc = np.sort(org_array)[::-1]\n", + "print('내림차순으로 정렬:', sort_array1_desc)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "248cbc34-5423-42ca-938e-bbd7e8359033", + "metadata": { + "id": "248cbc34-5423-42ca-938e-bbd7e8359033", + "outputId": "9f9c2855-bc31-4ac5-c2d5-0e73b231c913" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "로우 방향으로 정렬:\n", + " [[ 7 1]\n", + " [ 8 12]]\n", + "칼럼 방향으로 정렬:\n", + " [[ 8 12]\n", + " [ 1 7]]\n" + ] + } + ], + "source": [ + "array2d = np.array([[8,12],\n", + " [7,1]])\n", + "\n", + "sort_array2d_axis0 = np.sort(array2d, axis=0) # 0 -> 로우 방향 = 세로 방향\n", + "print('로우 방향으로 정렬:\\n', sort_array2d_axis0)\n", + "\n", + "sort_array2d_axis1 = np.sort(array2d, axis=1) # 1 -> 칼럼 방향 = 가로 방향\n", + "print('칼럼 방향으로 정렬:\\n', sort_array2d_axis1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cfb417a2-5ae5-459b-81b2-1a895bae839e", + "metadata": { + "id": "cfb417a2-5ae5-459b-81b2-1a895bae839e", + "outputId": "2f737931-53e6-4396-cf4f-a0deb7c553c7" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "행렬 정렬 시 원본 행렬의 인덱스: [1 0 3 2]\n" + ] + } + ], + "source": [ + "org_array = np.array([3,1,9,5])\n", + "sort_indices = np.argsort(org_array)\n", + "print(type(sort_indices))\n", + "print('행렬 정렬 시 원본 행렬의 인덱스:', sort_indices)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "44e9f038-6463-49b7-baa0-5be57ef20395", + "metadata": { + "id": "44e9f038-6463-49b7-baa0-5be57ef20395", + "outputId": "7a941101-d2f8-4008-e6d6-86bc3dc9a79d" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "행렬 내림차순 정렬 시 원본 행렬의 인덱스: [2 3 0 1]\n" + ] + } + ], + "source": [ + "org_array = np.array([3,1,9,5])\n", + "sort_indices_desc = np.argsort(org_array)[::-1]\n", + "print('행렬 내림차순 정렬 시 원본 행렬의 인덱스:', sort_indices_desc)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "**argsort**" + ], + "metadata": { + "id": "BUXMSihKcYiD" + }, + "id": "BUXMSihKcYiD" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df094541-7425-436c-bf65-4d809bf2a0c3", + "metadata": { + "id": "df094541-7425-436c-bf65-4d809bf2a0c3", + "outputId": "836a566b-58a6-4515-9408-e58f15088889" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "성적 오름차순 정렬 시 score_array의 인덱스: [0 2 4 1 3]\n", + "성적 오름차순으로 name_array의 이름 출려: ['John' 'Sarah' 'Samuel' 'Mike' 'Kate']\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "\n", + "name_array = np.array(['John', 'Mike', 'Sarah', 'Kate', 'Samuel'])\n", + "score_array = np.array([78, 95, 84, 98, 88])\n", + "\n", + "sort_indices_asc = np.argsort(score_array)\n", + "print('성적 오름차순 정렬 시 score_array의 인덱스:', sort_indices_asc)\n", + "print('성적 오름차순으로 name_array의 이름 출려:', name_array[sort_indices_asc])" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# 선형대수 연산 - 행렬 내적과 전치 행렬 구하기\n", + "* np.dot(): 행렬 내적\n", + "* np.transpose(): 전치 행렬" + ], + "metadata": { + "id": "7JH2xlHWcf1y" + }, + "id": "7JH2xlHWcf1y" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a98d56f9-d9ad-4d1a-b4c6-0a114e4da1c0", + "metadata": { + "id": "a98d56f9-d9ad-4d1a-b4c6-0a114e4da1c0", + "outputId": "30e3cf03-cf90-4da3-bda5-7c7b0a1c2e36" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "행렬 내적 결과:\n", + " [[ 58 64]\n", + " [139 154]]\n" + ] + } + ], + "source": [ + "A = np.array([[1,2,3],\n", + " [4,5,6]])\n", + "B = np.array([[7,8],\n", + " [9,10],\n", + " [11,12]])\n", + "dot_product = np.dot(A,B)\n", + "print('행렬 내적 결과:\\n', dot_product)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9dc0c1f0-7cb1-443d-8a92-79b1bd2491fe", + "metadata": { + "id": "9dc0c1f0-7cb1-443d-8a92-79b1bd2491fe", + "outputId": "5c27fdd0-f94c-4262-c274-40711f3c3f15" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A의 전치 행렬:\n", + " [[1 3]\n", + " [2 4]]\n" + ] + } + ], + "source": [ + "A = np.array([[1,2],\n", + " [3,4]])\n", + "transpose_mat = np.transpose(A)\n", + "print('A의 전치 행렬:\\n', transpose_mat)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# **PART 4 판다스**" + ], + "metadata": { + "id": "t_-tiuildGT8" + }, + "id": "t_-tiuildGT8" + }, + { + "cell_type": "markdown", + "source": [ + "# 판다스 개요\n", + "* 파이썬 데이터 처리 대표 라이브러리 - 2차원 (행x열) 데이터 처리에 특화\n", + "* 넘파이보다 고수준 편리한 API 제공\n", + "* 리스트, 딕셔너리, 넘파이, ndarray, CSV 등 다양한 소스를 손쉽게 DataFrame으로 변환" + ], + "metadata": { + "id": "ALmTqWVvdJbk" + }, + "id": "ALmTqWVvdJbk" + }, + { + "cell_type": "markdown", + "source": [ + "# DataFrame 객체\n", + "* DataFrame: 여러 행과 열로 이루워진 2차원 데이터 구조체 (판다스의 핵심 객체)" + ], + "metadata": { + "id": "jG3npeH-gAZp" + }, + "id": "jG3npeH-gAZp" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f6a99b51-0ed6-4fa6-b03e-08a5085cf00f", + "metadata": { + "id": "f6a99b51-0ed6-4fa6-b03e-08a5085cf00f" + }, + "outputs": [], + "source": [ + "import pandas as pd" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# DataFrame 로딩 & 기본 정보 확인\n", + "\n", + "* pd.read_csv(데이터파일경로명) -> 데이터를 DataFrame으로 로딩\n", + "* .head(n): 맨앞 n개의 로우를 반환 (Default는 5개)\n", + "* .shape: (행,열) 튜플 반환\n", + "* .info(): 칼럼별 데이터 타입, Null이 아닌 데이터 건수, 전체 메모리 사용량 요약\n", + "* .describe(): 숫자형 칼럼의 분포 요약 -> 데이터 분포 파악에 유용 (object 타입은 자동 제외)\n", + "* [].value_counts(): 특정 칼럼(Series)의 값별 건수 반환 - 분포 확인에 자주 사용 (dropna 인자로 Null 포함 여부 결정)" + ], + "metadata": { + "id": "AoS-gEhXdpap" + }, + "id": "AoS-gEhXdpap" + }, + { + "cell_type": "markdown", + "source": [ + "**DF로딩**" + ], + "metadata": { + "id": "PwyBs5pfm_cZ" + }, + "id": "PwyBs5pfm_cZ" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f22a28f5-7198-420b-8786-7ac9abf5113b", + "metadata": { + "id": "f22a28f5-7198-420b-8786-7ac9abf5113b", + "outputId": "92745da6-8f8d-417c-9f0b-6be3bd4ba8fd" + }, + "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": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df = pd.read_csv(r\"C:\\Users\\송영은\\titanic_train.csv\")\n", + "titanic_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "64825fda-4d26-49d8-b9e1-8b63604a71d7", + "metadata": { + "id": "64825fda-4d26-49d8-b9e1-8b63604a71d7", + "outputId": "8dcfc2bb-871b-4743-e609-6ebe4997bc14" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "titanic 변수 type: \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", + "
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
3411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.01011380353.1000C123S
4503Allen, Mr. William Henrymale35.0003734508.0500NaNS
.......................................
88688702Montvila, Rev. Juozasmale27.00021153613.0000NaNS
88788811Graham, Miss. Margaret Edithfemale19.00011205330.0000B42S
88888903Johnston, Miss. Catherine Helen \"Carrie\"femaleNaN12W./C. 660723.4500NaNS
88989011Behr, Mr. Karl Howellmale26.00011136930.0000C148C
89089103Dooley, Mr. Patrickmale32.0003703767.7500NaNQ
\n", + "

891 rows × 12 columns

\n", + "
" + ], + "text/plain": [ + " 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 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", + "3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 \n", + "4 Allen, Mr. William Henry male 35.0 0 \n", + ".. ... ... ... ... \n", + "886 Montvila, Rev. Juozas male 27.0 0 \n", + "887 Graham, Miss. Margaret Edith female 19.0 0 \n", + "888 Johnston, Miss. Catherine Helen \"Carrie\" female NaN 1 \n", + "889 Behr, Mr. Karl Howell male 26.0 0 \n", + "890 Dooley, Mr. Patrick male 32.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 \n", + "3 0 113803 53.1000 C123 S \n", + "4 0 373450 8.0500 NaN S \n", + ".. ... ... ... ... ... \n", + "886 0 211536 13.0000 NaN S \n", + "887 0 112053 30.0000 B42 S \n", + "888 2 W./C. 6607 23.4500 NaN S \n", + "889 0 111369 30.0000 C148 C \n", + "890 0 370376 7.7500 NaN Q \n", + "\n", + "[891 rows x 12 columns]" + ] + }, + "execution_count": 60, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df = pd.read_csv('titanic_train.csv')\n", + "print('titanic 변수 type:', type(titanic_df))\n", + "titanic_df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "944f286c-f107-49af-97fa-919b2691d5ad", + "metadata": { + "id": "944f286c-f107-49af-97fa-919b2691d5ad", + "outputId": "24766523-5737-4b61-a4c2-7c223c6257dc" + }, + "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": 61, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df.head(3)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "**shape**" + ], + "metadata": { + "id": "9iIkmQh7nFT4" + }, + "id": "9iIkmQh7nFT4" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1d326764-4fc2-4e44-88c1-a507b28d579e", + "metadata": { + "id": "1d326764-4fc2-4e44-88c1-a507b28d579e", + "outputId": "d1e256fb-164e-4c9a-ea25-058f9b43965f" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "DateFrame 크기: (891, 12)\n" + ] + } + ], + "source": [ + "print('DateFrame 크기:', titanic_df.shape)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "**info**" + ], + "metadata": { + "id": "PMgrXdvKnHWf" + }, + "id": "PMgrXdvKnHWf" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bdf62949-f8df-49f4-95f3-54a0eef0c5f2", + "metadata": { + "id": "bdf62949-f8df-49f4-95f3-54a0eef0c5f2", + "outputId": "648fdd87-733f-45a4-9648-e8ba15c1b7cb" + }, + "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 str \n", + " 4 Sex 891 non-null str \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 str \n", + " 9 Fare 891 non-null float64\n", + " 10 Cabin 204 non-null str \n", + " 11 Embarked 889 non-null str \n", + "dtypes: float64(2), int64(5), str(5)\n", + "memory usage: 118.9 KB\n" + ] + } + ], + "source": [ + "titanic_df.info()" + ] + }, + { + "cell_type": "markdown", + "source": [ + "**describe**" + ], + "metadata": { + "id": "4WG24cwKnMVB" + }, + "id": "4WG24cwKnMVB" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1ca1f75c-e0c5-4798-bcc7-627b92b30a72", + "metadata": { + "id": "1ca1f75c-e0c5-4798-bcc7-627b92b30a72", + "outputId": "6326bd90-aed1-4ef9-8ba2-3ab743f3b822" + }, + "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": 64, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df.describe()" + ] + }, + { + "cell_type": "markdown", + "source": [ + "**value_counts**" + ], + "metadata": { + "id": "6hNx7YQcnPiF" + }, + "id": "6hNx7YQcnPiF" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "59a56f46-cde0-42b2-a9b8-747e378196dd", + "metadata": { + "id": "59a56f46-cde0-42b2-a9b8-747e378196dd", + "outputId": "4df998bb-6489-479d-bbd7-10538f104b78" + }, + "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": null, + "id": "61c26666-5c1e-410d-845a-5355ce61ade4", + "metadata": { + "id": "61c26666-5c1e-410d-845a-5355ce61ade4", + "outputId": "c254a6ba-678f-448d-c596-fbf08432c4e1" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "titanic_pclass = titanic_df['Pclass']\n", + "print(type(titanic_pclass))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "37a05e78-ff2a-46dd-86c1-479643f9a5d6", + "metadata": { + "id": "37a05e78-ff2a-46dd-86c1-479643f9a5d6", + "outputId": "f737717b-ceb0-42c2-cf88-5e5600c5e801" + }, + "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": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_pclass.head()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5a681e55-0a7f-4a21-9dc5-a20452d3768f", + "metadata": { + "id": "5a681e55-0a7f-4a21-9dc5-a20452d3768f", + "outputId": "6147e00d-a827-4e1e-e39a-59cea77002e6" + }, + "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": null, + "id": "060daf67-7a80-42f5-9c9c-411819926486", + "metadata": { + "id": "060daf67-7a80-42f5-9c9c-411819926486", + "outputId": "2409a4ff-cfae-4029-a37c-6935f85397c0" + }, + "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", + "# 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": "markdown", + "source": [ + "# 데이터 구조 상호 변환\n", + "\n", + "* 리스트,딕셔너리,넘파이ndarray -> DataFrame \\\n", + ": pd.DataFrame(리스트 등, columns = 칼럼명)\\\n", + " (DataFrame: columns 인자로 칼럼명 지정)\n", + "\n", + "---\n", + "\n", + "\n", + "* DataFrame -> ndarray\\\n", + ": .values 속성 사용 (대부분의 머신러닝 패키지가 ndarray를 입력으로 받으므로 매우 빈번하게 사용)\n", + "* DataFrame -> 리스트: values.tolists()\n", + "* DataFrame -> 딕셔너리: values.to_dict()" + ], + "metadata": { + "id": "4woi6g8mhGQk" + }, + "id": "4woi6g8mhGQk" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1a88d5f-78c4-4a3f-bf85-d9416a030ae7", + "metadata": { + "id": "f1a88d5f-78c4-4a3f-bf85-d9416a030ae7", + "outputId": "d5194314-a422-4032-81d7-f6f02391512e" + }, + "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": [ + "import numpy as np\n", + "\n", + "col_name1=['col1']\n", + "list1 = [1, 2, 3]\n", + "array1 = np.array(list1)\n", + "print('array1 shape:', array1.shape)\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": null, + "id": "3f9258bc-330c-436b-9a3e-420a7b4fe2f3", + "metadata": { + "id": "3f9258bc-330c-436b-9a3e-420a7b4fe2f3", + "outputId": "e64c840f-d615-42a1-9800-63621490cf6a" + }, + "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", + "df_array2 = pd.DataFrame(array2, columns=col_name2)\n", + "print('2차원 ndarray로 만든 DataFrame:\\n', df_array2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c7a6f53-85a6-4d67-a3ea-e265c3ea8bc2", + "metadata": { + "id": "4c7a6f53-85a6-4d67-a3ea-e265c3ea8bc2", + "outputId": "766e1a5c-34a0-43d8-f279-104fcc8b6c5d" + }, + "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)\n", + "print('딕셔너리로 만든 DataFrame:\\n', df_dict)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ebb633cd-e465-4e0c-9b75-a7f7c48e4606", + "metadata": { + "id": "ebb633cd-e465-4e0c-9b75-a7f7c48e4606", + "outputId": "76bae4ad-a7d4-4a94-881a-a46dc8798bf4" + }, + "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\n", + "print('df_dict.values 타입:', type(array3), 'df_dict.values shape:', array3.shape)\n", + "print(array3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13f8228f-0872-4b9f-9fc0-4c1a3a37a006", + "metadata": { + "id": "13f8228f-0872-4b9f-9fc0-4c1a3a37a006", + "outputId": "49a01c82-a64d-48c9-a048-677e60b3025d" + }, + "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": "markdown", + "source": [ + "# 칼럼 생성•수정과 데이터 삭제\n", + "* [] 연산자에 새 칼럼명을 대입하면 칼럼 생성 - 상수 일괄 할당, 기존 칼럼을 가공한 값 할당 모두 가능\n", + "* .drop(['칼럼명', ...] or [인덱스, ...] , axis=@): 데이터 삭제 메서드 - axis = 1 칼럼 삭제, axis = 0은 로우 삭제\n", + "* inplace = False(기본): 원본 유지, 삭제된 결과를 새로 반환\\\n", + "inplace = True: 원본 자체를 변경, 반환값은 None\n" + ], + "metadata": { + "id": "Jk9MiHjxjzzu" + }, + "id": "Jk9MiHjxjzzu" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "18e0bc18-2580-4bd3-8d57-fa813f187f31", + "metadata": { + "id": "18e0bc18-2580-4bd3-8d57-fa813f187f31", + "outputId": "da9bb703-3fa9-498d-d965-1301cad38c24" + }, + "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": 84, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df['Age_0']=0\n", + "titanic_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c616858e-53d4-4da5-aa05-de0863508c12", + "metadata": { + "id": "c616858e-53d4-4da5-aa05-de0863508c12", + "outputId": "df6fae1b-ee4a-41fc-93c1-7b69a27ea6e9" + }, + "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": 85, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df['Age_0']=0\n", + "titanic_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f6b1b1a-41b3-473c-a104-06e69324d9ca", + "metadata": { + "id": "2f6b1b1a-41b3-473c-a104-06e69324d9ca", + "outputId": "7d3bfb1b-832c-4f11-bec8-fe2f30a38e3c" + }, + "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": 87, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "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": null, + "id": "c7e4692b-009d-4019-8ff7-8f9e0d3b71a2", + "metadata": { + "id": "c7e4692b-009d-4019-8ff7-8f9e0d3b71a2", + "outputId": "f789f5e2-c6e7-44b9-8e39-48ba2fa50fd9" + }, + "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": 88, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df['Age_by_10'] = titanic_df['Age_by_10'] + 100\n", + "titanic_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e1aa65b5-cbb2-4f26-bf03-b576b75f1ff8", + "metadata": { + "id": "e1aa65b5-cbb2-4f26-bf03-b576b75f1ff8", + "outputId": "53fd9539-8f79-4a87-ad56-07dbed510516" + }, + "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": 89, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_drop_df = titanic_df.drop('Age_0', axis=1)\n", + "titanic_drop_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3226ca3c-38c1-4512-804a-9683ea3e1fe9", + "metadata": { + "id": "3226ca3c-38c1-4512-804a-9683ea3e1fe9", + "outputId": "f1231f91-d62f-461d-cac1-677d842ecfdd" + }, + "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": 90, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "96e77d40-216d-4569-ad3c-b1f818f7ca96", + "metadata": { + "id": "96e77d40-216d-4569-ad3c-b1f818f7ca96", + "outputId": "d523b656-564c-4b0a-c1e7-65f6d8ddf02c" + }, + "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": 91, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "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": null, + "id": "2c56ff7b-2c7d-4b56-b1bf-3adb5ee39c71", + "metadata": { + "id": "2c56ff7b-2c7d-4b56-b1bf-3adb5ee39c71", + "outputId": "f6b1b17c-e207-4f62-e900-230a9b7333d6" + }, + "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": [ + "pd.set_option('display.width', 1000)\n", + "pd.set_option('display.max_colwidth', 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": "markdown", + "source": [ + "# Index 객체\n", + "\n", + "* Index: 데이터를 고유 식별하는 값 - DataFrame,Series 모두 보유, 연산에선 제외되고 식별용으로만 사용, 한번 생성되면 임의 변경 불가\\\n", + "\\\n", + "* DF.index : 인덱스 객체 추출\n", + "* IND.values : 인덱스 객체를 실제 값 array로 변환\n", + "\n", + "* 식별성 데이터를 1차원 array로 가지고 있다.\n", + "* 단일 값 반환 및 슬라이싱 가능" + ], + "metadata": { + "id": "sjh9C-9ylcwG" + }, + "id": "sjh9C-9ylcwG" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f1620c3-5c3e-4790-b517-c67189ef149d", + "metadata": { + "id": "4f1620c3-5c3e-4790-b517-c67189ef149d", + "outputId": "9f925a71-6324-4b50-9115-4ea40f1d94c1" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Index 객체: 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": [ + "# 원본 파일 다시 로딩\n", + "titanic_df = pd.read_csv('titanic_train.csv')\n", + "# Index 객체 추출\n", + "indexes = titanic_df.index\n", + "print('Index 객체:', indexes)\n", + "# Index 객체를 실제 값 array로 변환\n", + "print('Index 객체 array값:\\n', indexes.values)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "add04ee1-9063-4d80-937c-8c568b2cc20a", + "metadata": { + "id": "add04ee1-9063-4d80-937c-8c568b2cc20a", + "outputId": "c0d1af81-6926-42b5-e89c-7e86e39e1afa" + }, + "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))\n", + "print(indexes.values.shape)\n", + "print(indexes[:5].values)\n", + "print(indexes.values[:5])\n", + "print(indexes[6])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "outputId": "0c9c7cf5-55ea-4320-819a-056630ce5179", + "id": "smsLe4auAjYZ" + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "Index does not support mutable operations", + "output_type": "error", + "traceback": [ + "\u001b[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[61]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m indexes[\u001b[32m0\u001b[39m] = \u001b[32m5\u001b[39m\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:5382\u001b[39m, in \u001b[36mIndex.__setitem__\u001b[39m\u001b[34m(self, key, value)\u001b[39m\n\u001b[32m 5380\u001b[39m \u001b[38;5;129m@final\u001b[39m\n\u001b[32m 5381\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m__setitem__\u001b[39m(\u001b[38;5;28mself\u001b[39m, key, value) -> \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m5382\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\u001b[33m\"\u001b[39m\u001b[33mIndex does not support mutable operations\u001b[39m\u001b[33m\"\u001b[39m)\n", + "\u001b[31mTypeError\u001b[39m: Index does not support mutable operations" + ] + } + ], + "source": [ + "indexes[0] = 5" + ], + "id": "smsLe4auAjYZ" + }, + { + "cell_type": "markdown", + "source": [ + "# Series 객체\n", + "* Series: Index + 칼럼 1개로 구성된 데이터 구조체 (DataFrame = 여러 Series의 집합으로 볼 수 있음)\n", + "* Index 객체를 포함하지만 Series 객체에 연산 함수를 적용할 떄 Index는 연산에서 제외 (Index는 오직 식별용)" + ], + "metadata": { + "id": "mFYDUvjon5Ol" + }, + "id": "mFYDUvjon5Ol" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "04c49d2d-90ca-46c5-a475-2007621ac8cb", + "metadata": { + "id": "04c49d2d-90ca-46c5-a475-2007621ac8cb", + "outputId": "c022f5d7-a9eb-4589-b672-dd7b18e8c196" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Fair Series max 값: 512.3292\n", + "Fair series sum 값: 28693.9493\n", + "sum() Fair Series: 28693.9493\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())\n", + "print('Fair series sum 값:', series_fair.sum())\n", + "print('sum() Fair Series:', sum(series_fair))\n", + "print('Fair Series + 3:\\n', (series_fair + 3).head(3))" + ] + }, + { + "cell_type": "markdown", + "source": [ + "* .reset_index(): DF 및 S에 이 메서드를 수행하면 새롭게 인덱스를 연속 숫자 형으로 할당하며 기존 인덱스는 'index'라는 새로운 칼럼명으로 추가됨" + ], + "metadata": { + "id": "nLJ1EnqUo51J" + }, + "id": "nLJ1EnqUo51J" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2bdc781c-b799-4408-bfce-f80f0590db08", + "metadata": { + "id": "2bdc781c-b799-4408-bfce-f80f0590db08", + "outputId": "8b3da4a7-2ccb-4aa1-df23-24bb97dc47f6" + }, + "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": 102, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_reset_df = titanic_df.reset_index(inplace=False)\n", + "titanic_reset_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cf68ec1c-252c-490e-a73f-c9ed86ba4573", + "metadata": { + "id": "cf68ec1c-252c-490e-a73f-c9ed86ba4573", + "outputId": "82e99461-30e3-4caa-8ec8-64627dd8272b" + }, + "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", + "new_value_counts = value_counts.reset_index(inplace=False)\n", + "print('### After reset index ###')\n", + "print(new_value_counts)\n", + "print('new_value_counts 객체 변수 타입:', type(new_value_counts))" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# 데이터 컬렉션 - [], iloc[], loc[]\n", + "\n", + "* DataFrame 뒤의 []: 칼럼명(또는 칼럼 리스트) 지정 전용으로 쓰는 것이 원칙 (숫자 위치•슬라이싱 사용은 혼동을 유발하므로 비권장, 단 슬라이싱•불린 인덱싱은 예외적으로 동작)\n", + "* iloc[]: 위치 기반 - 행•열 모두 정수 위치 값으로 지정, 라벨을 넣으면 오류\n", + "* loc[]: 명칭(Label) 기반 - 행 위치엔 인덱스 값, 열 위치엔 칼럼명 지정 (슬라이싱 시 종료 위치까지 포함된다는 점이 iloc과 다름)\n", + "* 불린 인덱싱: []•loc[]에서 공통 지원(iloc는 미지원) - 조건식을 그대로 대입해 필터링, and(&)•or(|)•not(~)으로 복합조건 결합" + ], + "metadata": { + "id": "Xwem8JOBqBG4" + }, + "id": "Xwem8JOBqBG4" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6bc2b5ec-9d44-4299-9a13-98db1ed9146d", + "metadata": { + "id": "6bc2b5ec-9d44-4299-9a13-98db1ed9146d", + "outputId": "ad0b0d5b-58ab-4b8d-ce03-44d699701374" + }, + "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" + ] + }, + { + "ename": "KeyError", + "evalue": "0", + "output_type": "error", + "traceback": [ + "\u001b[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:3641\u001b[39m, in \u001b[36mIndex.get_loc\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 3640\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m3641\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_engine\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mget_loc\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mcasted_key\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 3642\u001b[39m \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", + "\u001b[36mFile \u001b[39m\u001b[32mpandas/_libs/index.pyx:168\u001b[39m, in \u001b[36mpandas._libs.index.IndexEngine.get_loc\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m--> \u001b[39m\u001b[32m168\u001b[39m \u001b[33m'Could not get source, probably due dynamically evaluated source code.'\u001b[39m\n", + "\u001b[36mFile \u001b[39m\u001b[32mpandas/_libs/index.pyx:176\u001b[39m, in \u001b[36mpandas._libs.index.IndexEngine.get_loc\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m--> \u001b[39m\u001b[32m176\u001b[39m \u001b[33m'Could not get source, probably due dynamically evaluated source code.'\u001b[39m\n", + "\u001b[36mFile \u001b[39m\u001b[32mpandas/_libs/index.pyx:583\u001b[39m, in \u001b[36mpandas._libs.index.StringObjectEngine._check_type\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m--> \u001b[39m\u001b[32m583\u001b[39m \u001b[33m'Could not get source, probably due dynamically evaluated source code.'\u001b[39m\n", + "\u001b[31mKeyError\u001b[39m: 0", + "\nThe above exception was the direct cause of the following exception:\n", + "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[105]\u001b[39m\u001b[32m, line 3\u001b[39m\n\u001b[32m 1\u001b[39m print(\u001b[33m'단일 칼럼 데이터 추출:\\n'\u001b[39m, titanic_df[\u001b[33m'Pclass'\u001b[39m].head(\u001b[32m3\u001b[39m))\n\u001b[32m 2\u001b[39m print(\u001b[33m'\\n여러 칼럼의 데이터 추출:\\n'\u001b[39m, titanic_df[[\u001b[33m'Survived'\u001b[39m, \u001b[33m'Pclass'\u001b[39m]].head(\u001b[32m3\u001b[39m))\n\u001b[32m----> \u001b[39m\u001b[32m3\u001b[39m print(\u001b[33m'[] 안에 숫자 index는 KeyError 오류 발생:\\n'\u001b[39m, titanic_df[\u001b[32m0\u001b[39m])\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\frame.py:4378\u001b[39m, in \u001b[36mDataFrame.__getitem__\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 4376\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m.columns.nlevels > \u001b[32m1\u001b[39m:\n\u001b[32m 4377\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._getitem_multilevel(key)\n\u001b[32m-> \u001b[39m\u001b[32m4378\u001b[39m indexer = \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mcolumns\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mget_loc\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mkey\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 4379\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m is_integer(indexer):\n\u001b[32m 4380\u001b[39m indexer = [indexer]\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:3648\u001b[39m, in \u001b[36mIndex.get_loc\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 3643\u001b[39m \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[32m 3644\u001b[39m \u001b[38;5;28misinstance\u001b[39m(casted_key, abc.Iterable)\n\u001b[32m 3645\u001b[39m \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[32m 3646\u001b[39m ):\n\u001b[32m 3647\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m InvalidIndexError(key) \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01merr\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m3648\u001b[39m \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;250m \u001b[39m\u001b[34;01merr\u001b[39;00m\n\u001b[32m 3649\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m:\n\u001b[32m 3650\u001b[39m \u001b[38;5;66;03m# If we have a listlike key, _check_indexing_error will raise\u001b[39;00m\n\u001b[32m 3651\u001b[39m \u001b[38;5;66;03m# InvalidIndexError. Otherwise we fall through and re-raise\u001b[39;00m\n\u001b[32m 3652\u001b[39m \u001b[38;5;66;03m# the TypeError.\u001b[39;00m\n\u001b[32m 3653\u001b[39m \u001b[38;5;28mself\u001b[39m._check_indexing_error(key)\n", + "\u001b[31mKeyError\u001b[39m: 0" + ] + } + ], + "source": [ + "print('단일 칼럼 데이터 추출:\\n', titanic_df['Pclass'].head(3))\n", + "print('\\n여러 칼럼의 데이터 추출:\\n', titanic_df[['Survived', 'Pclass']].head(3))\n", + "print('[] 안에 숫자 index는 KeyError 오류 발생:\\n', titanic_df[0])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7b02aaad-bf2c-47d0-bdd8-e45fc80cc800", + "metadata": { + "id": "7b02aaad-bf2c-47d0-bdd8-e45fc80cc800", + "outputId": "dbad0450-9284-49b5-e9ff-567405a402ab" + }, + "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
0103Braund, Mr....male22.010A/5 211717.2500NaNS
1211Cumings, Mr...female38.010PC 1759971.2833C85C
\n", + "
" + ], + "text/plain": [ + " 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" + ] + }, + "execution_count": 106, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df[0:2]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "217b7e5c-df69-48e3-bb6c-12cff4118610", + "metadata": { + "id": "217b7e5c-df69-48e3-bb6c-12cff4118610", + "outputId": "cdc0d17c-a5c0-4f9c-b8d1-e92e37c9995f" + }, + "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....male22.010A/5 211717.250NaNS
2313Heikkinen, ...female26.000STON/O2. 31...7.925NaNS
4503Allen, Mr. ...male35.0003734508.050NaNS
\n", + "
" + ], + "text/plain": [ + " 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.250 NaN S\n", + "2 3 1 3 Heikkinen, ... female 26.0 0 0 STON/O2. 31... 7.925 NaN S\n", + "4 5 0 3 Allen, Mr. ... male 35.0 0 0 373450 8.050 NaN S" + ] + }, + "execution_count": 107, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df[titanic_df['Pclass'] ==3].head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9d2d34a5-9316-415e-a16d-3f51d95f15ae", + "metadata": { + "id": "9d2d34a5-9316-415e-a16d-3f51d95f15ae", + "outputId": "1aa719e3-7552-44fc-e8a6-330a8f4c675b" + }, + "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", + "
NameYearsGender
oneChulmin2011Male
twoEunkyung2016Female
threeJinwoong2015Male
fourSoobeom2015Male
\n", + "
" + ], + "text/plain": [ + " Name Years Gender\n", + "one Chulmin 2011 Male\n", + "two Eunkyung 2016 Female\n", + "three Jinwoong 2015 Male\n", + "four Soobeom 2015 Male" + ] + }, + "execution_count": 109, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data = {'Name': ['Chulmin', 'Eunkyung', 'Jinwoong', 'Soobeom'],\n", + " 'Years': [2011, 2016, 2015, 2015],\n", + " 'Gender': ['Male', 'Female', 'Male', 'Male']\n", + " }\n", + "data_df = pd.DataFrame(data, index=['one', 'two', 'three', 'four'])\n", + "data_df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2068894d-7192-4af5-ba70-85fe3599da4c", + "metadata": { + "id": "2068894d-7192-4af5-ba70-85fe3599da4c", + "outputId": "3a166797-8d58-4229-b104-35bbd265021c" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Chulmin'" + ] + }, + "execution_count": 110, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data_df.iloc[0,0]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "78a901ab-d54c-4e64-90a9-c5e565d72933", + "metadata": { + "id": "78a901ab-d54c-4e64-90a9-c5e565d72933", + "outputId": "c27efde9-9528-454a-f791-1283b4ec0a87" + }, + "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[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mValueError\u001b[39m Traceback (most recent call last)", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:993\u001b[39m, in \u001b[36m_LocationIndexer._validate_tuple_indexer\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 992\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m993\u001b[39m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_validate_key\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mk\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mi\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 994\u001b[39m \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[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1635\u001b[39m, in \u001b[36m_iLocIndexer._validate_key\u001b[39m\u001b[34m(self, key, axis)\u001b[39m\n\u001b[32m 1634\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1635\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mCan only index by location with a [\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m._valid_types\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m]\u001b[39m\u001b[33m\"\u001b[39m)\n", + "\u001b[31mValueError\u001b[39m: 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[31mValueError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[111]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[32m 1\u001b[39m \u001b[38;5;66;03m# 아래 코드는 오류를 발생시킵니다.\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m2\u001b[39m data_df.iloc[\u001b[32m0\u001b[39m, \u001b[33m'Name'\u001b[39m]\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1200\u001b[39m, in \u001b[36m_LocationIndexer.__getitem__\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 1198\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._is_scalar_access(key):\n\u001b[32m 1199\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m.obj._get_value(*key, takeable=\u001b[38;5;28mself\u001b[39m._takeable)\n\u001b[32m-> \u001b[39m\u001b[32m1200\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_getitem_tuple\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mkey\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1201\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m 1202\u001b[39m \u001b[38;5;66;03m# we by definition only have the 0th axis\u001b[39;00m\n\u001b[32m 1203\u001b[39m axis = \u001b[38;5;28mself\u001b[39m.axis \u001b[38;5;129;01mor\u001b[39;00m \u001b[32m0\u001b[39m\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1711\u001b[39m, in \u001b[36m_iLocIndexer._getitem_tuple\u001b[39m\u001b[34m(self, tup)\u001b[39m\n\u001b[32m 1710\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m_getitem_tuple\u001b[39m(\u001b[38;5;28mself\u001b[39m, tup: \u001b[38;5;28mtuple\u001b[39m):\n\u001b[32m-> \u001b[39m\u001b[32m1711\u001b[39m tup = \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_validate_tuple_indexer\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mtup\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1712\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m suppress(IndexingError):\n\u001b[32m 1713\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._getitem_lowerdim(tup)\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:995\u001b[39m, in \u001b[36m_LocationIndexer._validate_tuple_indexer\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 993\u001b[39m \u001b[38;5;28mself\u001b[39m._validate_key(k, i)\n\u001b[32m 994\u001b[39m \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[32m--> \u001b[39m\u001b[32m995\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[32m 996\u001b[39m \u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mLocation based indexing can only have [\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m._valid_types\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m] types\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 997\u001b[39m ) \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01merr\u001b[39;00m\n\u001b[32m 998\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m key\n", + "\u001b[31mValueError\u001b[39m: 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, 'Name']" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "844f857d-e3dd-46a5-93ae-06f619d94639", + "metadata": { + "id": "844f857d-e3dd-46a5-93ae-06f619d94639", + "outputId": "f1744301-e576-486c-ce37-ff59ff4774da" + }, + "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[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mValueError\u001b[39m Traceback (most recent call last)", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:993\u001b[39m, in \u001b[36m_LocationIndexer._validate_tuple_indexer\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 992\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m993\u001b[39m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_validate_key\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mk\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mi\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 994\u001b[39m \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[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1635\u001b[39m, in \u001b[36m_iLocIndexer._validate_key\u001b[39m\u001b[34m(self, key, axis)\u001b[39m\n\u001b[32m 1634\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1635\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mCan only index by location with a [\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m._valid_types\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m]\u001b[39m\u001b[33m\"\u001b[39m)\n", + "\u001b[31mValueError\u001b[39m: 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[31mValueError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[112]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[32m 1\u001b[39m \u001b[38;5;66;03m# 아래 코드는 오류를 발생시킵니다.\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m2\u001b[39m data_df.iloc[\u001b[33m'one'\u001b[39m,\u001b[32m0\u001b[39m]\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1200\u001b[39m, in \u001b[36m_LocationIndexer.__getitem__\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 1198\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._is_scalar_access(key):\n\u001b[32m 1199\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m.obj._get_value(*key, takeable=\u001b[38;5;28mself\u001b[39m._takeable)\n\u001b[32m-> \u001b[39m\u001b[32m1200\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_getitem_tuple\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mkey\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1201\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m 1202\u001b[39m \u001b[38;5;66;03m# we by definition only have the 0th axis\u001b[39;00m\n\u001b[32m 1203\u001b[39m axis = \u001b[38;5;28mself\u001b[39m.axis \u001b[38;5;129;01mor\u001b[39;00m \u001b[32m0\u001b[39m\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1711\u001b[39m, in \u001b[36m_iLocIndexer._getitem_tuple\u001b[39m\u001b[34m(self, tup)\u001b[39m\n\u001b[32m 1710\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m_getitem_tuple\u001b[39m(\u001b[38;5;28mself\u001b[39m, tup: \u001b[38;5;28mtuple\u001b[39m):\n\u001b[32m-> \u001b[39m\u001b[32m1711\u001b[39m tup = \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_validate_tuple_indexer\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mtup\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1712\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m suppress(IndexingError):\n\u001b[32m 1713\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._getitem_lowerdim(tup)\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:995\u001b[39m, in \u001b[36m_LocationIndexer._validate_tuple_indexer\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 993\u001b[39m \u001b[38;5;28mself\u001b[39m._validate_key(k, i)\n\u001b[32m 994\u001b[39m \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[32m--> \u001b[39m\u001b[32m995\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[32m 996\u001b[39m \u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mLocation based indexing can only have [\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m._valid_types\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m] types\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 997\u001b[39m ) \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01merr\u001b[39;00m\n\u001b[32m 998\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m key\n", + "\u001b[31mValueError\u001b[39m: 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['one',0]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cc60592b-b335-40eb-ab11-952417cd6ced", + "metadata": { + "id": "cc60592b-b335-40eb-ab11-952417cd6ced", + "outputId": "7987b11b-bf44-48fd-aa07-9dbfbef09d9a" + }, + "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: str\n", + "\n", + " 맨 마지막 칼럼을 제외한 모든 데이터 [:, :-1]\n", + " Name Years\n", + "one Chulmin 2011\n", + "two Eunkyung 2016\n", + "three Jinwoong 2015\n", + "four Soobeom 2015\n" + ] + } + ], + "source": [ + "print('\\n 맨 마지막 칼럼 데이터 [:, -1] \\n', data_df.iloc[:,-1])\n", + "print('\\n 맨 마지막 칼럼을 제외한 모든 데이터 [:, :-1]\\n', data_df.iloc[:,:-1])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "07cee4de-9695-48a0-a85f-a1349dbd86c3", + "metadata": { + "id": "07cee4de-9695-48a0-a85f-a1349dbd86c3", + "outputId": "249e627c-92b0-44ac-874f-c4cca286d9c2" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Chulmin'" + ] + }, + "execution_count": 114, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data_df.loc['one', 'Name']" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b506a536-e92a-4e1c-b28e-ed9028347ba6", + "metadata": { + "id": "b506a536-e92a-4e1c-b28e-ed9028347ba6", + "outputId": "d118a18e-7f0a-4bbc-bc0d-533748b14780" + }, + "outputs": [ + { + "ename": "KeyError", + "evalue": "0", + "output_type": "error", + "traceback": [ + "\u001b[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:3641\u001b[39m, in \u001b[36mIndex.get_loc\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 3640\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m3641\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_engine\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mget_loc\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mcasted_key\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 3642\u001b[39m \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", + "\u001b[36mFile \u001b[39m\u001b[32mpandas/_libs/index.pyx:168\u001b[39m, in \u001b[36mpandas._libs.index.IndexEngine.get_loc\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m--> \u001b[39m\u001b[32m168\u001b[39m \u001b[33m'Could not get source, probably due dynamically evaluated source code.'\u001b[39m\n", + "\u001b[36mFile \u001b[39m\u001b[32mpandas/_libs/index.pyx:176\u001b[39m, in \u001b[36mpandas._libs.index.IndexEngine.get_loc\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m--> \u001b[39m\u001b[32m176\u001b[39m \u001b[33m'Could not get source, probably due dynamically evaluated source code.'\u001b[39m\n", + "\u001b[36mFile \u001b[39m\u001b[32mpandas/_libs/index.pyx:583\u001b[39m, in \u001b[36mpandas._libs.index.StringObjectEngine._check_type\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m--> \u001b[39m\u001b[32m583\u001b[39m \u001b[33m'Could not get source, probably due dynamically evaluated source code.'\u001b[39m\n", + "\u001b[31mKeyError\u001b[39m: 0", + "\nThe above exception was the direct cause of the following exception:\n", + "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[115]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[32m 1\u001b[39m \u001b[38;5;66;03m# 다음 코드는 오류를 발생시킵니다.\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m2\u001b[39m data_df.loc[\u001b[32m0\u001b[39m, \u001b[33m'Name'\u001b[39m]\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexing.py:1199\u001b[39m, in \u001b[36m_LocationIndexer.__getitem__\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 1197\u001b[39m key = \u001b[38;5;28mtuple\u001b[39m(com.apply_if_callable(x, \u001b[38;5;28mself\u001b[39m.obj) \u001b[38;5;28;01mfor\u001b[39;00m x \u001b[38;5;129;01min\u001b[39;00m key)\n\u001b[32m 1198\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._is_scalar_access(key):\n\u001b[32m-> \u001b[39m\u001b[32m1199\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mobj\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_get_value\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkey\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mtakeable\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_takeable\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1200\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._getitem_tuple(key)\n\u001b[32m 1201\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m 1202\u001b[39m \u001b[38;5;66;03m# we by definition only have the 0th axis\u001b[39;00m\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\frame.py:4495\u001b[39m, in \u001b[36mDataFrame._get_value\u001b[39m\u001b[34m(self, index, col, takeable)\u001b[39m\n\u001b[32m 4489\u001b[39m series = \u001b[38;5;28mself\u001b[39m._get_item(col)\n\u001b[32m 4491\u001b[39m \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.index, MultiIndex):\n\u001b[32m 4492\u001b[39m \u001b[38;5;66;03m# CategoricalIndex: Trying to use the engine fastpath may give incorrect\u001b[39;00m\n\u001b[32m 4493\u001b[39m \u001b[38;5;66;03m# results if our categories are integers that dont match our codes\u001b[39;00m\n\u001b[32m 4494\u001b[39m \u001b[38;5;66;03m# IntervalIndex: IntervalTree has no get_loc\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m4495\u001b[39m row = \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mindex\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mget_loc\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mindex\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 4496\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m series._values[row]\n\u001b[32m 4498\u001b[39m \u001b[38;5;66;03m# For MultiIndex going through engine effectively restricts us to\u001b[39;00m\n\u001b[32m 4499\u001b[39m \u001b[38;5;66;03m# same-length tuples; see test_get_set_value_no_partial_indexing\u001b[39;00m\n", + "\u001b[36mFile \u001b[39m\u001b[32mC:\\ProgramData\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:3648\u001b[39m, in \u001b[36mIndex.get_loc\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 3643\u001b[39m \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[32m 3644\u001b[39m \u001b[38;5;28misinstance\u001b[39m(casted_key, abc.Iterable)\n\u001b[32m 3645\u001b[39m \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[32m 3646\u001b[39m ):\n\u001b[32m 3647\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m InvalidIndexError(key) \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01merr\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m3648\u001b[39m \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;250m \u001b[39m\u001b[34;01merr\u001b[39;00m\n\u001b[32m 3649\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m:\n\u001b[32m 3650\u001b[39m \u001b[38;5;66;03m# If we have a listlike key, _check_indexing_error will raise\u001b[39;00m\n\u001b[32m 3651\u001b[39m \u001b[38;5;66;03m# InvalidIndexError. Otherwise we fall through and re-raise\u001b[39;00m\n\u001b[32m 3652\u001b[39m \u001b[38;5;66;03m# the TypeError.\u001b[39;00m\n\u001b[32m 3653\u001b[39m \u001b[38;5;28mself\u001b[39m._check_indexing_error(key)\n", + "\u001b[31mKeyError\u001b[39m: 0" + ] + } + ], + "source": [ + "# 다음 코드는 오류를 발생시킵니다.\n", + "data_df.loc[0, 'Name']" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ca4dd857-a6fb-4e30-a9f0-4e92ac1294a5", + "metadata": { + "id": "ca4dd857-a6fb-4e30-a9f0-4e92ac1294a5", + "outputId": "3e5df828-62b4-4558-eac4-cd145149f4f9" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "위치기반 iloc slicing\n", + " one Chulmin\n", + "Name: Name, dtype: str \n", + "\n", + "명칭기반 loc slicing\n", + " one Chulmin\n", + "two Eunkyung\n", + "Name: Name, dtype: str\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": null, + "id": "1e16ebb4-7bcc-410f-8943-86f88e306b39", + "metadata": { + "id": "1e16ebb4-7bcc-410f-8943-86f88e306b39", + "outputId": "21079291-91ee-46b3-9eb9-c27de5854bbe" + }, + "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...male66.000C.A. 2457910.5000NaNS
545501Ostby, Mr. ...male65.00111350961.9792B30C
969701Goldschmidt...male71.000PC 1775434.6542A5C
11611703Connors, Mr...male70.5003703697.7500NaNQ
17017101Van der hoe...male61.00011124033.5000B19S
25225301Stead, Mr. ...male62.00011351426.5500C87S
27527611Andrews, Mi...female63.0101350277.9583D7S
28028103Duane, Mr. ...male65.0003364397.7500NaNQ
32632703Nysveen, Mr...male61.0003453646.2375NaNS
43843901Fortune, Mr...male64.01419950263.0000C23 C25 C27S
45645701Millet, Mr....male65.0001350926.5500E38S
48348413Turkula, Mr...female63.00041349.5875NaNS
49349401Artagaveyti...male71.000PC 1760949.5042NaNC
54554601Nicholson, ...male64.00069326.0000NaNS
55555601Wright, Mr....male62.00011380726.5500NaNS
57057112Harris, Mr....male62.000S.W./PP 75210.5000NaNS
62562601Sutton, Mr....male61.0003696332.3208D50S
63063111Barkworth, ...male80.0002704230.0000A23S
67267302Mitchell, M...male70.000C.A. 2458010.5000NaNS
74574601Crosby, Cap...male70.011WE/P 573571.0000B22S
82983011Stone, Mrs....female62.00011357280.0000B28NaN
85185203Svensson, M...male74.0003470607.7750NaNS
\n", + "
" + ], + "text/plain": [ + " PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n", + "33 34 0 2 Wheadon, Mr... male 66.0 0 0 C.A. 24579 10.5000 NaN S\n", + "54 55 0 1 Ostby, Mr. ... male 65.0 0 1 113509 61.9792 B30 C\n", + "96 97 0 1 Goldschmidt... male 71.0 0 0 PC 17754 34.6542 A5 C\n", + "116 117 0 3 Connors, Mr... male 70.5 0 0 370369 7.7500 NaN Q\n", + "170 171 0 1 Van der hoe... male 61.0 0 0 111240 33.5000 B19 S\n", + "252 253 0 1 Stead, Mr. ... male 62.0 0 0 113514 26.5500 C87 S\n", + "275 276 1 1 Andrews, Mi... female 63.0 1 0 13502 77.9583 D7 S\n", + "280 281 0 3 Duane, Mr. ... male 65.0 0 0 336439 7.7500 NaN Q\n", + "326 327 0 3 Nysveen, Mr... male 61.0 0 0 345364 6.2375 NaN S\n", + "438 439 0 1 Fortune, Mr... male 64.0 1 4 19950 263.0000 C23 C25 C27 S\n", + "456 457 0 1 Millet, Mr.... male 65.0 0 0 13509 26.5500 E38 S\n", + "483 484 1 3 Turkula, Mr... female 63.0 0 0 4134 9.5875 NaN S\n", + "493 494 0 1 Artagaveyti... male 71.0 0 0 PC 17609 49.5042 NaN C\n", + "545 546 0 1 Nicholson, ... male 64.0 0 0 693 26.0000 NaN S\n", + "555 556 0 1 Wright, Mr.... male 62.0 0 0 113807 26.5500 NaN S\n", + "570 571 1 2 Harris, Mr.... male 62.0 0 0 S.W./PP 752 10.5000 NaN S\n", + "625 626 0 1 Sutton, Mr.... male 61.0 0 0 36963 32.3208 D50 S\n", + "630 631 1 1 Barkworth, ... male 80.0 0 0 27042 30.0000 A23 S\n", + "672 673 0 2 Mitchell, M... male 70.0 0 0 C.A. 24580 10.5000 NaN S\n", + "745 746 0 1 Crosby, Cap... male 70.0 1 1 WE/P 5735 71.0000 B22 S\n", + "829 830 1 1 Stone, Mrs.... female 62.0 0 0 113572 80.0000 B28 NaN\n", + "851 852 0 3 Svensson, M... male 74.0 0 0 347060 7.7750 NaN S" + ] + }, + "execution_count": 117, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df = pd.read_csv('titanic_train.csv')\n", + "titanic_boolean = titanic_df[titanic_df['Age']>60]\n", + "print(type(titanic_boolean))\n", + "titanic_boolean" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7435b973-8c03-4d6a-bd78-845be5989c39", + "metadata": { + "id": "7435b973-8c03-4d6a-bd78-845be5989c39", + "outputId": "ad9eb6d1-22b2-4ef0-b11a-45951156d229" + }, + "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", + "
NameAge
33Wheadon, Mr...66.0
54Ostby, Mr. ...65.0
96Goldschmidt...71.0
\n", + "
" + ], + "text/plain": [ + " Name Age\n", + "33 Wheadon, Mr... 66.0\n", + "54 Ostby, Mr. ... 65.0\n", + "96 Goldschmidt... 71.0" + ] + }, + "execution_count": 118, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df.loc[titanic_df['Age']>60, ['Name', 'Age']].head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d5d49a80-58ab-466a-8d9f-93c8ba5a1d9f", + "metadata": { + "id": "d5d49a80-58ab-466a-8d9f-93c8ba5a1d9f", + "outputId": "17e6988c-985b-450e-e50a-2504e24bde2a" + }, + "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, Mi...female63.0101350277.9583D7S
82983011Stone, Mrs....female62.00011357280.0000B28NaN
\n", + "
" + ], + "text/plain": [ + " PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n", + "275 276 1 1 Andrews, Mi... female 63.0 1 0 13502 77.9583 D7 S\n", + "829 830 1 1 Stone, Mrs.... female 62.0 0 0 113572 80.0000 B28 NaN" + ] + }, + "execution_count": 119, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df[(titanic_df['Age']>60)&(titanic_df['Pclass']==1)&(titanic_df['Sex']=='female')]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f8946bb-8b65-40f3-a50e-c633f044ac06", + "metadata": { + "id": "4f8946bb-8b65-40f3-a50e-c633f044ac06", + "outputId": "e1e1954b-320a-4dbf-cf75-95e20164f353" + }, + "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, Mi...female63.0101350277.9583D7S
82983011Stone, Mrs....female62.00011357280.0000B28NaN
\n", + "
" + ], + "text/plain": [ + " PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n", + "275 276 1 1 Andrews, Mi... female 63.0 1 0 13502 77.9583 D7 S\n", + "829 830 1 1 Stone, Mrs.... female 62.0 0 0 113572 80.0000 B28 NaN" + ] + }, + "execution_count": 120, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "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": "markdown", + "source": [ + "# 정렬 • Aggregation • Groupby\n", + "\n", + "* .sort_value(by=[]): by(정렬 칼럼)•ascending(오름/내림차순)•inplace 파라미터로 정렬\n", + "* Aggregation 함수(.min/max/sum/count 등): DataFrame에 바로 호출하면 모든 칼럼에 적용\n", + "* .groupby(''): 지정 칼럼 기준으로 그룹화한 DataFrameGroupby 객체 반환\n", + "* .agg(): \\\n", + "한 칼럼에 대한 aggregation 함수 적용 : ['칼럼명'].agg([함수])\\\n", + "그룹별로 칼럼마다 다른 aggregation 함수를 적용: .agg({'칼럼':'함수'})\n" + ], + "metadata": { + "id": "OigyTitarYen" + }, + "id": "OigyTitarYen" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7094d13e-e528-46ba-b658-f496babf27b0", + "metadata": { + "id": "7094d13e-e528-46ba-b658-f496babf27b0", + "outputId": "8ec8eaa6-8d40-4a09-910e-edc71dc9113a" + }, + "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....male42.000C.A. 55477.55NaNS
74674703Abbott, Mr....male16.011C.A. 267320.25NaNS
27928013Abbott, Mrs...female35.011C.A. 267320.25NaNS
\n", + "
" + ], + "text/plain": [ + " PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n", + "845 846 0 3 Abbing, Mr.... male 42.0 0 0 C.A. 5547 7.55 NaN S\n", + "746 747 0 3 Abbott, Mr.... male 16.0 1 1 C.A. 2673 20.25 NaN S\n", + "279 280 1 3 Abbott, Mrs... female 35.0 1 1 C.A. 2673 20.25 NaN S" + ] + }, + "execution_count": 121, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_sorted = titanic_df.sort_values(by=['Name'])\n", + "titanic_sorted.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "83680524-3c9f-41bb-be45-385fa8d09eba", + "metadata": { + "id": "83680524-3c9f-41bb-be45-385fa8d09eba", + "outputId": "62180d58-7dad-4bf5-fe0c-e57b19de663f" + }, + "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 Melkebe...maleNaN003457779.5NaNS
15315403van Billiar...male40.502A/5. 85114.5NaNS
28228303de Pelsmaek...male16.0003457789.5NaNS
\n", + "
" + ], + "text/plain": [ + " PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n", + "868 869 0 3 van Melkebe... male NaN 0 0 345777 9.5 NaN S\n", + "153 154 0 3 van Billiar... male 40.5 0 2 A/5. 851 14.5 NaN S\n", + "282 283 0 3 de Pelsmaek... male 16.0 0 0 345778 9.5 NaN S" + ] + }, + "execution_count": 122, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_sorted = titanic_df.sort_values(by=['Pclass', 'Name'], ascending=False)\n", + "titanic_sorted.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "56779f7e-6eb8-4b41-81f4-7316b80191cb", + "metadata": { + "id": "56779f7e-6eb8-4b41-81f4-7316b80191cb", + "outputId": "91cfd0c5-0295-44da-ed11-7d9f56103dcc" + }, + "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": 123, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df.count()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "15857780-fe94-4927-ae84-cb336590d68b", + "metadata": { + "id": "15857780-fe94-4927-ae84-cb336590d68b", + "outputId": "41397b98-1f3c-45e3-c6ab-d73f6fdc63c8" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Age 29.699118\n", + "Fare 32.204208\n", + "dtype: float64" + ] + }, + "execution_count": 124, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df[['Age', 'Fare']].mean()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2bfe208c-da89-49d3-93ef-aa02514d7be9", + "metadata": { + "id": "2bfe208c-da89-49d3-93ef-aa02514d7be9", + "outputId": "d51c31b7-eff3-450c-882d-5566b8eb703b" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "titanic_groupby = titanic_df.groupby(by='Pclass')\n", + "print(type(titanic_groupby))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8b3cebf6-4a6a-4922-b45e-29e3f00022c8", + "metadata": { + "id": "8b3cebf6-4a6a-4922-b45e-29e3f00022c8", + "outputId": "698a24fd-224c-4db3-8d66-64ded756c286" + }, + "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 Cabin Embarked\n", + "Pclass \n", + "1 216 216 216 216 186 216 216 216 216 176 214\n", + "2 184 184 184 184 173 184 184 184 184 16 184\n", + "3 491 491 491 491 355 491 491 491 491 12 491" + ] + }, + "execution_count": 126, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_groupby = titanic_df.groupby('Pclass').count()\n", + "titanic_groupby" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df619f4d-12ec-4485-87b5-05cb531f940a", + "metadata": { + "id": "df619f4d-12ec-4485-87b5-05cb531f940a", + "outputId": "ab0d82ab-00b5-4728-dbf8-c093ce9ada3d" + }, + "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": 127, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_groupby = titanic_df.groupby('Pclass')[['PassengerId', 'Survived']].count()\n", + "titanic_groupby" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a1cae946-bf09-41ed-9fa9-20e6518cbd1d", + "metadata": { + "id": "a1cae946-bf09-41ed-9fa9-20e6518cbd1d", + "outputId": "8398b10f-3a5e-4be5-dc6d-08d2a0fa9185" + }, + "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", + "
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": 128, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df.groupby('Pclass')['Age'].agg([max,min])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3133eb16-ca50-4bd7-9f55-ddda2e6a5a24", + "metadata": { + "id": "3133eb16-ca50-4bd7-9f55-ddda2e6a5a24", + "outputId": "ecdb86b4-dcab-4fad-cc2f-db7a8ca01d4c" + }, + "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": 130, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "agg_format = {'Age':'max', 'SibSp':'sum', 'Fare':'mean'}\n", + "titanic_df.groupby('Pclass').agg(agg_format)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# 결손 데이터 처리\n", + "\n", + "* Null 값은 넘파이의 NaN으로 표시됨 - 대부분의 머신러닝 알고리즘이 NaN을 처리하지 못하므로 반드시 다른 값으로 대체 필요\n", + "* .isna(): 칼럼별 NaN여부를 True/False로 반환 (.sum()과 결합하면 칼럼별 결손 개수 확인 가능)\n", + "* .fillna(): NaN을 지정 값으로 대체 (반환값 재할당 또는 inplace = True 필요)" + ], + "metadata": { + "id": "SeYmSW6Lw4KG" + }, + "id": "SeYmSW6Lw4KG" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ce082fc4-6fd6-4eda-8313-e42467e65d12", + "metadata": { + "id": "ce082fc4-6fd6-4eda-8313-e42467e65d12", + "outputId": "d2ef5145-f54a-44bb-ce9d-d77867d702ba" + }, + "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 Fare Cabin Embarked\n", + "0 False False False False False False False False False False True False\n", + "1 False False False False False False False False False False False False\n", + "2 False False False False False False False False False False True False" + ] + }, + "execution_count": 131, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df.isna().head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "28060068-5e3f-44c8-8c0c-4108c7035a79", + "metadata": { + "id": "28060068-5e3f-44c8-8c0c-4108c7035a79", + "outputId": "7bbb4694-3c5c-4c38-95ea-51fcbe9af623" + }, + "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": 132, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df.isna().sum()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "61881dd9-b00e-4c1c-9b65-c04af1ab26a7", + "metadata": { + "id": "61881dd9-b00e-4c1c-9b65-c04af1ab26a7", + "outputId": "5e903c9d-8177-471d-c66c-db430c2f0dce" + }, + "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....male22.010A/5 211717.2500C000S
1211Cumings, Mr...female38.010PC 1759971.2833C85C
2313Heikkinen, ...female26.000STON/O2. 31...7.9250C000S
\n", + "
" + ], + "text/plain": [ + " 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 C000 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 C000 S" + ] + }, + "execution_count": 133, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000')\n", + "titanic_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "20d71089-ee82-461a-b85a-7218042fee96", + "metadata": { + "id": "20d71089-ee82-461a-b85a-7218042fee96", + "outputId": "1bb2148c-e856-44c4-ab78-6f3a704cdc0e" + }, + "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": 135, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())\n", + "titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')\n", + "titanic_df.isna().sum()" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# apply lambda 식으로 데이터 가공 (로우 단위 데이터 가공)\n", + "\n", + "* 칼럼 전체 일괄 가공은 벡터 연산이 빠르지만, 로우별 복잡한 조건 가공에는 apply() + lambda 사용\n", + "* lambda: 함수명 없이 '입력값: 계산식' 한 줄로 정의하는 함수 표현식 (함수형 프로그래밍 지원)\n", + "* if/else는 지원하나 else if(elif)는 미지원 -> 괄호로 중첩하거나, 복잡한 분기는 별도 함수를 만들어 apply (lambda x: 함수(x)) 형태로 호출" + ], + "metadata": { + "id": "NkZZucsnxuIi" + }, + "id": "NkZZucsnxuIi" + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f8dfb02f-5653-4cd1-a564-8f0dc51ba59a", + "metadata": { + "id": "f8dfb02f-5653-4cd1-a564-8f0dc51ba59a", + "outputId": "2edf189f-22bc-487b-ff81-6300a42c726d" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3의 제곱은: 9\n" + ] + } + ], + "source": [ + "def get_square(a):\n", + " return a**2\n", + "\n", + "print('3의 제곱은:', get_square(3))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d8dad81d-9849-485f-88b1-d9837f524b23", + "metadata": { + "id": "d8dad81d-9849-485f-88b1-d9837f524b23", + "outputId": "bbc36028-d552-4225-8017-6186ab0434d8" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3의 제곱은: 9\n" + ] + } + ], + "source": [ + "lambda_square = lambda x: x**2\n", + "print('3의 제곱은:', lambda_square(3))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8b604d1e-4744-49a0-ba07-b4013800b146", + "metadata": { + "id": "8b604d1e-4744-49a0-ba07-b4013800b146", + "outputId": "b9676dcc-c14f-4c49-ac3c-c45a25d0b9f4" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 4, 9]" + ] + }, + "execution_count": 143, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = [1,2,3]\n", + "squares = map(lambda x : x**2, a)\n", + "list(squares)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "69924b01-9683-43bc-8938-2ac4f1cfc08c", + "metadata": { + "id": "69924b01-9683-43bc-8938-2ac4f1cfc08c", + "outputId": "4cbbef98-f9e0-4693-e9b6-314a3fa99950" + }, + "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....23
1Cumings, Mr...51
2Heikkinen, ...22
\n", + "
" + ], + "text/plain": [ + " Name Name_len\n", + "0 Braund, Mr.... 23\n", + "1 Cumings, Mr... 51\n", + "2 Heikkinen, ... 22" + ] + }, + "execution_count": 144, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "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": null, + "id": "24bd24bd-87aa-476d-8189-c79565bc952b", + "metadata": { + "id": "24bd24bd-87aa-476d-8189-c79565bc952b", + "outputId": "403e2adb-3ed6-4ca1-eb75-9acc08da0e2d" + }, + "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", + "
AgeChild_Adult
022.000000Adult
138.000000Adult
226.000000Adult
335.000000Adult
435.000000Adult
529.699118Adult
654.000000Adult
72.000000Child
\n", + "
" + ], + "text/plain": [ + " Age Child_Adult\n", + "0 22.000000 Adult\n", + "1 38.000000 Adult\n", + "2 26.000000 Adult\n", + "3 35.000000 Adult\n", + "4 35.000000 Adult\n", + "5 29.699118 Adult\n", + "6 54.000000 Adult\n", + "7 2.000000 Child" + ] + }, + "execution_count": 145, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "titanic_df['Child_Adult']= titanic_df['Age'].apply(lambda x: 'Child' if x <= 15 else 'Adult')\n", + "titanic_df[['Age', 'Child_Adult']].head(8)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "692a8cfa-f7f0-4b26-85cb-0ff7677276b6", + "metadata": { + "id": "692a8cfa-f7f0-4b26-85cb-0ff7677276b6", + "outputId": "cd732e04-f010-47b3-dd20-026280aebfe3" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Age_cat\n", + "Adult 786\n", + "Child 83\n", + "Elderly 22\n", + "Name: count, dtype: int64" + ] + }, + "execution_count": 146, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "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": null, + "id": "c3c1648a-2012-4766-94e8-fea9f4f22ea9", + "metadata": { + "id": "c3c1648a-2012-4766-94e8-fea9f4f22ea9", + "outputId": "9ed76d21-6669-40ad-b60e-1c0f402365bb" + }, + "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": 148, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 나이에 따라 세분화된 분류를 수행하는 함수 생성\n", + "\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()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d8dbd4e2-45e7-4b09-9a45-887efeee7260", + "metadata": { + "id": "d8dbd4e2-45e7-4b09-9a45-887efeee7260" + }, + "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.14.6" + }, + "colab": { + "provenance": [] + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git "a/Week1\354\230\210\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.pdf" "b/Week1\354\230\210\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.pdf" new file mode 100644 index 0000000..337c7f1 Binary files /dev/null and "b/Week1\354\230\210\354\212\265\352\263\274\354\240\234_\354\206\241\354\230\201\354\235\200.pdf" differ