diff --git "a/01_basics/01. Python \347\260\241\344\273\213.ipynb" "b/01_basics/01. Python \347\260\241\344\273\213.ipynb" new file mode 100644 index 0000000..cfb0502 --- /dev/null +++ "b/01_basics/01. Python \347\260\241\344\273\213.ipynb" @@ -0,0 +1,479 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 簡介" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Python 之父\n", + "### Guido Van Rossum (荷蘭, 1956~)\n", + "\n", + "[![Guido Van Rossum (荷蘭, 1956~)](../images/Guido_van_Rossum_OSCON_2006_cropped.png)](https://en.wikipedia.org/wiki/Guido_van_Rossum)\n", + "\n", + "* 1989 年 Xmas 時,為了打發時間,Guido 開始寫 Python。\n", + "* 1991 釋出 Python。\n", + "* 取名 Python 的原因是 Guido 喜歡看 \"Monty Python's Flying Circus\"。\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "293af2dd-d2e0-4f2e-a448-2cbf1641e7d5" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Why Python?\n", + "\n", + "* 自由軟體:完全免費、參與者眾\n", + "* 擴充性強:模組豐富、應用性強\n", + "* 易學好用:語法簡潔、易學易懂\n", + "* 跨平台:Windows / Linux / Mac / ...\n", + "* 同好者眾:支援性強、問題快解\n", + "\n", + "[More:Python 發展歷史與特點](http://www.ziqiangxuetang.com/python/python-intro.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 從下面的笑話,可以稍微看出 Python 的特點!\n", + "\n", + "![](../images/python-vs-java.jpg)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Python is a glue language!!!\n", + "\n", + "* 使用者通常不需要自己實作程式所有的功能,而是需要協調及整合模組跟套件的運作!!!\n", + "\n", + "|| C/C++ | Python |\n", + "|:-:|:-:|:-:|\n", + "|開發速度|慢|快|\n", + "|偵錯速度|慢|快|\n", + "|佈署速度|慢|快|\n", + "|執行速度|非常快|快|\n", + "\n", + "* 使用 Python 可以在最短的時間做出產品雛形。" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 新創公司喜歡 Python!\n", + "\n", + "[![](../images/AL_jobs.png)](https://www.codementor.io/learn-programming/beginner-programming-language-job-salary-community)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 學校喜歡教 Python (Top US Universities Teach Python)\n", + "\n", + "[![](../images/Top39-700.4.png)](http://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 初學者喜歡學 Python (PYPL, PopularitY of Programming Language Index)\n", + "\n", + "[![](../images/PYPL_2017_03.png)](http://pypl.github.io/PYPL.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "81f50645-13d2-43a5-a557-902be09c9968" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 電子電機工程師喜歡 Python (2016 IEEE Programming Languages Ranking)\n", + "[![](../images/2016 IEEE Top 10 Programming Languages.png)](http://spectrum.ieee.org/computing/software/the-2016-top-programming-languages)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "[![](../images/IoT_languages.png)](http://www.developer-tech.com/news/2016/apr/20/research-iot-developer-survey-reveals-popular-technologies/)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 資料科學家喜歡 Python (Top 10 Tools for Analytics/Data Science)\n", + "\n", + "[![](../images/top10-analytics-data-science-software-2016.jpg)](http://www.kdnuggets.com/2016/06/r-python-top-analytics-data-mining-data-science-software.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 社群喜歡 Python (TIOBE Programming Community Index)\n", + "\n", + "[![](../images/Tiobe_2017_02.png)](http://www.tiobe.com/tiobe-index/)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 後端喜歡 Python (Python/Django Market Share)\n", + "\n", + "[![](../images/silicon_valley.png)](https://www.quora.com/How-is-the-market-for-programmers-in-Python-Django)\n", + "\n", + "[![](../images/berlin.png)](https://www.quora.com/How-is-the-market-for-programmers-in-Python-Django)\n", + "\n", + "[![](../images/barcelona.png)](https://www.quora.com/How-is-the-market-for-programmers-in-Python-Django)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "[![](../images/backend.png)](https://en.wikipedia.org/wiki/Programming_languages_used_in_most_popular_websites)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Fintech 喜歡 Python\n", + "[![](../images/fintech-finance-1.png)](https://blog.hackerrank.com/emerging-languages-still-overshadowed-by-incumbents-java-python-in-coding-interviews/)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "25ac7855-2c20-47bb-b4ab-6a7fbba20e2d" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 2015 Github Statistics\n", + "[![](../images/Python vs R in Github.png)](http://githut.info/?utm_content=buffer781de&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer)\n", + "\n", + "[Python vs. R (Datacamp)](https://www.datacamp.com/community/tutorials/r-or-python-for-data-analysis)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "6ddd881a-45b7-47cb-8a82-8c8280270623" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## stackoverflow\n", + "[![](../images/2016 stackoverflow Languages Ranking.png)](http://stackoverflow.com/research/developer-survey-2016#technology-most-popular-technologies)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 天瓏書局中文暢銷書排行榜\n", + "\n", + "|月份|前五名 Python 書籍有幾本?|前十名 Python 書籍有幾本?|\n", + "|:----:|:----------------------:|:----------------------:|\n", + "|[2016/09](https://www.tenlong.com.tw/zh_tw/bestselling?date=2016-09-30)|2|3|\n", + "|[2016/10](https://www.tenlong.com.tw/zh_tw/bestselling?date=2016-10-30)|3|5|\n", + "|[2016/11](https://www.tenlong.com.tw/zh_tw/bestselling?date=2016-11-30)|4|5|\n", + "|[2016/12](https://www.tenlong.com.tw/zh_tw/bestselling?date=2016-12-28)|4|6|\n", + "|[2017/01](https://www.tenlong.com.tw/zh_tw/bestselling?date=2017-01-28)|3|6|\n", + "|[2017/02](https://www.tenlong.com.tw/zh_tw/bestselling?date=2017-02-28)|4|6|" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Python -> 工程師最佳第二程式語言" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## So... Python 2 or 3 ?..." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 注意:\n", + "* Python 3 主要針對了 Python 的 Unicode 的部分做了修正,解決了很多處理字元編碼的問題,但也破壞了向後相容性。\n", + "* Python 2.7 是 Python 2 的最後一個版本,預計只支援到 2020 年。\n", + "* Python 2.7 版只會對臭蟲跟安全問題做修正,不會再增加新功能。\n", + "* 常用的套件,大部分都已經遷移到 Python 3 上。" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "[![](../images/py3readiness.png)](http://py3readiness.org/)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 建議安裝 Python 3.x!!!\n", + "\n", + "### (本課程使用 Python 3.5)" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/02. Python \345\256\211\350\243\235\345\217\212\344\275\277\347\224\250.ipynb" "b/01_basics/02. Python \345\256\211\350\243\235\345\217\212\344\275\277\347\224\250.ipynb" new file mode 100644 index 0000000..843c195 --- /dev/null +++ "b/01_basics/02. Python \345\256\211\350\243\235\345\217\212\344\275\277\347\224\250.ipynb" @@ -0,0 +1,624 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 安裝及使用" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "3fa64452-39b2-4e24-983d-07a5bf82b02e" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Python 環境建置:Anaconda (推薦)\n", + "\n", + "* 版本:2.x vs. 3.x\n", + "\n", + "[![](images/Anaconda.png)](https://www.continuum.io/downloads)\n", + "\n", + "[More](http://www.ziqiangxuetang.com/python/python-install.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 使用 conda 安裝套件\n", + "\n", + "* 檢查 conda 的版本\n", + "```\n", + "c:\\> conda -V\n", + "```\n", + "\n", + "* 更新 conda\n", + "```\n", + "c:\\> conda update conda\n", + "```\n", + "\n", + "* 安裝 package\n", + "```\n", + "c:\\> conda install -n yourenvname [package]\n", + "# 注意:如果沒有加 \"-n yourenvname\",則套件會被安裝到 root env\n", + "```\n", + "\n", + "* 移除 package\n", + "```\n", + "c:\\> conda uninstall -n yourenvname [package]\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 使用 conda 建立 Virtual Environment\n", + "\n", + "\n", + "* 建立 virtual environment\n", + "```\n", + "c:\\> conda create -n yourenvname python=x.x anaconda\n", + "```\n", + "\n", + "* 列出所有 virtual environment\n", + "```\n", + "c:\\> conda info -e\n", + "```\n", + "\n", + "* 啟動 virtual environment\n", + "```\n", + "c:\\> source activate yourenvname\n", + "```\n", + "\n", + "* 停止 virtual environment\n", + "```\n", + "c:\\> source deactivate\n", + "```\n", + "\n", + "* 刪除 virtual environment\n", + "```\n", + "c:\\> conda remove -n yourenvname --all\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Hello World\n", + "\n", + "* 打開 notepad\n", + "* 鍵入 \"print(\"Hello World!\")\"\n", + "* 存成 hello.py 檔!\n", + "* 在命令列使用 python hello.py 執行!\n", + "```\n", + "c:\\> python hello.py\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "# Python 的程式架構" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "![](images/Python_Syntax.png)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 重點:\n", + "\n", + "* Python 使用空白字元來定義程式結構\n", + " - 每一行最前面的空白字元的數目是有意義的\n", + " - 同一個區塊的縮排需要一樣\n", + "* 使用 import 來載入套件或模組\n", + "* \"#\" 開頭的為註解\n", + "* 引號(單引號或雙引號)標注起來的為字串" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 怎麼尋找 Python 套件?" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "94a40ef6-d5f5-451d-ba73-d11f8d4b2719" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## PyPI (Python Packages Index)\n", + "[![](images/PyPI.png)](https://pypi.python.org/pypi)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 如何安裝套件?" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## [使用 pip](https://pip.pypa.io/en/stable/)\n", + "\n", + "* 安裝套件\n", + "```\n", + "c:\\> pip install \n", + "```\n", + "\n", + "* 更新套件\n", + "```\n", + "c:\\> pip install --upgrade \n", + "```\n", + "\n", + "* 移除套件\n", + "```\n", + "c:\\> pip uninstall \n", + "```\n", + "\n", + "* 搜尋套件\n", + "```\n", + "c:\\> pip search \n", + "```\n", + "\n", + "* 列出已安裝套件\n", + "```\n", + "c:\\> pip list\n", + "```\n", + "\n", + "* 列出已安裝套件 (requirement format)\n", + "```\n", + "c:\\> pip freeze\n", + "```\n", + "\n", + "* 將已安裝之套件及版本輸出成文字檔\n", + "```\n", + "c:\\ pip freeze > requirements.txt\n", + "```\n", + "\n", + "* 從 requirements.txt 安裝對應套件\n", + "```\n", + "c:\\ pip install -r requirements.txt\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Python 的IDE\n", + "\n", + "* [Atom](https://atom.io/)\n", + "* [PyCharm Community Edition](https://www.jetbrains.com/pycharm/download/)\n", + "* [Sublime Text](https://www.sublimetext.com/)\n", + "* [Visual Studio Code](https://code.visualstudio.com/)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "72048d63-6776-41b6-874e-5ef962c3246a" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Python IDE: Spyder (Anaconda 內建)\n", + "![](images/SpyderIDE.png)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "28a11fcd-516d-4007-ae51-4304d199cfbc" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## Python IDE: jupyter notebook (Anaconda 內建)\n", + "* jupyter 由來:[julia](http://julialang.org/) + [Python](https://www.python.org/) + [R](https://www.r-project.org/)\n", + "* 互動式、即見式、展演式\n", + "[![](images/jupyter.png)](http://jupyter.org/)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "e9d95b93-a13a-4adc-9aad-51e724a8e75b" + }, + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## jupyter notebook 基礎常識\n", + "\n", + "* 啟動 jupyter notebook\n", + " - 程式集:搜尋 jupyter notebook => 左鍵點擊 jupyter notebook\n", + " - 終端機 (命令提示字元):輸入 jupyter notebook\n", + "\n", + "* [27 Jupyter Notebook tips, tricks and shortcuts](https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/) ([中譯版](http://www.liuchengxu.org/pelican-blog/jupyter-notebook-tips.html))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 常用的熱鍵或指令\n", + "* 執行區塊:\n", + " - Shfit + Enter 執行該 cell 且跳下一個 cell\n", + " - Ctrl + Enter 執行該 cell (但停在該 cell)\n", + "* 自動填滿:Tab 鍵\n", + "* 提示引數:Shift + Tab\n", + "* 線上諮詢:\n", + " - ?FunctionName()\n", + " - help FunctionName\n", + "* 註解:\n", + " - 單行註解 #\n", + " - 多行註解 ''' '''\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 魔術命令 (Magic Commands) 清單\n", + "%lsmagic" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 的模組及套件" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 什麼是模組?\n", + "\n", + "* 每個 .py 的檔案就是一個模組\n", + "* 模組可以被直接執行,也可以被載入其他模組內執行\n", + "* 每個模組有一個特殊屬性: \"\\_\\_name\\_\\_\"\n", + " - 如果模組被直接執行,\"\\_\\_name\\_\\_\"屬性的值為\"\\_\\_main\\_\\_\"。\n", + " - 如果被載入其他模組,\"\\_\\_name\\_\\_\"屬性的值為自己的模組名稱。" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 什麼是套件?\n", + "\n", + "* 套件為用來管理模組的目錄架構。\n", + "* 每個套件目錄底下,必須有一個名為\"\\_\\_init\\_\\_.py\"的檔案。" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 套件範例:\n", + "\n", + "![](images/package.png)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 怎麼載入模組及套件?\n", + "\n", + "* import\n", + "* import... as...\n", + "* from... import..." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# Python 的模組搜尋路徑\n", + "\n", + "import sys\n", + "\n", + "sys.path" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 如果要使用的模組所在的目錄,不在搜尋的路徑上,可以使用下面方式加入\n", + "\n", + "# 1.\n", + "# sys.path.append(r\"c:\\path\\to\\the\\module\")\n", + "\n", + "# 2.\n", + "# 也可以設定 PYTHONPATH 參數,讓 Python 去搜尋特定路徑\n", + "\n", + "# 3.\n", + "# 設定一個 .pth 檔,將 .pth 檔放在 package 的存放路徑上,.pth 檔裡面填入模組的路徑" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "import site\n", + "\n", + "site.getsitepackages()" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/03. Python \347\232\204\350\256\212\346\225\270.ipynb" "b/01_basics/03. Python \347\232\204\350\256\212\346\225\270.ipynb" new file mode 100644 index 0000000..78a3519 --- /dev/null +++ "b/01_basics/03. Python \347\232\204\350\256\212\346\225\270.ipynb" @@ -0,0 +1,392 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 的變數" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 變數的命名規則\n", + "\n", + "* 變數名稱最好以英文字母或底線做開頭 (數字不能做開頭)\n", + " - \\_variable, variable, variable\\_ \n", + "* 除開頭字元外,其他字元使用數字、底線、或英文字母\n", + " - _var123, var_123\n", + "* 變數會區分大小寫\n", + "* 避開 keywords\n", + "* 避開 [built-in objects](https://docs.python.org/3/library/builtins.html)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "字串 = \"Hello World!\"\n", + "\n", + "print(字串)\n", + "\n", + "# 咦... 可以用中文變數耶!!!\n", + "\n", + "# 但是請不要這樣用,因為在使用很多套件時,這樣的變數名稱可能會造成問題。" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "import string\n", + "\n", + "# help(string)\n", + "\n", + "# ?string\n", + "\n", + "string.ascii_letters" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# Keywords\n", + "\n", + "import keyword\n", + "\n", + "print(keyword.kwlist)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# https://docs.python.org/3/reference/executionmodel.html\n", + "\n", + "# built-in objects\n", + "\n", + "# Python 2.7.x\n", + "#import __builtin__\n", + "#\n", + "#dir(__builtin__)\n", + "\n", + "# Python 3.5\n", + "\n", + "import builtins\n", + "\n", + "print(dir(builtins))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 兩個好用的函數:\n", + "\n", + "* type()\n", + "* dir()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 使用 type() 列出變數型別\n", + "\n", + "a = 1\n", + "\n", + "type(a)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "b = '123'\n", + "\n", + "type(b)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 使用 dir() 列出 local scope 裡面有那些變數或模組等\n", + "dir()\n", + "\n", + "# 關於 magic methods\n", + "# http://minhhh.github.io/posts/a-guide-to-pythons-magic-methods" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 使用 dir(module) 列出模組可以使用的屬性及方法等\n", + "\n", + "dir(sys)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 使用 dir() 列出物件的方法及屬性\n", + "\n", + "print(dir(b))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "c = [1, 2, 3]\n", + "\n", + "type(c)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "print(dir(c))" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/04. Python \347\232\204\350\263\207\346\226\231\345\236\213\346\205\213.ipynb" "b/01_basics/04. Python \347\232\204\350\263\207\346\226\231\345\236\213\346\205\213.ipynb" new file mode 100644 index 0000000..5c1a205 --- /dev/null +++ "b/01_basics/04. Python \347\232\204\350\263\207\346\226\231\345\236\213\346\205\213.ipynb" @@ -0,0 +1,892 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 的資料型態" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 資料型態\n", + "* 數值 number\n", + " - 整數 integer (int)\n", + " - 浮點數 float\n", + " - 複數 (complex)\n", + "* 字串 string (str)\n", + "* 布林 boolean (bool)\n", + "* 日期時間 datetime\n", + "* None" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 整數 int\n", + "A = 3\n", + "type(A)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "B = 2\n", + "C = A + B\n", + "type(C)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 2進位 (0b), 8進位 (0o), 16進位 (0x) 整數\n", + "A = 0b101\n", + "type(A)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "A" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "A = 0xFF\n", + "A" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 型別轉換\n", + "\n", + "# 字串轉整數\n", + "A='10'\n", + "type(A)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "B=int(A)\n", + "type(B)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "B" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 無前綴時,將字串轉乘 8 進位整數\n", + "int('12', 8)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 有前綴時,將字串轉乘 8 進位整數\n", + "int('0o12', 0)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 浮點數轉整數\n", + "int(3.6)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 整數轉成不同進位的字串\n", + "oct(10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "hex(10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 浮點數 float\n", + "A = 1.23\n", + "type(A)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 浮點數另一種表示法\n", + "B = 1E-3\n", + "B" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "C = 2\n", + "type(C)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "D = B + C\n", + "type(D)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 字串 str\n", + "\n", + "# 字串宣告\n", + "Name = 'Victor'\n", + "type(Name)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "ID = '001'\n", + "\n", + "## 字串串聯 (相加)\n", + "NameID = Name + ID\n", + "NameID" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "skip" + } + }, + "outputs": [], + "source": [ + "# 跳脫字元?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "## 字串分割\n", + "sentence = 'It is raining cats and dogs'\n", + "words = sentence.split(' ') # 注意:此處是 ' ' 而非 ''\n", + "print(words)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 格式化輸出\n", + "\n", + "## 傳統作法 I\n", + "print('Name=' + Name + ': A=' + str(A) + '; B=' + str(B))\n", + "\n", + "## 傳統作法 II\n", + "print('Name=%s: A=%d; B=%d' % (Name, A, B))\n", + "print('Name=%s: A=%d; B=%f' % (Name, A, B))\n", + "print('Name=%s: A=%d; B=%3.5f' % (Name, A, B))\n", + "\n", + "''' \n", + "%d is the format code for an integer.\n", + "%f is the format code for a float.\n", + "%s prints the str() of an object\n", + "%r prints the repr() of an object (\n", + "'''\n", + "# http://stackoverflow.com/questions/15215242/python-2-7-d-s-and-float" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "## 建議作法\n", + "print('Name={0}: A={1}; B={2}'.format(Name, A, B))\n", + "print('Name={}: A={}; B={}'.format(Name, A, B))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 什麼是 Unicode?\n", + "\n", + "* [Wikipedia - Unicode](https://en.wikipedia.org/wiki/Unicode)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "fragment" + } + }, + "source": [ + "### 什麼是 Encode()?\n", + "\n", + "將字串轉換成特定格式(如UTF-8)的 bytes,以便於儲存或網路傳輸。 " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "fragment" + } + }, + "source": [ + "### 什麼是 Decode()?\n", + "\n", + "將特定格式的 bytes,轉換回字串以便於顯示。" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "a = \"中文\"\n", + "b = a.encode('utf-8')\n", + "b" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "type(b)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "b.decode('utf-8')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 從字元找對應的 codepoint\n", + "ord('中')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 從 codepoint 找回字元\n", + "chr(20013)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "hex(ord('中'))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 邏輯 bool: True: 1; False: 0\n", + "\n", + "A = 3\n", + "B = 3\n", + "\n", + "A == B\n", + "type(A == B)\n", + "A != B\n", + "\n", + "A is B\n", + "A is not B\n", + "\n", + "res = (A == B)\n", + "res\n", + "res == 0" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# datetime\n", + "#\n", + "# package: datetime\n", + "# http://www.wklken.me/posts/2015/03/03/python-base-datetime.html\n", + "\n", + "# 取得當下的日期與時間\n", + "import datetime" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "now = datetime.datetime.now()\n", + "now" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "type(now) # datetime.datetime" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "datetime.datetime.now().date()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "type(datetime.datetime.now().date()) # datetime.date" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "datetime.datetime.now().time()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "type(datetime.datetime.now().time()) # datetime.time" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "datetime.date.today()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "type(datetime.date.today()) " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 1. 字串 -> 日期\n", + "# 2. 日期 -> 字串\n", + "\n", + "# https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior\n", + "\n", + "# strptime\n", + "s = '2017-03-11'\n", + "datetime.datetime.strptime(s, '%Y-%m-%d')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# datetime 2 string: .strftime(Format)\n", + "date = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n", + "date" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "date = datetime.datetime.now().strftime(\"%Y%m%d\")\n", + "date" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/05. Python \347\232\204\345\256\271\345\231\250\345\236\213\345\210\245.ipynb" "b/01_basics/05. Python \347\232\204\345\256\271\345\231\250\345\236\213\345\210\245.ipynb" new file mode 100644 index 0000000..5172d1a --- /dev/null +++ "b/01_basics/05. Python \347\232\204\345\256\271\345\231\250\345\236\213\345\210\245.ipynb" @@ -0,0 +1,472 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 的容器類別" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 容器類別 (資料結構)\n", + "* [列表 list](http://www.runoob.com/python/python-lists.html)\n", + "* [元組 tuple](http://www.runoob.com/python/python-tuples.html)\n", + "* [字典 dict](http://www.runoob.com/python/python-dictionary.html)\n", + "* [集合 set](http://www.iplaypython.com/jichu/set.html)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 列表 list:[]\n", + "\n", + "## 宣告方式\n", + "list1 = []\n", + "list1 = list()\n", + "type(list1)\n", + "\n", + "list1 = ['B', 'A', 'C'] \n", + "list1\n", + "\n", + "# indexing 索引指標\n", + "list1[0] \n", + "list1[-1]\n", + "\n", + "# slicing\n", + "list1[1:]\n", + "\n", + "# len():計算 list 長度\n", + "len(list1) \n", + "\n", + "list2 = [80, 70]\n", + "\n", + "# list 串聯\n", + "list1 + list2\n", + "\n", + "# list 複製\n", + "list1 * 3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "a = [1, 2, 3]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "a" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "a * 2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b = np.array([1, 2, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b * 2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "## in 隸屬 (包含) operatior\n", + "element = 'C'\n", + "element in list1\n", + "\n", + "element = 'D'\n", + "element in list1\n", + "\n", + "## 排序:sorted()\n", + "sorted(list1)\n", + "sorted(list1, reverse=True)\n", + "\n", + "## 排序:.sort() # 注意:會蓋掉原始序列\n", + "list3 = list1.copy() \n", + "print(list3)\n", + "\n", + "list3.sort()\n", + "print(list3)\n", + "\n", + "list3.sort(reverse=True)\n", + "print(list3)\n", + "\n", + "## 顛倒 list\n", + "list3.reverse()\n", + "print(list3)\n", + "\n", + "## 移除特定 element\n", + "list3.remove('B')\n", + "print(list3)\n", + "\n", + "## 刪除 list\n", + "del list3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# tuple 元組:()\n", + "\n", + "## tuple vs. list: \n", + "# 1. tuple 生成後不可修改;list 生成後可以修改 (區別:記憶體能否動態配置)\n", + "# 2. tuple 的處理效能會優於 list,但 list 的彈性會優於 tuple\n", + "\n", + "## 宣告方式\n", + "tup1 = ()\n", + "tup1 = tuple()\n", + "type(tup1)\n", + "\n", + "tup1 = ('physics', 'chemistry', 1997, 2000)\n", + "tup1\n", + "\n", + "# 型別轉換\n", + "tuple(list1) # list 2 tuple\n", + "list(tup1) # tuple 2 list" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# dict 字典:{key : value}\n", + "\n", + "## 宣告 dict\n", + "dict1 = {}\n", + "type(dict1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "dir(dict)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}\n", + "dict1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "dict1.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "dict1.values()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "dict1.items()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "dict1['Alice']" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# set 集合\n", + "\n", + "# 宣告 set\n", + "set1 = set()\n", + "type(set1)\n", + "\n", + "a = set('abc')\n", + "a.add('wxyz')\n", + "a\n", + "\n", + "a = set('abc')\n", + "a.update('wxyz')\n", + "a\n", + "\n", + "a = set('abc')\n", + "b = set('cde')\n", + "a & b # 交集\n", + "a | b # 聯集\n", + "a - b # 差集" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/06. Python \347\232\204\351\201\213\347\256\227\345\255\220.ipynb" "b/01_basics/06. Python \347\232\204\351\201\213\347\256\227\345\255\220.ipynb" new file mode 100644 index 0000000..6310d75 --- /dev/null +++ "b/01_basics/06. Python \347\232\204\351\201\213\347\256\227\345\255\220.ipynb" @@ -0,0 +1,403 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 的運算子" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 重點:\n", + "\n", + "* 算術運算子\n", + "* 比較運算子\n", + "* 指定運算子\n", + "* 邏輯運算子\n", + "* 位元運算子\n", + "* 成員運算子 (in, not in)\n", + "* 相等運算子 (Identity Operator) (is, is not)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 算術運算子\n", + "\n", + "|運算子|說明|\n", + "|:-:|:-:|\n", + "|+|加法|\n", + "|-|減法|\n", + "|\\*|乘法|\n", + "|/|除法|\n", + "|//|整數除法|\n", + "|**|次方|\n", + "|%|求餘數|" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 比較運算子\n", + "\n", + "|運算子|說明|\n", + "|:-:|:-:|\n", + "|==|等於|\n", + "|!=|不等於|\n", + "|>|大於|\n", + "|<|小於|\n", + "|>=|大於等於|\n", + "|<=|小於等於|" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 指定運算子\n", + "\n", + "|運算子|範例|同義式|\n", + "|:-:|:-:|::|\n", + "|=|a = b||\n", + "|+=|a += b|a = a + b|\n", + "|-=|a -= b|a = a - b|\n", + "|\\*=|a \\*= b|a = a \\* b|\n", + "|/=|a /= b|a = a / b|\n", + "|%=|a %= b|a = a % b|\n", + "|**=|a **= b|a = a ** b|\n", + "|//=|a //= b|a = a // b|" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 邏輯運算子 (Logical Operators)\n", + "\n", + "|運算子|說明|\n", + "|:-:|:-:|\n", + "|and|且|\n", + "|or|或|\n", + "|not|非|" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "a = True\n", + "b = False\n", + "c = True\n", + "\n", + "a and b" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "a and c" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "a or c" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "not (a and b)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 成員運算子 (Membership Operators)\n", + "\n", + "|運算子|說明|\n", + "|:-:|:-:|\n", + "|in|在容器類別中|\n", + "|not in|不在容器類別中|" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "a = [1, 2, 3]\n", + "\n", + "1 in a" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "4 in a" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 位元運算子 (Bitwise Operators)\n", + "\n", + "|運算子|說明|\n", + "|:-:|:-:|\n", + "|&|邏輯 and|\n", + "|||邏輯 or|\n", + "|^|邏輯 xor|\n", + "|~|邏輯 not|\n", + "|>>|位元右移|\n", + "|<<|位元左移|" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 相等預算子 (Identity Operators)\n", + "\n", + "會比較兩變數的記憶體位置是否相等。\n", + "\n", + "|運算子|說明|\n", + "|:-:|:-:|\n", + "|is|物件相等|\n", + "|is not|物件不相等|" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/07. Python \347\232\204\346\265\201\347\250\213\346\216\247\345\210\266.ipynb" "b/01_basics/07. Python \347\232\204\346\265\201\347\250\213\346\216\247\345\210\266.ipynb" new file mode 100644 index 0000000..ac4c6e9 --- /dev/null +++ "b/01_basics/07. Python \347\232\204\346\265\201\347\250\213\346\216\247\345\210\266.ipynb" @@ -0,0 +1,377 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 流程控制" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 重點:\n", + "\n", + "* if 語句\n", + " - if\n", + " - if-else\n", + " - if-elif-else\n", + "* 迴圈\n", + " - for loop\n", + " - while loop\n", + " - continue, break,..." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 條件判斷 if\n", + "name = \"Victor\"\n", + "\n", + "if name == \"Victor\":\n", + " print(\"Hi!\", name)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 條件判斷 if-else\n", + "\n", + "A = 3\n", + "B = 2\n", + "\n", + "if A == B:\n", + " print('A = B')\n", + "else:\n", + " print('A != B')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 條件判斷 if-elif-else\n", + "\n", + "A = 3\n", + "B = 2\n", + "\n", + "if A > B:\n", + " print('A > B')\n", + "elif A < B:\n", + " print('A < B')\n", + "else:\n", + " print('A = B')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# for 迴圈\n", + "\n", + "A = range(10)\n", + "\n", + "for i in A:\n", + " print('{} \\n'.format(i))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "help(range)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# for 迴圈\n", + "\n", + "A = range(1,10, 2)\n", + "\n", + "for i, item in enumerate(A): # enumerate: iterator\n", + " print('{}: {} \\n'.format(i, item))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# while 迴圈\n", + "\n", + "count = 0\n", + "while (count < 8):\n", + " print(count)\n", + " count += 1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# while 迴圈\n", + "\n", + "count = 0\n", + "while (count < 8):\n", + " count += 1\n", + " if count % 2 == 0:\n", + " continue\n", + " print(count)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# while 迴圈\n", + "\n", + "count = 0\n", + "while (count < 8):\n", + " count += 1\n", + " if count % 2 == 0:\n", + " break\n", + " print(count)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# while 迴圈\n", + "\n", + "count = 0\n", + "while (count < 10):\n", + " if count % 3 == 0:\n", + " print(str(count))\n", + " count += 1" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/08. Python \347\232\204\345\207\275\345\274\217.ipynb" "b/01_basics/08. Python \347\232\204\345\207\275\345\274\217.ipynb" new file mode 100644 index 0000000..5955c3a --- /dev/null +++ "b/01_basics/08. Python \347\232\204\345\207\275\345\274\217.ipynb" @@ -0,0 +1,441 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 函式" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 函式 (Functions)\n", + "\n", + "* 使用 def 定義函式\n", + "* pass\n", + "* lambda function (匿名函式)\n", + "* 位置引數 (positional arguments)\n", + "* 關鍵字引數 (keyword arguments)\n", + "* 預設引數 (default arguments)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 函式定義\n", + "def f():\n", + " print(\"Hello!\")\n", + "\n", + "# 函式呼叫\n", + "f()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 空函式\n", + "def f():\n", + " pass\n", + "\n", + "f()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# def function\n", + "def f(x): \n", + " return x**2\n", + "\n", + "def f(x): return x**2\n", + "\n", + "# lambda function\n", + "g = lambda x: x**2\n", + "\n", + "f(3)\n", + "g(3)\n", + "\n", + "MySum = lambda x, y: x + y\n", + "MySum(3,2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "## 字串分割\n", + "sentence = 'It is raining cats and dogs'\n", + "words = sentence.split(' ') # 注意:此處是 ' ' 而非 ''\n", + "type(words)\n", + "print(words)\n", + "\n", + "lengths = map(lambda word: len(word), words)\n", + "print(lengths)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# function\n", + "\n", + "def MyMean(data):\n", + " total = 0\n", + " for num in data: # 避免使用回圈是提高計算效率的關鍵之一\n", + " total = total + num\n", + " return total / len(data)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "data = [1, 2, 5, 8, 11]\n", + "MyMean(data)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# Positional Parameters\n", + "def f(a, b, c):\n", + " return {'a':a, 'b':b, 'c':c}\n", + "\n", + "f(1, 2, 3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# Keyword Parameters\n", + "def f(a, b, c):\n", + " return {'a':a, 'b':b, 'c':c}\n", + "\n", + "f(b=1, c=2, a=3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "f(1, c=2, b=3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# * 跟 ** 的使用\n", + "def f(*args):\n", + " print(args)\n", + "\n", + "f(1, 2, 3, 4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "def f(**kwargs):\n", + " print(kwargs)\n", + " \n", + "f(a=1, b=2, c=3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "def f(*args, **kwargs):\n", + " print(\"args:\", args)\n", + " print(\"kwargs:\", kwargs)\n", + " \n", + "f(1, 2, 3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# unpacking\n", + "\n", + "arg_dict = {'a':1, 'b':2, 'c':3}\n", + "\n", + "f(**arg_dict)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# default arguments?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# decorator?" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/09. Python \347\224\237\346\210\220\345\274\217 (Comprehension).ipynb" "b/01_basics/09. Python \347\224\237\346\210\220\345\274\217 (Comprehension).ipynb" new file mode 100644 index 0000000..60ceef9 --- /dev/null +++ "b/01_basics/09. Python \347\224\237\346\210\220\345\274\217 (Comprehension).ipynb" @@ -0,0 +1,258 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 生成式 (Comprehension)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 重點:\n", + "\n", + "* list comprehension\n", + "* dict comprehension\n", + "* set comprehension\n", + "* generator comprehension" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# list comprehension\n", + "a = [1, 2, 3]\n", + "b = [e**2 for e in a]\n", + "b" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# dict comprehension\n", + "word = \"letters\"\n", + "letter_counts = {letter: word.count(letter) for letter in word}\n", + "letter_counts" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# set comprehension\n", + "a_set = {number for number in range(1, 6) if number % 3 == 1}\n", + "a_set" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# generator comprehension\n", + "a = [1, 2, 3]\n", + "b = (e**2 for e in a)\n", + "b" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "for c in b:\n", + " print(c)" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/10. Python \347\232\204\346\252\224\346\241\210 IO.ipynb" "b/01_basics/10. Python \347\232\204\346\252\224\346\241\210 IO.ipynb" new file mode 100644 index 0000000..c33b7ee --- /dev/null +++ "b/01_basics/10. Python \347\232\204\346\252\224\346\241\210 IO.ipynb" @@ -0,0 +1,387 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 的檔案IO" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 常見的儲存方式\n", + "* 文字檔:txt (tab 分隔 / space 分隔)、csv (逗點分隔)\n", + "* EXCEL 檔:xls / xlsx\n", + "* 網路檔:html / xml / json\n", + "* 資料庫:SQLite / PostgreSQL / MySQL..." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 一般文字檔" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 寫入檔案\n", + "file = open('test.txt','w')\n", + "file.write('this is a test!')\n", + "file.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### mode 字串\n", + "|字元|說明|\n", + "|:-:|:-|\n", + "|r|讀取模式|\n", + "|w|寫入模式|\n", + "|x|檔案不存在時才寫入|\n", + "|a|附加模式|\n", + "|b|二進位模式|\n", + "|t|文字模式|\n", + "|+|更新模式|" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 讀取檔案:\n", + "file = open('test.txt', 'r')\n", + "# 把所有資料一次全部讀進來\n", + "text = file.read()\n", + "\n", + "print(text)\n", + "# 關閉檔案\n", + "file.close()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 讀取檔案:\n", + "# 如果沒有第二個參數,表示預設的模式是 'r'\n", + "file = open('test.txt')\n", + "\n", + "# 一次全部讀進來,但是分行\n", + "text = file.readlines()\n", + "\n", + "print(text)\n", + "\n", + "# 關閉檔案\n", + "file.close()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 讀取檔案:\n", + "file = open('test.txt')\n", + "\n", + "# 將資料一行一行的讀進來處理\n", + "for line in file:\n", + " print(line)\n", + "\n", + "# 關閉檔案\n", + "file.close()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 附加資料 (Append)\n", + "file = open('test.txt', 'a')\n", + "file.write('this is a test!')\n", + "file.close()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 如果不想每一次都要呼叫 close() 來關閉檔案,則可以使用 with … as 語法。\n", + "with open('test.txt') as file:\n", + " text = file.read()\n", + " print(text)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### .csv 檔\n", + "\n", + "### csv 是 Comma Separated Values 的縮寫" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "import csv" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 台灣證券交易所 - 加權指數歷史資料\n", + "# http://www.tse.com.tw/ch/trading/indices/MI_5MINS_HIST/MI_5MINS_HIST.php#\n", + "# 此範例取自 \"Python 3.5 技術手冊, 林信良\"\n", + "with open('MI_5MINS_HIST10603.csv', encoding='Big5') as f:\n", + " for row in csv.reader(f):\n", + " print(row)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "with open('MI_5MINS_HIST10603.csv', encoding='Big5') as rf:\n", + " with open('10603-UTF8.csv', 'w', encoding='UTF-8', newline='') as wf:\n", + " rows = csv.reader(rf)\n", + " csv.writer(wf).writerows(rows)" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/11. Python \347\232\204\347\266\262\350\267\257\350\263\207\346\226\231\346\223\267\345\217\226.ipynb" "b/01_basics/11. Python \347\232\204\347\266\262\350\267\257\350\263\207\346\226\231\346\223\267\345\217\226.ipynb" new file mode 100644 index 0000000..0c4b75e --- /dev/null +++ "b/01_basics/11. Python \347\232\204\347\266\262\350\267\257\350\263\207\346\226\231\346\223\267\345\217\226.ipynb" @@ -0,0 +1,253 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 的網路資料擷取" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 重點:\n", + "\n", + "* 怎麼使用 requests 擷取網路資料?\n", + "* 處理 json 資料\n", + "* 處理 html 資料" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "import requests\n", + "import json" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "r=requests.get('http://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindAllTypeJ')\n", + "r.text" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 載入 json 檔案\n", + "doc=json.loads(r.text)\n", + "print(doc[0]['categoryName'])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "dict1 = {'a':1, 'b':2, 'c':3}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "doc1 = str(dict1)\n", + "doc1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "doc2 = json.dumps(dict1)\n", + "doc2" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/12. Python \347\232\204\344\276\213\345\244\226\350\231\225\347\220\206.ipynb" "b/01_basics/12. Python \347\232\204\344\276\213\345\244\226\350\231\225\347\220\206.ipynb" new file mode 100644 index 0000000..9156946 --- /dev/null +++ "b/01_basics/12. Python \347\232\204\344\276\213\345\244\226\350\231\225\347\220\206.ipynb" @@ -0,0 +1,230 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "\n", + "# Python 的例外處理" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### 重點:\n", + "\n", + "* try... except\n", + "* try... except... else\n", + "* try... except... else... finally" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "a = 1\n", + "b = 0\n", + "a / b" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 如果知道可能產生的錯誤是甚麼\n", + "\n", + "try:\n", + " a / b\n", + "except ZeroDivisionError:\n", + " print(\"哇!除數是零!\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "import sys\n", + "\n", + "try:\n", + " a / b\n", + "except:\n", + " print(sys.exc_info())" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/01_basics/13. Python \347\232\204\347\211\251\344\273\266\345\260\216\345\220\221\347\250\213\345\274\217\350\250\255\350\250\210.ipynb" "b/01_basics/13. Python \347\232\204\347\211\251\344\273\266\345\260\216\345\220\221\347\250\213\345\274\217\350\250\255\350\250\210.ipynb" new file mode 100644 index 0000000..e56cce6 --- /dev/null +++ "b/01_basics/13. Python \347\232\204\347\211\251\344\273\266\345\260\216\345\220\221\347\250\213\345\274\217\350\250\255\350\250\210.ipynb" @@ -0,0 +1,511 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "nbpresent": { + "id": "904e7041-5347-4036-bfff-4b5af4763913" + }, + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Python 程式設計教學\n", + "\n", + "## Victor Gau\n", + "\n", + "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", + "\n", + "### 2017-03-11\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# 物件導向程式設計\n", + "## (Object-Orientation Programming, OOP)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 注意:\n", + "\n", + "* 解決問題並不一定需要使用物件導向設計。\n", + "* 雖然在 Python 中,萬物皆為物件!但Python之父 Guido van Rossum 曾經說過,自己並非物件導向的信徒。" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 物件導向設計的三大核心觀念:\n", + "\n", + "* 封裝 (Encapulation)\n", + "* 繼承 (Inheritance)\n", + "* 多型 (Polymorphism)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "## 重點:\n", + "\n", + "* 怎麼定義類別?\n", + "* 生成物件 (Instantiation)\n", + "* \\_\\_new\\_\\_, \\_\\_init\\_\\_, \\_\\_del\\_\\_\n", + "* 類別屬性\n", + "* 類別方法\n", + "* 靜態方法\n", + "* 物件屬性\n", + "* 物件方法\n", + "* 繼承\n", + "* 多型" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 定義類別\n", + "class Human:\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 生成物件\n", + "human1 = Human()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 定義物件屬性\n", + "human1.name = \"Victor\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "human2 = Human()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "human2.name" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# __new__(): 要生成物件時被呼叫,初學者通常不會實作這個方法。\n", + "# __init__(): 要初始化物件時被呼叫\n", + "# __del()__: 要刪除物件時被呼叫\n", + "\n", + "class Human:\n", + " # 類別屬性\n", + " count = 0\n", + " \n", + " def __init__(self):\n", + " Human.count += 1\n", + " \n", + " def __del__(self):\n", + " Human.count -= 1\n", + "\n", + "human1 = Human()\n", + "Human.count" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "human2 = Human()\n", + "Human.count" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "del human1\n", + "Human.count" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "del human2\n", + "Human.count" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 增加兩個方法,描述物件的行為\n", + "\n", + "class Human:\n", + " # 類別屬性\n", + " count = 0\n", + " \n", + " def __init__(self, name):\n", + " self.name = name\n", + " Human.count += 1\n", + " \n", + " def __del__(self):\n", + " Human.count -= 1\n", + " \n", + " def sleep(self):\n", + " print(self.name, \"sleeps!\")\n", + " \n", + " def attack(self):\n", + " print(self.name, \"attacks with bare hands.\") \n", + "\n", + "human1 = Human(\"John\")\n", + "human1.sleep()\n", + "human1.attack()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "# 繼承\n", + "class Knight(Human):\n", + " pass\n", + "\n", + "# 父類別的方法被繼承下來了\n", + "knight1 = Knight('Jack')\n", + "knight1.sleep()\n", + "knight1.attack()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "# 多型\n", + "class Knight(Human):\n", + " def attack(self):\n", + " print(self.name, \"attacks with a sword.\")\n", + "\n", + "class Wizard(Human):\n", + " def attack(self):\n", + " print(self.name, \"attacks with a spell.\")\n", + "\n", + "human1 = Knight(\"David\")\n", + "human2 = Wizard(\"Tom\")\n", + "\n", + "group1 = [human1, human2]\n", + "\n", + "for man in group1:\n", + " man.attack()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "class Human:\n", + " # 類別屬性\n", + " count = 0\n", + " \n", + " def __init__(self, name):\n", + " self.name = name\n", + " Human.count += 1\n", + " \n", + " def __del__(self):\n", + " Human.count -= 1\n", + " \n", + " def sleep(self):\n", + " print(self.name, \"sleeps!\")\n", + " \n", + " def attack(self):\n", + " print(self.name, \"attacks with bare hands.\")\n", + " \n", + " @staticmethod\n", + " def fight(man1, man2):\n", + " print(man1.name, \"fights\", man2.name)\n", + " \n", + " @classmethod\n", + " def default(clz):\n", + " return clz('John Doe')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "human3 = Human.default()\n", + "human3.name" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "slideshow": { + "slide_type": "fragment" + } + }, + "outputs": [], + "source": [ + "Human.fight(human1, human2)" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "celltoolbar": "Slideshow", + "kernelspec": { + "display_name": "Python [default]", + "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.5.2" + }, + "livereveal": { + "scroll": true + }, + "nbpresent": { + "slides": {}, + "themes": { + "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "theme": { + "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { + "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", + "palette": { + "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { + "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", + "rgb": [ + 252, + 252, + 252 + ] + }, + "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { + "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", + "rgb": [ + 68, + 68, + 68 + ] + }, + "50f92c45-a630-455b-aec3-788680ec7410": { + "id": "50f92c45-a630-455b-aec3-788680ec7410", + "rgb": [ + 155, + 177, + 192 + ] + }, + "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { + "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "rgb": [ + 43, + 126, + 184 + ] + }, + "efa7f048-9acb-414c-8b04-a26811511a21": { + "id": "efa7f048-9acb-414c-8b04-a26811511a21", + "rgb": [ + 25.118061674008803, + 73.60176211453744, + 107.4819383259912 + ] + } + }, + "rules": { + "blockquote": { + "color": "50f92c45-a630-455b-aec3-788680ec7410" + }, + "code": { + "font-family": "Anonymous Pro" + }, + "h1": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 8 + }, + "h2": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 6 + }, + "h3": { + "color": "50f92c45-a630-455b-aec3-788680ec7410", + "font-family": "Lato", + "font-size": 5.5 + }, + "h4": { + "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", + "font-family": "Lato", + "font-size": 5 + }, + "h5": { + "font-family": "Lato" + }, + "h6": { + "font-family": "Lato" + }, + "h7": { + "font-family": "Lato" + }, + "pre": { + "font-family": "Anonymous Pro", + "font-size": 4 + } + }, + "text-base": { + "font-family": "Merriweather", + "font-size": 4 + } + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git "a/02_numpy_matplotlib_pandas/01. Numpy \347\260\241\344\273\213.ipynb" "b/02_numpy_matplotlib_pandas/01. Numpy \347\260\241\344\273\213.ipynb" new file mode 100644 index 0000000..0ec86ad --- /dev/null +++ "b/02_numpy_matplotlib_pandas/01. Numpy \347\260\241\344\273\213.ipynb" @@ -0,0 +1,752 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Numpy 簡介" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Numpy 是 Numerical Python 的簡稱,是 Python 用來作科學運算的基礎套件。\n", + "\n", + "#### 這一份筆記主要說明以下重點:\n", + "\n", + "* 為何需要 Numpy?\n", + "* Numpy 比 pure python 提供了那些不一樣的東西?\n", + "* 怎麼使用 Numpy 的 ndarray?\n", + "* 投資理財相關領域中常用的 Numpy 的函式有哪些?\n", + "\n", + "#### 參考資料:\n", + "\n", + "* [Numpy 官網](http://www.numpy.org/)\n", + "* [Numpy 教學](https://docs.scipy.org/doc/numpy-dev/user/quickstart.html)\n", + "* [Python Numpy Array Tutorial](https://www.datacamp.com/community/tutorials/python-numpy-tutoria)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 為什麼需要 Numpy?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 關於向量運算:\n", + "\n", + "在工程、科學及金融領域,需要用到很多向量運算。簡單說明如下:\n", + "\n", + "假設有兩個向量 (Vectors) A 跟 B,\n", + "\n", + "$A = \\left(\n", + " \\begin{array}{c}\n", + " a_1 \\\\\n", + " a_2 \\\\\n", + " a_3\n", + " \\end{array}\n", + " \\right)\n", + "$\n", + "\n", + "$B = \\left(\n", + " \\begin{array}{c}\n", + " b_1 \\\\\n", + " b_2 \\\\\n", + " b_3\n", + " \\end{array}\n", + " \\right)\n", + "$\n", + "\n", + "向量加法運算如下:\n", + "\n", + "$A + B = \\left(\n", + " \\begin{array}{c}\n", + " a_1 + b_1 \\\\\n", + " a_2 + b_2 \\\\\n", + " a_3 + b_3\n", + " \\end{array}\n", + " \\right)\n", + "$\n", + "\n", + "向量的純量積算法如下:\n", + "\n", + "$c \\cdot A = \n", + " \\left(\n", + " \\begin{array}{c}\n", + " ca_1 \\\\\n", + " ca_2 \\\\\n", + " ca_3\n", + " \\end{array}\n", + " \\right)\n", + "$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. python 的 list 沒有辦法直接作向量運算。" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "A = [1, 2, 3]\n", + "B = [4, 5, 6]\n", + "A + B" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "A * 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. 替代性的方法運算速度緩慢" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "C = []\n", + "for i, j in zip(A, B):\n", + " C.append(i + j)\n", + "C" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "D = []\n", + "for i in A:\n", + " D.append(i * 2)\n", + "D" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. Numpy 提供簡易即迅速的方式執行上面那些向量運算" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import numpy as np" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "A1 = np.array(A)\n", + "B1 = np.array(B)\n", + "A1 + B1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "A1 * 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Numpy 提供了什麼不一樣的東西?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Numpy 中主要提供了一個叫做多維陣列 ndarray, or Multi-dimensional Array 的資料結構,透過它可以直接作向量運算。\n", + "#### ndarray 有兩個重要的屬性 dtype 及 shape,dtype 為 ndarry 裡面的資料的型態,而 shape 則為資料的形狀。\n", + "#### 底下會用例子加以說明。" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Numpy 中的兩大概念:\n", + "\n", + "* 資料結構\n", + " - ndarray\n", + " - dtype\n", + " - shape\n", + "\n", + "\n", + "* 通用函式\n", + " - ufunc\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 如何創建 ndarray?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 最簡單的方法就是使用 Numpy 的 array 函式。" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "X = [1, 2, 3]\n", + "Y = np.array(X)\n", + "Y" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "Z = np.array([4, 5, 6])\n", + "Z" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "Z.dtype" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "Z.shape" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 其他的創建方式\n", + "\n", + "|函式|說明|\n", + "|:-|:-|\n", + "|array|將輸入的資料轉換成 ndarray。|\n", + "|arange|range 的 ndarray 版。|\n", + "|ones, ones_like|創建一個全部是1的ndarray。|\n", + "|zeros, zeros_like|創建一個全部是0的ndarray。|\n", + "|empty, empty_like|創建一個未填入資料的ndarray。|\n", + "|eye, identity|創建一個單位矩陣。|" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "I = np.eye(4)\n", + "I" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "I.shape" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G = np.arange(25)\n", + "G" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G.shape" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "F = G.reshape(5, 5)\n", + "F" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G.shape = 5, 5\n", + "G" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ndarray 的 indexing" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G[1, 1]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G[1][1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ndarray 的 slicing" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G[0]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G[0, :]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G[:, 0]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G[:][0]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G[1:3, 1:3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ndarray 的 boolean indexing" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G > 10" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "G[G > 10]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.where(G > 10, G, 0)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.all(G > -1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.all(G < 25)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.all(G > 0)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.any(G > 0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 什麼是 ufunc?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* universal function 的縮寫\n", + "* 用來對 ndarray 裡面的每個元素作操作的函式。\n", + "* ufunc 可以被看作是一般 python 函式的向量化版本。\n", + "* Numpy 的 ufunc 都是衍生自 numpy.ufunc 類別。\n", + "* 很多內建的 ufunc 底層都是使用 C 實作的,所以速度很快。\n", + "\n", + "詳細內容請參考:[ufuncs](https://docs.scipy.org/doc/numpy/reference/ufuncs.html)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "isinstance(np.sin, np.ufunc)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "isinstance(np.arange, np.ufunc)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import math\n", + "math.pi" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "K = np.arange(0, 2, 0.1)\n", + "K = K * math.pi\n", + "K" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.sin(K)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "import matplotlib.pyplot as plt\n", + "plt.plot(np.sin(K))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### numpy 有哪些 ufuncs?\n", + "\n", + "想知道 numpy 有哪些 ufunc ,可以參考官網上面的連結:[Available ufuncs](https://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 金融投資相關領域中常用的 numpy 函式有哪些?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* [Numpy 的函式列表](https://docs.scipy.org/doc/numpy/reference/routines.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 統計相關函式\n", + "\n", + "參考:[Statistics](https://docs.scipy.org/doc/numpy-1.12.0/reference/routines.statistics.html)\n", + "\n", + "|函式|說明|\n", + "|:-|:-|\n", + "|sum|總和|\n", + "|mean|平均|\n", + "|std|標準差|\n", + "|var|變異數|\n", + "|min, max|最小值、最大值|\n", + "|argmin, argmax|最小值的索引、最大值的索引|\n", + "|cumsum|和的累計值|\n", + "|cumprod|積的累計值|" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 亂數相關函式\n", + "\n", + "參考:[Random Sampling (numpy.random)](https://docs.scipy.org/doc/numpy/reference/routines.random.html)\n", + "\n", + "|函式|說明|\n", + "|:-|:-|\n", + "|[seed](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html#numpy.random.seed)|設定亂數的種子|\n", + "|[permutation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html)|隨機排列|\n", + "|[shuffle](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html)|沿著 axis 0 的隨機排列|\n", + "|[rand](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand)|返回指定形狀的亂數,亂數值為[0,1]間的均勻分布|\n", + "|[randn](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn)|返回指定形狀的亂數,亂數值為mean為0,variance為1的高斯分布|\n", + "|[randint](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint)|使用離散均勻分布,返回指定形狀的整數亂數|\n", + "|[normal](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal)|返回指定形狀的亂數,亂數值為自訂的mean跟variance的高斯分布|\n", + "|[uniform](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform)|使用均勻分布,返回指定形狀的亂數|" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.random.seed(10)\n", + "np.random.rand(5)" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python [conda root]", + "language": "python", + "name": "conda-root-py" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git "a/02_numpy_matplotlib_pandas/02. MatPlotLib \347\260\241\344\273\213.ipynb" "b/02_numpy_matplotlib_pandas/02. MatPlotLib \347\260\241\344\273\213.ipynb" new file mode 100644 index 0000000..bcca85c --- /dev/null +++ "b/02_numpy_matplotlib_pandas/02. MatPlotLib \347\260\241\344\273\213.ipynb" @@ -0,0 +1,631 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# MatPlotLib 簡介" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### MatPlotLib 是 Matrix Plotting Libray 的縮寫。它是 Python 最主要的 2D 繪圖套件,是用 Python 來畫圖的首選套件。" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 這一份筆記主要說明以下重點:\n", + "\n", + "* MatPlotLib 的架構\n", + "* 怎麼使用 MatPlotLib 畫圖?\n", + "* 針對一維資料作圖\n", + "* 針對二維資料作圖\n", + "* 控制線型、顏色\n", + "* 控制圖形參數(標題、X軸、Y軸標題等)\n", + "* 圖形上的文字標註\n", + "* 圖面上的中文顯示\n", + "* 子圖 (Subplot)\n", + "* 畫其他的圖表 (散步圖、餅圖、直方圖等)\n", + "* 金融圖形 (K線圖等等)\n", + "\n", + "參考資料:\n", + "\n", + "* [Github of Python for Finance](https://github.com/yhilpisch/py4fi)\n", + "* [Github of Python for Data Analysis](https://github.com/wesm/pydata-book)\n", + "* [Wiki - MatPlotLib](https://en.wikipedia.org/wiki/Matplotlib)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## MatPlotLib 的架構\n", + "\n", + "MatPlotLib 的架構分成三層:Scripting Layer, Artist Layer, 跟 Backend Layer。\n", + "\n", + "Backend Layer 負責將圖形實際繪製出來。屬於比較低階的操作,一般使用者較少直接接觸。\n", + "\n", + "Artist Layer 負責告訴 Backend Layer 要畫那些東西,是用來組成繪圖物件 (lines, rectangles, text, 等等) 的地方,Artist 物件主要分成 Primitives 跟 Containers 兩種。Primitives 為需要被畫出來的圖形 (lines, rectangles 等),而 Containers (如 axes 等) 則是用來放置圖形物件的地方。\n", + "\n", + "Scripting Layer 提供了更簡單的操作介面,讓使用者可以更容易地去控制 Artist Layer。初學者大致上只會用到 Scripting Layer。\n", + "\n", + "參考資料:\n", + "\n", + "* [MatPlotLib](http://www.aosabook.org/en/matplotlib.html)\n", + "* [Artist Tutorial](http://matplotlib.org/users/artists.html)\n", + "* [Plotting commands summary](http://matplotlib.org/api/pyplot_summary.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[](http://www.aosabook.org/en/matplotlib.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[](http://www.aosabook.org/en/matplotlib.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 怎麼使用 MatPlotLib 畫圖?\n", + "\n", + "在 Jupyter Notebook 裡面使用 MatPlotLib 畫圖可以加上底下的魔術命令,讓產生的圖形嵌入 HTML 頁面中。\n", + "\n", + "```\n", + "%matplotlib inline\n", + "```\n", + "\n", + "我們主要使用的是 matplotlib.pyplot 這個模組來做 scripting 的動作。\n", + "\n", + "慣例上,我們會用以下的方式載入模組。\n", + "\n", + "```\n", + "import matplotlib.pyplot as plt\n", + "```\n", + "\n", + "接著,使用 plt.plot() 函式即可作圖。" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "# 載入 pyplot 時,通常使用如下慣例\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# 載入 numpy 時,通常使用如下慣例\n", + "import numpy as np" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "plt.plot?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 針對一維資料作圖" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.arange(10)\n", + "plt.plot(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "如果是寫成獨立的程式 (.py 檔),則需用下面程式來顯示圖形。\n", + "\n", + "```\n", + "plt.show()\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 針對二維資料作圖" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.random.rand(10, 2)\n", + "plt.plot(x)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.random.rand(10, 2)\n", + "plt.plot(x)\n", + "\n", + "# 畫點\n", + "i=3\n", + "plt.plot(i, x[i, 0], '^')\n", + "\n", + "# 畫線 plt.plot([x1, x2], [y1, y2])\n", + "j=7\n", + "plt.plot([i, j], [x[i, 0], x[j, 0]], 'k-')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 控制線型、顏色\n", + "\n", + "參考資料:[matplotlib.pyplot.plot](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.arange(10)\n", + "plt.plot(x, 'r')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.arange(10)\n", + "plt.plot(x, 'ro')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.arange(10)\n", + "plt.plot(x, 'ro-')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 控制圖形參數(標題、X軸、Y軸標題等)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.arange(10)\n", + "plt.plot(x, 'ro-')\n", + "plt.title('Demo')\n", + "plt.xlabel('X Axis')\n", + "xplt.ylabel('Y Axis')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.random.rand(10)\n", + "plt.plot(x)\n", + "plt.grid(True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.random.rand(10)\n", + "plt.plot(x, label='line 01')\n", + "plt.legend(loc=0)\n", + "# location code 請參考:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.random.rand(10)\n", + "plt.plot(x)\n", + "plt.xlim(-1, 10)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 圖形上的文字標註\n", + "\n", + "參考:[Text Introduction](http://matplotlib.org/users/text_intro.html)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.random.rand(10)\n", + "plt.plot(x)\n", + "i = 5\n", + "plt.text(i, x[i], str(x[i]))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 圖面上的中文顯示" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from matplotlib.font_manager import FontProperties\n", + "font = FontProperties(fname=r\"c:\\windows\\fonts\\simsun.ttc\", size=14)\n", + "\n", + "x = np.arange(10)\n", + "plt.plot(x)\n", + "plt.title('中文測試', fontproperties=font)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 子圖 (Subplot)\n", + "\n", + "參考資料:[Subplot Demo](http://matplotlib.org/examples/pylab_examples/subplots_demo.html)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.subplot(211)\n", + "x = np.arange(10)\n", + "plt.plot(x)\n", + "plt.subplot(212)\n", + "y = np.random.rand(10)\n", + "plt.plot(y)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.subplot(121)\n", + "x = np.arange(10)\n", + "plt.plot(x)\n", + "plt.subplot(122)\n", + "y = np.random.rand(10)\n", + "plt.plot(y)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.subplot(221)\n", + "x1 = np.random.rand(10)\n", + "plt.plot(x1, 'ro')\n", + "plt.subplot(222)\n", + "x2 = np.random.rand(10)\n", + "plt.plot(x2, 'b^')\n", + "plt.subplot(223)\n", + "x3 = np.random.rand(10)\n", + "plt.plot(x3, 'gx')\n", + "plt.subplot(224)\n", + "x4 = np.random.rand(10)\n", + "plt.plot(x4, 'k*')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 畫其他的圖表 (散布圖、餅圖、直方圖等)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# 請參考:http://matplotlib.org/examples/shapes_and_collections/scatter_demo.html\n", + "N = 50\n", + "x = np.random.rand(N)\n", + "y = np.random.rand(N)\n", + "colors = np.random.rand(N)\n", + "area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii\n", + "\n", + "plt.scatter(x, y, s=area, c=colors, alpha=0.5)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# 請參考:http://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html\n", + "# Pie chart, where the slices will be ordered and plotted counter-clockwise:\n", + "labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'\n", + "sizes = [15, 30, 45, 10]\n", + "explode = (0, 0.1, 0, 0) # only \"explode\" the 2nd slice (i.e. 'Hogs')\n", + "\n", + "fig1, ax1 = plt.subplots()\n", + "ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',\n", + " shadow=True, startangle=90)\n", + "ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# bar chart - 1\n", + "N = 10\n", + "y = np.random.randint(1, 10, size=N)\n", + "x = range(N)\n", + "width = 0.5\n", + "plt.bar(x, y, width, color=\"blue\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# bar chart - 2\n", + "N = 10\n", + "y = np.random.randint(1, 10, size=N)\n", + "x = np.arange(N)\n", + "width = 0.5\n", + "plt.bar(x - 0.25, y, width, color=\"blue\")\n", + "plt.xlim(-1, 10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "y" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# histogram\n", + "x = np.random.randn(1000)\n", + "n_bins = 10\n", + "\n", + "plt.hist(x, n_bins, color='g', rwidth=0.8)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 金融圖形 (K線圖等等)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.finance as mpf\n", + "\n", + "start = (2014, 5, 1)\n", + "end = (2014, 6, 30)\n", + "\n", + "quotes = mpf.quotes_historical_yahoo_ohlc('YHOO', start, end)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(figsize=(8, 5))\n", + "fig.subplots_adjust(bottom=0.2)\n", + "mpf.candlestick_ohlc(ax, quotes, width=0.6, colorup='g', colordown='r')\n", + "plt.grid(True)\n", + "ax.xaxis_date() # dates on the x axis\n", + "ax.autoscale_view()\n", + "plt.setp(plt.gca().get_xticklabels(), rotation=30)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(figsize=(8, 5))\n", + "mpf.plot_day_summary_ohlc(ax, quotes, colorup='g', colordown='r')\n", + "plt.grid(True)\n", + "ax.xaxis_date()\n", + "plt.title('Yahoo Inc.')\n", + "plt.ylabel('Prices')\n", + "plt.setp(plt.gca().get_xticklabels(), rotation=30)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "quotes = np.array(quotes)\n", + "fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8, 6))\n", + "mpf.candlestick_ohlc(ax1, quotes, width=0.6, colorup='g', colordown='r')\n", + "ax1.set_title('Yahoo Inc.')\n", + "ax1.set_ylabel('Prices')\n", + "ax1.grid(True)\n", + "ax1.xaxis_date()\n", + "plt.bar(quotes[:, 0] - 0.25, quotes[:, 5], width=0.5)\n", + "ax2.set_ylabel('volume')\n", + "ax2.grid(True)\n", + "ax2.autoscale_view()\n", + "plt.setp(plt.gca().get_xticklabels(), rotation=30)" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python [conda root]", + "language": "python", + "name": "conda-root-py" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git "a/02_numpy_matplotlib_pandas/03. Pandas \347\260\241\344\273\213.ipynb" "b/02_numpy_matplotlib_pandas/03. Pandas \347\260\241\344\273\213.ipynb" new file mode 100644 index 0000000..9ed6177 --- /dev/null +++ "b/02_numpy_matplotlib_pandas/03. Pandas \347\260\241\344\273\213.ipynb" @@ -0,0 +1,668 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Pandas 簡介" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Pandas 是 Python 裡面被用來作資料分析及整理最常用的套件。" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 這一份筆記主要說明以下重點:\n", + "\n", + "* 資料結構及其基本操作\n", + " - Series\n", + " - DataFrame\n", + "* 網路資料存取\n", + "* 資料視覺化\n", + "* 資料分組及聚合\n", + "\n", + "參考資料:\n", + "\n", + "* [Python Data Analysis Library](http://pandas.pydata.org/)\n", + "* [Pandas Cookbook](http://pandas.pydata.org/pandas-docs/version/0.18.0/cookbook.html)\n", + "* [Pandas 入門介紹](https://github.com/Wei1234c/Introduction_to_Pandas)\n", + "* [Financial Time Series](https://github.com/yhilpisch/py4fi/blob/master/ipython3/06_Financial_Time_Series.ipynb)\n", + "* [Pandas API references](http://pandas.pydata.org/pandas-docs/stable/api.html#api-dataframe-stats)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pandas as pd\n", + "\n", + "pd.__version__" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "import numpy as np" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Pandas 的資料結構" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Series" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s = pd.Series([1, 2, 3, 4, 5])\n", + "s" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Series 跟 ndarray 有什麼不同呢?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s.values" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s.index" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### index 可以在創建 Series 時指定" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "s = pd.Series(range(5), index=list('abcde'))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### index 也可以在創建完 Series 後指定" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s.index = list('fghij')\n", + "s" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 什麼是 reindex?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s.reindex(list('hijabcd'))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### DataFrame" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "data = np.random.randn(10, 4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df = pd.DataFrame(data)\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.columns = ['No1', 'No2', 'No3', 'No4']\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.index = pd.date_range('2016-01-01', periods=10)\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.ix['2016-01-06']" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.drop(datetime(2016, 1, 3), inplace=True)\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.index=range(9)\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.ix[1]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.drop(4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 使用 Pandas 作資料存取\n", + "\n", + "### 這一部分包括底下幾個重點:\n", + "\n", + "* read_csv() 的使用\n", + "* read_html() 的使用\n", + "* 如何抓取股市資訊?\n", + "\n", + "底下練習一下將 [台灣證券交易所 - 加權股價指數歷史資料](http://www.tse.com.tw/ch/trading/indices/MI_5MINS_HIST/MI_5MINS_HIST.php#) 的資料轉成 DataFrame。" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 使用 read_csv() 讀取資料\n", + "\n", + "參考連結:[pandas.read_csv](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "df = pd.read_csv(\"data/MI_5MINS_HIST10603.csv\", encoding=\"Big5\", header=1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.drop(df.index[len(df.index)-1], inplace=True)\n", + "df" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 使用 read_html() 讀取資料\n", + "\n", + "參考連結:[pandas.read_html](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import requests\n", + "from bs4 import BeautifulSoup" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "r = requests.get(\"http://www.tse.com.tw/ch/trading/indices/MI_5MINS_HIST/MI_5MINS_HIST.php\")\n", + "r.encoding = 'Big5'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "soup = BeautifulSoup(r.text, \"lxml\")\n", + "tables = soup.select(\"table.board_trad\")\n", + "tables" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "type(tables[0])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "df_list = pd.read_html(str(tables[0]), header=1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df_list[0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 使用 Pandas 讀取股價資訊\n", + "\n", + "參考資料:[pandas-datareadre 說明文件](https://pandas-datareader.readthedocs.io/en/latest/)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import pandas_datareader.data as web\n", + "from datetime import datetime" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df = web.DataReader(\"TSLA\", 'yahoo', datetime(2016,1,1))\n", + "df['Close'].plot()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 資料視覺化\n", + "\n", + "Series 跟 DataFrame 都附帶有一個產生各類圖表的 plot(),預設的情況下,它會產生線形圖。\n", + "\n", + "參考資料:[Pandas Plotting](http://pandas.pydata.org/pandas-docs/stable/visualization.html)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s = pd.Series(np.random.randn(10), index=np.arange(10))\n", + "s.plot()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "s.plot(kind=\"bar\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))\n", + "df.plot()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.plot(kind='bar')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 資料分組與聚合" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "data = np.random.randn(10, 4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df = pd.DataFrame(data, columns=['No1', 'No2', 'No3', 'No4'])\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df['Category'] = np.NaN\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "clist = ['C1'] * 3 + ['C2'] * 5 + ['C3'] * 2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df['Category'] = np.random.permutation(clist)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "groups = df.groupby('Category')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "groups" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "groups.mean()" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python [conda root]", + "language": "python", + "name": "conda-root-py" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/02_numpy_matplotlib_pandas/data/MI_5MINS_HIST10603.csv b/02_numpy_matplotlib_pandas/data/MI_5MINS_HIST10603.csv new file mode 100644 index 0000000..6123f19 --- /dev/null +++ b/02_numpy_matplotlib_pandas/data/MI_5MINS_HIST10603.csv @@ -0,0 +1,21 @@ +"106 ~03 oq[vѻƾv" +"","}L","̰","̧C","L" +" 106/03/01"," 9,751.12"," 9,758.78"," 9,674.78"," 9,674.78" +" 106/03/02"," 9,727.60"," 9,774.60"," 9,646.34"," 9,691.80" +" 106/03/03"," 9,672.26"," 9,679.82"," 9,633.88"," 9,648.21" +" 106/03/06"," 9,647.00"," 9,688.50"," 9,647.00"," 9,682.63" +" 106/03/07"," 9,690.26"," 9,738.07"," 9,690.20"," 9,738.07" +" 106/03/08"," 9,744.26"," 9,773.49"," 9,712.50"," 9,753.45" +" 106/03/09"," 9,740.05"," 9,743.78"," 9,650.32"," 9,658.61" +" 106/03/10"," 9,653.79"," 9,656.65"," 9,562.75"," 9,627.89" +" 106/03/13"," 9,656.56"," 9,697.34"," 9,656.56"," 9,697.34" +" 106/03/14"," 9,720.53"," 9,767.66"," 9,720.53"," 9,744.21" +" 106/03/15"," 9,741.29"," 9,749.01"," 9,714.58"," 9,740.31" +" 106/03/16"," 9,768.85"," 9,842.17"," 9,768.85"," 9,837.83" +" 106/03/17"," 9,845.59"," 9,908.69"," 9,835.51"," 9,908.69" +" 106/03/20"," 9,905.81"," 9,916.18"," 9,869.35"," 9,912.97" +" 106/03/21"," 9,923.18"," 9,976.61"," 9,918.39"," 9,972.49" +" 106/03/22"," 9,911.96"," 9,922.66"," 9,843.07"," 9,922.66" +" 106/03/23"," 9,921.97"," 9,945.24"," 9,897.45"," 9,930.74" +" 106/03/24"," 9,914.12"," 9,932.68"," 9,892.31"," 9,902.98" +"" \ No newline at end of file diff --git a/02_numpy_matplotlib_pandas/images/artists_figure.png b/02_numpy_matplotlib_pandas/images/artists_figure.png new file mode 100644 index 0000000..c4a2c1c Binary files /dev/null and b/02_numpy_matplotlib_pandas/images/artists_figure.png differ diff --git a/02_numpy_matplotlib_pandas/images/artists_tree.png b/02_numpy_matplotlib_pandas/images/artists_tree.png new file mode 100644 index 0000000..56a23c1 Binary files /dev/null and b/02_numpy_matplotlib_pandas/images/artists_tree.png differ diff --git a/02_numpy_matplotlib_pandas/images/od1.png b/02_numpy_matplotlib_pandas/images/od1.png new file mode 100644 index 0000000..f7c3b7d Binary files /dev/null and b/02_numpy_matplotlib_pandas/images/od1.png differ diff --git a/02_numpy_matplotlib_pandas/images/three_layers.png b/02_numpy_matplotlib_pandas/images/three_layers.png new file mode 100644 index 0000000..d126810 Binary files /dev/null and b/02_numpy_matplotlib_pandas/images/three_layers.png differ diff --git "a/Notebooks/\345\235\207\345\200\274\344\272\244\345\217\211.ipynb" "b/Notebooks/\345\235\207\345\200\274\344\272\244\345\217\211.ipynb" index eadef3a..357374a 100644 --- "a/Notebooks/\345\235\207\345\200\274\344\272\244\345\217\211.ipynb" +++ "b/Notebooks/\345\235\207\345\200\274\344\272\244\345\217\211.ipynb" @@ -15,7 +15,7 @@ }, "outputs": [], "source": [ - "%pylab inline\n", + "%matplotlib inline\n", "\n", "# Pandas v0.16 之前,使用下面這個\n", "# import pandas.io.data as web\n", @@ -39,7 +39,7 @@ "outputs": [], "source": [ "# 讀取從 1970/1/1 之後的股價資訊\n", - "df=web.DataReader(\"FSLR\", 'yahoo', datetime(2012,1,1))" + "df=web.DataReader(\"TSLA\", 'yahoo', datetime(2016,8,1))" ] }, { @@ -51,8 +51,8 @@ "outputs": [], "source": [ "# 計算均線\n", - "df['20d'] = np.round(pd.rolling_mean(df['Close'], window=20), 2)\n", - "df['60d'] = np.round(pd.rolling_mean(df['Close'], window=60), 2)\n", + "df['20d'] = np.round(pd.Series.rolling(df['Close'], window=20).mean(), 2)\n", + "df['60d'] = np.round(pd.Series.rolling(df['Close'], window=60).mean(), 2)\n", "\n", "# 判斷均線向上或向下\n", "df['20d_diff'] = np.round(df['20d'].diff(), 2)\n", @@ -70,6 +70,19 @@ "df[['Close','20d','60d']].plot(grid=True, figsize=(10,8))" ] }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Donchian Channel\n", + "df['20d_high'] = np.round(pd.Series.rolling(df['Close'], window=20).max(), 2)\n", + "df['10d_low'] = np.round(pd.Series.rolling(df['Close'], window=10).min(), 2)" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -95,12 +108,49 @@ "outputs": [], "source": [ "# 第一個策略\n", - "#df['signal'] = np.where(df['20d']-df['60d'] > 0, 1.0, 0.0)\n", + "df['positions'] = np.where(df['20d']-df['60d'] > 0, 1.0, 0.0)\n", "\n", + "df['signals'] = df['positions'].diff()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ "# 第二個策略\n", - "df['signal'] = np.where(np.logical_and(df['20d']-df['60d'] > 0, df['20d_diff'] > 0), 1.0, 0.0)\n", + "df['positions'] = np.where(np.logical_and(df['20d']-df['60d'] > 0, df['20d_diff'] > 0), 1.0, 0.0)\n", "\n", - "df['positions'] = df['signal'].diff()" + "df['signals'] = df['positions'].diff()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# 第三個策略\n", + "has_position = False\n", + "df['signals'] = zeros(size(df['Close']))\n", + "for t in range(2, df['signals'].size):\n", + " if df['Close'][t] > df['20d_high'][t-1]:\n", + " if not has_position:\n", + " #df['signals'][t] = 1 # 這樣指定會有警告訊息\n", + " df.loc[df.index[t], 'signals'] = 1.0\n", + " has_position = True\n", + " elif df['Close'][t] < df['10d_low'][t-1]:\n", + " if has_position:\n", + " #df['signals'][t] = -1\n", + " df.loc[df.index[t], 'signals'] = -1.0\n", + " has_position = False\n", + "\n", + "df['positions'] = df['signals'].cumsum()" ] }, { @@ -118,15 +168,15 @@ "# Plot the AAPL closing price overlaid with the moving averages\n", "df['Close'].plot(ax=ax1, color='gray', lw=1., figsize=(10,8))\n", "df[['20d', '60d']].plot(ax=ax1, lw=2., grid=True)\n", + "df[['20d_high', '10d_low']].plot(ax=ax1, lw=2., grid=True)\n", "\n", "# Plot the \"buy\" trades against AAPL\n", - "ax1.plot(df.ix[df.positions == 1.0].index,df['20d'][df.positions == 1.0],'^', markersize=10, color='r')\n", + "#ax1.plot(df.ix[df.signals == 1.0].index,df['20d'][df.signals == 1.0],'^', markersize=10, color='r')\n", + "ax1.plot(df.ix[df.signals == 1.0].index,df['Close'][df.signals == 1.0],'^', markersize=10, color='r')\n", "\n", "# Plot the \"sell\" trades against AAPL\n", - "ax1.plot(df.ix[df.positions == -1.0].index, df['20d'][df.positions == -1.0], 'v', markersize=10, color='k')\n", - "\n", - "# 如果不是在 IPython Notebook 則需要下面這一行來顯示圖形\n", - "#fig.show()" + "#ax1.plot(df.ix[df.signals == -1.0].index, df['20d'][df.signals == -1.0], 'v', markersize=10, color='k')\n", + "ax1.plot(df.ix[df.signals == -1.0].index, df['Close'][df.signals == -1.0], 'v', markersize=10, color='k')" ] }, { @@ -151,13 +201,13 @@ "cell_type": "code", "execution_count": null, "metadata": { - "collapsed": true + "collapsed": false }, "outputs": [], "source": [ "#假設無風險利率為 4%\n", "#假設一年有252個交易日\n", - "excessRet = (dailyRet - 0.04/252)[df['signal']==1]\n", + "excessRet = (dailyRet - 0.04/252)[df['positions']==1.0]\n", "\n", "sharpeRatio = sqrt(252.0)*mean(excessRet)/std(excessRet)" ] @@ -202,11 +252,11 @@ " drawdownduration[t] = 0\n", " else:\n", " # 從日期來計算 MaxDDD 的天數\n", - " # drawdownduration[t] = drawdownduration[t-1] + (cumRet.index[t]-cumRet.index[t-1]).days\n", - " drawdownduration[t] = drawdownduration[t-1] + 1\n", + " drawdownduration[t] = drawdownduration[t-1] + (cumRet.index[t]-cumRet.index[t-1]).days\n", + " #drawdownduration[t] = drawdownduration[t-1] + 1\n", " maxDD = max(drawdown)\n", " maxDDD = max(drawdownduration)\n", - " Series(drawdownduration).plot()\n", + " Series(drawdownduration, index=cumRet.index).plot()\n", " return maxDD, maxDDD" ] }, diff --git "a/Notebooks/\345\246\202\344\275\225\345\276\236\347\266\262\350\267\257\350\256\200\345\217\226\350\202\241\345\203\271\350\263\207\346\226\231\344\270\246\347\271\252\350\243\275\345\234\226\345\275\242.ipynb" "b/Notebooks/\345\246\202\344\275\225\345\276\236\347\266\262\350\267\257\350\256\200\345\217\226\350\202\241\345\203\271\350\263\207\346\226\231\344\270\246\347\271\252\350\243\275\345\234\226\345\275\242.ipynb" index 7cb2772..476e6da 100644 --- "a/Notebooks/\345\246\202\344\275\225\345\276\236\347\266\262\350\267\257\350\256\200\345\217\226\350\202\241\345\203\271\350\263\207\346\226\231\344\270\246\347\271\252\350\243\275\345\234\226\345\275\242.ipynb" +++ "b/Notebooks/\345\246\202\344\275\225\345\276\236\347\266\262\350\267\257\350\256\200\345\217\226\350\202\241\345\203\271\350\263\207\346\226\231\344\270\246\347\271\252\350\243\275\345\234\226\345\275\242.ipynb" @@ -218,6 +218,7 @@ } ], "metadata": { + "anaconda-cloud": {}, "kernelspec": { "display_name": "Python [conda root]", "language": "python",