owned this note
owned this note
Published
Linked with GitHub
---
type: slide
---
# Python基礎教學
### 蔡昕翰
---
# Python簡介
1. 簡單易學
2. 高生產力
3. 跨多領域
4. 高可讀性
5. 動態Typing
6. 直譯式
7. 跨平台
---
# 安裝conda
### 1. Miniconda
沒有太多預裝軟體,最小化安裝
### 2. Anaconda
預裝很多東西,對科學計算可以輕易使用
---
# 什麼是conda
1. free & open source
2. 管理不同環境
3. 解決環境衝突
---
# 安裝Miniconda
### 1. 從官網
https://docs.conda.io/projects/miniconda/en/latest/
### 2. 我的server (使用學校網路可以較快)
---
# conda 指令介紹
## 檢查python、conda版本
```bash
$ conda -V
conda 23.1.0
$ python -V
Python 3.10.6
```
---
## 查看conda環境
```bash
conda env list
```
---
## conda建立新環境
```bash
conda create -n <env_name> python=<python_ver>
```
例如
```bash
conda create -n py39 python=3.9
```
---
## 進入/退出conda虛擬環境
```bash
conda activate <env> # 進入環境
conda deactivate <env> # 退出環境
```
例如
```bash
$ python -V
'python' 不是內部或外部命令、可執行的程式或批次檔。
$ conda activate py39
(py39) $ python -V
Python 3.9.13
(py39) $ conda deactivate
$ python -V
'python' 不是內部或外部命令、可執行的程式或批次檔。
```
---
## python 互動模式
在終端機直接打python
```bash
$ conda activate py39
(py39) $ python
Python 3.9.13 (tags/v3.9.13:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello, world")
hello, world
>>> exit()
$
```
---
## python script
- 產品用程式(production project)通常會寫成script
- 需有IDE (vscode, PyCharm, vim, nano, 記事本...)
----
<br>
<div style="text-align: left"> 例: </div>
1. 建立檔案 test.py
2. 在test.py內輸入:
```python=
print("hello, world")
```
3. 在終端機輸入:
```bash
$ python test.py
hello, world
```
---
## jupyter notebook
- 教學用、特定用途、科學及統計運算
- 嫌醜可用其他外殼包(vscode notebook mode, dataspell, ...)
- 可遠端連線操作
---
## 安裝jupyter
```bash
(py39) $ pip install jupyter
```
查看版本:
```bash
(py39) $ jupyter --version
Selected Jupyter core packages...
IPython : 7.31.1
ipykernel : 6.19.2
ipywidgets : 7.6.5
jupyter_client : 7.3.4
jupyter_core : 5.1.1
jupyter_server : 1.23.4
jupyterlab : 3.5.2
nbclient : 0.5.13
nbconvert : 6.4.4
nbformat : 5.7.0
notebook : 6.5.2
qtconsole : 5.2.2
traitlets : 5.7.1
```
---
## 啟動jupyter notebook
```bash
(py39) $ jupyter notebook
```
---
## 在jupyter內建立新筆記本

---

---
自己改筆記本名字
---
# Python基礎語法
easyeee~
---
所有東西都是物件
---
變數、賦值
```python=
message = "Hello World"
print(message)
```
---
條件判斷
```python=
x = 5
if x > 0 :
print("x是正數")
```
---
函數定義
```python=
def sayHello(name):
print("Hello " + name)
sayHello("John")
```
---
for循環結構
```python=
for i in range(5):
print(i)
list1 = [1,2,3]
for item in list1:
print(item)
```
---
while 循環
```python=
i = 10
while i > 0:
print(i)
```
```python=
i = 10
f = False
while not f:
if i == 0:
f = True
print(i)
```
---
## python的型別
python的變數可以隨意改變型別
```python=
number = 1 # int
print(number)
number = "asdf" # str
print(number)
```
會印出
```python=
1
asdf
```
---
檢查型別
```python=
random_thing = 1.3
print(type(random_thing))
```
會印出
```
<class 'float'>
```
---
數據結構
```python=
myList = [1, 2, 3] # 列表 list
myTuple = (1, 2, 3) # 元組 tuple
myDict = {"name": "John", "age": 25} # 字典 dict
mySet = {1, 2, 3} # 集合 set
```
---
取值
```python=
myList = [1, 2, 3] # 列表 list
myTuple = (1, 2, 3) # 元組 tuple
myDict = {"name": "John", "age": 25} # 字典 dict
mySet = {1, 2, 3} # 集合 set
print(myList[0])
print(myTuple[1])
print(myDict["name"])
print(mySet[2])
```
---
## 轉換型別
只有同種的可以互換
```
ex:
list <--> tuple
str <--> list
int <--> float
```
```python=
a = "abcdefg"
print(list(a))
print(tuple( list(a) ))
b = 1
c = 2
print(float(b) + float(c))
```
---
## 笨電腦
```python=
print(0.1 + 0.2)
```
---
# 數據分析
---
## 什麼是numpy?
- Python的開源數值計算擴展程式庫
- 提供高效能的多維陣列與矩陣運算、數學函數等功能
- 機器學習和數據科學的基礎套件
---
## numpy安裝
```bash
pip install numpy
```
*使用我的伺服器*
```bash
pip install numpy --extra-index-url http://<my_ip> --trusted-host <my_ip>
```
---
## numpy使用
首先需要匯入numpy模組,通常用np代稱
```python
import numpy as np
```
---
## 建立ndarray
ndarray為numpy的多維陣列物件
```python
array = np.array([1, 2, 3])
matrix = np.array([[1, 2], [3, 4]])
```
---
## ndarray屬性
- ndarray.shape: 陣列維度
- ndarray.dtype: 陣列中的元素類型
```python
array.shape # (3,)
matrix.shape # (2, 2)
array.dtype # int64
```
---
## 新增維度
可以使用np.newaxis或None來新增維度
```python=
array_2d = array[np.newaxis, :] # [[1,2,3]]
array_3d = array[:, np.newaxis, np.newaxis] # [[[1]],[[2]],[[3]]]
```
---
## 陣列運算
向量化運算,適用於整個陣列
```python
matrix + 2
matrix * matrix # 元素對應相乘
```
---
## 常用函數
- `np.linspace`: 創建線段陣列
- `np.mean`: 計算均值
- `np.sum`: 總和
- `np.min/max`: 最小值和最大值
等等
---
# pandas基本用法
---
## 什麼是pandas
pandas是基於numpy的Python數據分析庫,提供:
- 高效的數據結構(Series、DataFrame)
- 數據讀取/寫入工具
- 數據清理與處理方法
- 合併/連接數據集功能
---
## 安裝pandas
```bash
pip install pandas
```
*使用我的伺服器*
```bash
pip install pandas --extra-index-url http://<my_ip> --trusted-host <my_ip>
```
---
## 使用pandas
引入數據庫,通常會使用pd代稱
```python
import pandas as pd
```
---
## Series
一維數據,可設置索引
```python
s = pd.Series([1,2,3], index=['a','b','c'])
```
---
## DataFrame
二維數據,類似表格/excel
```python
data = {'Name': ['John', 'Mary'], 'Age': [25, 27]}
df = pd.DataFrame(data)
```
---
## 讀取csv
```python
df = pd.read_csv('data.csv')
```
---
## 查看資料
- `df.head()`/`df.tail()`
- `df.shape`
- `df.dtypes`
- `df.index`/`df.columns`
- `df.values`
- `df.describe()` 統計訊息
---
## 數據選取
- `df[col]`: column
- `df.loc[index]`: 行
- `df.iloc[index]`: 位置
---
## 數據清理
- 刪除列: `del df[col]`
- 填補NaN: `df.fillna()`
- 去除重復的: `df.drop_duplicates()`
---
# OpenCV-Python (cv2) 基本用法
---
## 安裝OpenCV
使用pip裝:
```
pip install opencv-python
```
*使用我的伺服器*
```bash
pip install opencv-python --extra-index-url http://<my_ip> --trusted-host <my_ip>
```
---
## 什麼是OpenCV?
OpenCV是開源的電腦視覺庫,提供許多影像處理和電腦視覺相關的功能。
最新版本是4.x,Python繫結是cv2。
```python
import cv2
```
---
為何是cv2不是cv?
---
## 讀取圖像
```python
img = cv2.imread('image.jpg')
```
支援讀取JPG、PNG、TIFF等格式。
---
## 顯示圖像
```python
cv2.imshow('Image', img)
cv2.waitKey(0) # 按任意鍵繼續
```
---
## 寫入圖像
```python
cv2.imwrite('output.jpg', img)
```
---
## 圖像資訊
- `img.shape` - 形狀
- `img.size` - 大小
- `img.dtype` - 數據類型
---
## 圖像處理
- 色彩空間轉換:`cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)`
- 縮放:`cv2.resize(img, (width, height))`
- 裁剪:`img[y1:y2, x1:x2]`
- 模糊:`cv2.blur(img, (5, 5))`
---
# Matplotlib基本用法
---
安裝:
```bash
pip install matplotlib
```
*使用我的伺服器*
```bash
pip install matplotlib --extra-index-url http://<my_ip> --trusted-host <my_ip>
```
---
## 什麼是Matplotlib
Matplotlib是Python的2D繪圖庫,廣泛用於繪製論文的數據圖表。
```python
import matplotlib.pyplot as plt
```
---
## 繪製圖表
### 線圖
```python
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y)
```
### 柱狀圖
```python
x = ['A', 'B', 'C', 'D']
y = [10, 30, 40, 20]
plt.bar(x, y)
```
---
## imshow顯示圖片
```python
img = cv2.imread('image.jpg')
plt.imshow(img)
```
---
## 圖標題、軸標籤
```python
plt.title('Title')
plt.xlabel('X Label')
plt.ylabel('Y Label')
```
---
## 圖片範圍、刻度
```python
plt.xlim(0, 5)
plt.ylim(0, 10)
plt.xticks([0, 1, 2, 3, 4, 5])
plt.yticks([0, 2, 4, 6, 8, 10])
```
---
## 圖例、顯示
```python
plt.legend(['A', 'B'])
plt.show()
```
---
## 感謝
祝AI之路順遂