<style>
.w {
color: #FFFFFF;
font-size: 1px;
left=100px;
}
h2{
color:#000080;
}
</style>
<font color="#000080">Python 第五週講義</font>
===
>[name= 林德恩、陳睿倬][time= Dec 3,2021 ]
###### tags:`python` `tcirc39th` `社課` `臺中一中電研社`
[TOC]
---
## <span class="blue">電研社</span>
社網:[tcirc.tw](https://tcirc.tw)
online judge:[judge.tcirc.tw](https://judge.tcirc.tw)
IG:[TCIRC_39th](https://www.instagram.com/tcirc_39th)
---
## 安裝python模組
在**shell**裡輸入
```
pip install 模組名稱
```
---
## NumPy
[官網的功能說明](https://numpy.org/doc/stable/reference/)
----
### 複習一下
----
##### 建立陣列
```python=
import numpy as np
arr = np.array([4, 6,7, 7])
print(arr)
print("==================")
#二維陣列
arr2 = np.array([[1, 4, 6, 7], [4, 5, 3, 1]])
print(arr2)
#直接設定陣列維度
arr7 = np.array([1, 4, 6, 7], ndmin = 7)
print("-----------------")
print(arr7)
print("arr7 維度: ", arr7.ndim)
```
----
**output**
```
[4 6 7 7]
==================
[[1 4 6 7]
[4 5 3 1]]
-----------------
[[[[[[[1 4 6 7]]]]]]]
arr7 維度: 7
```
----
**拜訪元素**
```python=
import numpy as np
arr = np.array([4, 6,7, 7])
print(arr)
#拜訪元素
print(arr[3])
print("==================")
#二維陣列
arr2 = np.array([[1, 4, 6, 7], [4, 5, 3, 1], [80, 83, 6, 7]])
print(arr2)
#拜訪元素
print(arr2[0, 2])
```
----
**output**
```
[4 6 7 7]
7
==================
[[ 1 4 6 7]
[ 4 5 3 1]
[80 83 6 7]]
6
```
----
### 陣列運算
注意,要相加的兩矩陣比需是維度相同,元素可一一對應
```python=
a = np.array([1, 5, 6, 2, 7])
b = np.array([4, 6, 2, 7, 4])
print(a)
print(b)
print("===========")
# 陣列運算
c = a+b
print(c)
c = a*b
print(c)
```
----
**output**
```
[1 5 6 2 7]
[4 6 2 7 4]
===========
[ 5 11 8 9 11]
[ 4 30 12 14 28]
```
----
矩陣相加
```python=
a2 = np.array([ [2, 4, 3, 2], [53, 223, 236, 256]])
b2 = np.array([ [45, 54 ,1,6], [14, 26, 2, 12]])
c2 = a2+b2
print(c2)
```
**output**
```
[[ 47 58 4 8]
[ 67 249 238 268]]
```
----
### 其餘功能
```python=
import numpy as np
arr = np.array([[[23, 24, 24, 82],
[423, 254, 142, 213]],
[[0, 142, 22, 34],
[54, 25, 456, 247]],
[[0 ,12 ,25, 32],
[42, 25, 63, 87]]])
print(arr)
print("=============")
#陣列維度
print(arr.ndim)
#陣列元素個數
print(arr.size)
#顯示陣列個維度個數
print(arr.shape)
```
----
**output**
```
[[[ 23 24 24 82]
[423 254 142 213]]
[[ 0 142 22 34]
[ 54 25 456 247]]
[[ 0 12 25 32]
[ 42 25 63 87]]]
=============
3
24
(3, 2, 4)
```
----
#### .unique()
這功能可刪掉重複的元素,使資料量減少
```python=
import numpy as np
a = np.array([1,1,1,1,2,2,2,4,5,2,1,2,2,1,5,4,4,7,8,3,6,9,4,7])
print(np.unique(a))
```
**output**
```
[1 2 3 4 5 6 7 8 9]
```
----
#### .concatenate()
可將兩個陣列合併成一個陣列
```python=
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
c = np.concatenate((a, b))
print(c)
```
**output**
```
[1 2 3 4 5 6 7 8]
```
----
#### .union1d (聯集)
.union1d(陣列1,陣列2)
取聯集(取出兩陣列的所有元素,但不會有重複的)
```python=
import numpy as np
a = np.array([4, 6, 2, 1, 7, 8])
b = np.array([3, 6, 7, 8])
print(np.union1d(a, b))
```
**output**
```
[1 2 3 4 6 7 8]
```
----
#### .intersect1d (交集)
.intersect1d(陣列1,陣列2)
取交集(取兩陣列重複的值)
```python=
import numpy as np
a = np.array([4, 6, 2, 1, 7, 8])
b = np.array([3, 6, 7, 8])
print(np.intersect1d(a, b))
```
**output**
```
[6 7 8]
```
----
#### .setdiff1d (差集)
.setdiff1d(陣列1,陣列2)
取差集(顯示兩個陣列中不同的元素)
```python=
import numpy as np
a = np.array([4, 6, 2, 1, 7, 8])
b = np.array([3, 6, 7, 8])
print(np.setdiff1d(a, b))
```
**output**
```
[1 2 4]
```
----
#### .random
NumPy也有random功能基本上和random函式差不多
.random.seed(x):參考[第三周講義](https://hackmd.io/o4go8rJQTTyDwOr99VelmA?view#randomseeda--None)
.random.randint(最小值,最大值,數量):參考[第三周講義](https://hackmd.io/o4go8rJQTTyDwOr99VelmA?view#randomrandinta-b)
.random.rand(數量):參考[第三周講義](https://hackmd.io/o4go8rJQTTyDwOr99VelmA?view#randomrandom)
.random.choice(容器):參考[第三周講義](https://hackmd.io/o4go8rJQTTyDwOr99VelmA?view#randomchoice%E5%AE%B9%E5%99%A8)
----
#### .abs(數值 或 陣列)
輸出進行絕對值運算後的陣列或數值
#### .sqrt(數值 或 陣列)
輸出進行開二次方根後的陣列或數值
```python=
import numpy as np
print(np.sqrt(4))
print(np.abs(-3))
```
**output**
```
2.0
3
```
---
## matplotlib
*初階*
本次只會講一些較淺的功能,有興趣的話可以自己去查更多功能
[matplotlib官網函式庫](https://matplotlib.org/stable/api/pyplot_summary.html)
----
### import
套件名稱:matplotlib
模組名稱:pyplot
```python=
import matplotlib.pyplot
```
----
### 使用
#### 折線圖(Line Plots)
.plot(x)
```python=
import matplotlib.pyplot as plt
data=[4,0,8,3]
plt.plot(data)
plt.show()
```
----
**output**
![](https://i.imgur.com/zNTsv1M.png)
----
#### 更改線條外觀
**顏色:**
* b:<span style="color:blue">藍色</span>
* g:<span style="color:green">綠色</span>
* r:<span style="color:red">紅色</span>
* c:<span style="color:cyan">青色</span>
* m:<span style="color:magenta">洋紅色</span>
* y:<span style="color:yellow">黃色</span>
* k:<span style="color:black">黑色</span>
* w:<span style="color:white;background-color:black">白色</span>
----
**線條:**
* <span style="font-size:30px">\- </span> :實線
* <span style="font-size:30px">\-\- </span>:虛線
* <span style="font-size:30px">.</span>:點組成的虛線
* <span style="font-size:30px">-.</span>: ·和-組成的虛線
----
**標記符號:**
* <span style="font-size:20px">.</span> :點
* <span style="font-size:20px">,</span> :無
* <span style="font-size:20px">o</span> :圓形
* <span style="font-size:20px">s</span> :方形
* <span style="font-size:20px">^</span> :三角形
----
**使用:**
在資料後面用逗點分開,再用雙引號("")括起來,順序是顏色-線條-標記符號
※可以只寫想要改的或不寫,預設是:點(b)、線(-)、標記符號(,)
```python=
import matplotlib.pyplot as plt
data=[4,0,8,3]
plt.plot(data,"c-.^")
plt.show()
```
----
**output**
![](https://i.imgur.com/WkJpRlX.png)
----
#### 圖例
.legend(loc=位置值)
使用前畫的線要先給標籤(label="標籤名稱")
※可不寫loc=位置值,預設為右上
----
* 'best' / 0
* 'upper right' / 1
* 'upper left' / 2
* 'lower left' / 3
* 'lower right' / 4
* 'right' / 5
* 'center left' / 6
* 'center right' / 7
* 'lower center' / 8
* 'upper center' / 9
* 'center' / 10
----
![](https://i.imgur.com/TGVAiVt.png)
----
程式
```python=
import matplotlib.pyplot as plt
data=[4,0,8,3]
d=[1,3,2,4]
plt.plot(data,"y-.^",label='a')
plt.plot(d,"k-s",label='b')
plt.legend()
plt.show()
```
----
**output**
![](https://i.imgur.com/2ZWHc4J.png)
----
#### 和NumPy並用
ex.畫sin曲線
```python=
import matplotlib.pyplot as plt
import numpy as np
import math
x=np.linspace(0,2*math.pi) # 建立一個等差數列 linspace(start, end)
y=np.sin(x) # 計算sin值, 可迭帶容器
plt.plot(x,y)
plt.show()
```
----
**output**
![](https://i.imgur.com/rROxlEt.png)
----
#### 長條圖(bar chart)
.bar(x,y)
```python=
import matplotlib.pyplot as plt
data=[4,0,8,3]
n=[0,1,2,3]
plt.bar(n,data) # bar(x, y)
plt.show()
```
----
**output**
![](https://i.imgur.com/mClp8HZ.png)
----
#### 散怖圖(scatter chart)
.scatter(x,y)
```python=
import matplotlib.pyplot as plt
data=[4,0,8,3]
n=[0,1,2,3]
plt.scatter(n,data)
plt.show()
```
----
output
![](https://i.imgur.com/l3tCOF5.png)
----
#### 直方圖
*部份用法*
.hist(x,bins=組距數量)
組距數量可以設為'auto',代表自動決定
```python=
import matplotlib.pyplot as plt
data=[4,0,8,3,5,7,6,2,1,9,8,5]
plt.hist(data,bins='auto')
plt.show()
```
----
output
![](https://i.imgur.com/wwBVcfK.png)
----
#### 圓餅圖
.pie(x)
```python=
import matplotlib.pyplot as plt
data=[4,0,8,31,5,6,8,10]
plt.pie(data)
plt.show()
```
----
**output**
![](https://i.imgur.com/SHyXHO0.png)
----
#### 標題
.title(標題)
#### 座標標籤
x軸:xlabel()
y軸:ylabel()
程式
```python=
import matplotlib.pyplot as plt
ki=[0,1,0,1,6]
ri=[4,8,7,6,3]
plt.plot(ki,ri,"k-.^")
plt.title('Sword Art Onlie')
plt.xlabel("starburst")
plt.ylabel("stream")
plt.show()
```
----
**output**
![](https://i.imgur.com/C73KGd8.png)
<!--
#### 3D(3.2.0後可不用另外import)
畫布=pyplot.figure()
-->
----
#### 軸的範圍
x軸:.xlim(最小值,最大值)
y軸:.ylim(最小值,最大值)
#### 軸的刻度
x軸:.xticks(刻度)
y軸:.yticks(刻度)
※刻度可以用range函式或list
----
**程式**
```python=
import matplotlib.pyplot as plt
data=[1,3,4,7,2]
x=[2,3.4,4]
plt.plot(data)
plt.xlim(2,4)
plt.ylim(2,8)
plt.xticks(x)
plt.yticks(range(2,8,2))
plt.show()
```
----
**output**
![](https://i.imgur.com/kytZLTm.png)
----
#### 儲存圖表
.savefig("檔案名稱.副檔名")
※檔案存為圖檔格式(.jpg/.png/.pdf/...)
※會存到與目前.py檔同一資料夾
※要寫在show之前,不然會全白
```python=
import matplotlib.pyplot as plt
Rick=range(31)
Astley=[0,5,6,8,6,10,10,9,0,5,6,8,6,9,9,8,7,6,0,5,6,8,6,8,9,7,6,5,5,9,8]
plt.plot(Rick,Astley,"r-o")
plt.title('Never gonna give you up')
plt.xlabel("Never gonna let you down")
plt.ylabel("Never gonna run around and desert you")
plt.yticks(range(14))
plt.savefig("rickroll.jpg")
plt.show()
```
----
**output**
![](https://i.imgur.com/hYJiYHT.jpg)
---
## pandas(python and analysis panel data)
*基礎*
pandas是一個主要用來畫表格的模組,也可以畫圖表
[pandas官網函式庫](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html)
模組:pandas
```python=
import pandas
```
----
### 建立series物件
透過.Series(數據,index=標籤)可製作成一表格
※index可不寫,會以0,1,2,3,4...作為標籤
```python=
import pandas as pd
data=[1,2,3,4,5,6,7,8,9]
idx=['a','b','c','d','e','f','g','h','i']
s=pd.Series(data,index=idx)
print(s)
print("======================")
print(s["c"]) # 用自訂索引訪問元素
e=pd.Series(data)
print("======================")
print(e)
```
----
output:
```
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
dtype: int64
======================
3
======================
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
dtype: int64
```
----
#### 相加
如果是同類別的會相加,少或不同會NaN
```python=
import pandas as pd
data=[1,2,3,4,5,6,7,8,9]
idx=['a','b','c','d','e','f','g','h',1]
data1=range(3,12)
s=pd.Series(data,index=idx)
e=pd.Series(data1,index=idx)
r=pd.Series([1,2,3],['a','b','c'])
print(s+e)
print("======================")
print(s+r)
```
----
**output**
```
a 4
b 6
c 8
d 10
e 12
f 14
g 16
h 18
1 20
dtype: int64
======================
1 NaN
a 2.0
b 4.0
c 6.0
d NaN
e NaN
f NaN
g NaN
h NaN
dtype: float64
```
----
#### 四則運算
```python=
import pandas as pd
data=[1,2,3,4,5,6,7,8,9]
idx=['a','b','c','d','e','f','g','h','i']
data1=range(3,12)
s=pd.Series(data,index=idx)
print((s*4+1)/4)
```
----
**output**
```
a 1.25
b 2.25
c 3.25
d 4.25
e 5.25
f 6.25
g 7.25
h 8.25
i 9.25
```
----
### DataFrame
.DataFrame(資料,index=標籤)可製作成一表格
※index可不寫,會以0,1,2,3,4...作為標籤
```python=
import pandas as pd
baha={
"GNN新聞":["手機","PC","TV 掌機","動漫畫","電玩瘋","電競","活動展覽","主題報導",None,None,None,None,None,None,None,None,None,None,None],
"哈啦區":["手機","PC","TV 掌機","動漫畫","主題","場外","站務","我的",None,None,None,None,None,None,None,None,None,None,None],
"動畫瘋":["奇幻冒險","科幻未來","青春校園","幽默搞笑","戀愛" ,"溫馨","靈異神怪","推理懸疑","料理美食","社會寫實","運動競技","歷史傳記","闔家觀賞","雙語","其他","OVA","電影版","付費會員","年齡限制"]
}
lis=["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19"]
df = pd.DataFrame(baha,index=lis)
print(df)
```
----
**output**
```
GNN新聞 哈啦區 動畫瘋
01 手機 手機 奇幻冒險
02 PC PC 科幻未來
03 TV 掌機 TV 掌機 青春校園
04 動漫畫 動漫畫 幽默搞笑
05 電玩瘋 主題 戀愛
06 電競 場外 溫馨
07 活動展覽 站務 靈異神怪
08 主題報導 我的 推理懸疑
09 None None 料理美食
10 None None 社會寫實
11 None None 運動競技
12 None None 歷史傳記
13 None None 闔家觀賞
14 None None 雙語
15 None None 其他
16 None None OVA
17 None None 電影版
18 None None 付費會員
19 None None 年齡限制
```
----
#### 轉向
表格物件.T
```python=
import pandas as pd
baha={
"GNN新聞":["手機","PC","TV 掌機","動漫畫","電玩瘋","電競","活動展覽","主題報導",None,None,None,None,None,None,None,None,None,None,None],
"哈啦區":["手機","PC","TV 掌機","動漫畫","主題","場外","站務","我的",None,None,None,None,None,None,None,None,None,None,None],
"動畫瘋":["奇幻冒險","科幻未來","青春校園","幽默搞笑","戀愛" ,"溫馨","靈異神怪","推理懸疑","料理美食","社會寫實","運動競技","歷史傳記","闔家觀賞","雙語","其他","OVA","電影版","付費會員","年齡限制"]
}
lis=["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19"]
df = pd.DataFrame(baha,,columns=["哈啦區","動畫瘋","GNN新聞"],index=lis)
print(df.T)
```
----
**output**
```
01 02 03 04 05 06 ... 14 15 16 17 18 19
GNN新聞 手機 PC TV 掌機 動漫畫 電玩瘋 電競 ... None None None None None None
哈啦區 手機 PC TV 掌機 動漫畫 主題 場外 ... None None None None None None
動畫瘋 奇幻冒險 科幻未來 青春校園 幽默搞笑 戀愛 溫馨 ... 雙語 其他 OVA 電影版 付費會員 年齡限制
[3 rows x 19 columns]
```
----
#### 表格輸出
會存到和程式同一資料夾
* HTML:表格變數.to_html("檔名.html")
* CSV:表格變數.to_csv("檔名.csv")
* JSON:表格變數.to_json("檔名.json")
* Excel:表格變數.to_excel("檔名.xls")
----
```python=
import pandas as pd
baha={
"GNN新聞":["手機","PC","TV 掌機","動漫畫","電玩瘋","電競","活動展覽","主題報導",None,None,None,None,None,None,None,None,None,None,None],
"哈啦區":["手機","PC","TV 掌機","動漫畫","主題","場外","站務","我的",None,None,None,None,None,None,None,None,None,None,None],
"動畫瘋":["奇幻冒險","科幻未來","青春校園","幽默搞笑","戀愛" ,"溫馨","靈異神怪","推理懸疑","料理美食","社會寫實","運動競技","歷史傳記","闔家觀賞","雙語","其他","OVA","電影版","付費會員","年齡限制"]
}
lis=["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19"]
df = pd.DataFrame(baha,index=lis)
df.T.to_html("gamer.html")
print(df)
```
----
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>01</th>
<th>02</th>
<th>03</th>
<th>04</th>
<th>05</th>
<th>06</th>
<th>07</th>
<th>08</th>
<th>09</th>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
</tr>
</thead>
<tbody>
<tr>
<th>GNN新聞</th>
<td>手機</td>
<td>PC</td>
<td>TV 掌機</td>
<td>動漫畫</td>
<td>電玩瘋</td>
<td>電競</td>
<td>活動展覽</td>
<td>主題報導</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
</tr>
<tr>
<th>哈啦區</th>
<td>手機</td>
<td>PC</td>
<td>TV 掌機</td>
<td>動漫畫</td>
<td>主題</td>
<td>場外</td>
<td>站務</td>
<td>我的</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
</tr>
<tr>
<th>動畫瘋</th>
<td>奇幻冒險</td>
<td>科幻未來</td>
<td>青春校園</td>
<td>幽默搞笑</td>
<td>戀愛</td>
<td>溫馨</td>
<td>靈異神怪</td>
<td>推理懸疑</td>
<td>料理美食</td>
<td>社會寫實</td>
<td>運動競技</td>
<td>歷史傳記</td>
<td>闔家觀賞</td>
<td>雙語</td>
<td>其他</td>
<td>OVA</td>
<td>電影版</td>
<td>付費會員</td>
<td>年齡限制</td>
</tr>
</tbody>
</table>
----
```htmlmixed=
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>01</th>
<th>02</th>
<th>03</th>
<th>04</th>
<th>05</th>
<th>06</th>
<th>07</th>
<th>08</th>
<th>09</th>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
</tr>
</thead>
<tbody>
<tr>
<th>GNN新聞</th>
<td>手機</td>
<td>PC</td>
<td>TV 掌機</td>
<td>動漫畫</td>
<td>電玩瘋</td>
<td>電競</td>
<td>活動展覽</td>
<td>主題報導</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
</tr>
<tr>
<th>哈啦區</th>
<td>手機</td>
<td>PC</td>
<td>TV 掌機</td>
<td>動漫畫</td>
<td>主題</td>
<td>場外</td>
<td>站務</td>
<td>我的</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>None</td>
</tr>
<tr>
<th>動畫瘋</th>
<td>奇幻冒險</td>
<td>科幻未來</td>
<td>青春校園</td>
<td>幽默搞笑</td>
<td>戀愛</td>
<td>溫馨</td>
<td>靈異神怪</td>
<td>推理懸疑</td>
<td>料理美食</td>
<td>社會寫實</td>
<td>運動競技</td>
<td>歷史傳記</td>
<td>闔家觀賞</td>
<td>雙語</td>
<td>其他</td>
<td>OVA</td>
<td>電影版</td>
<td>付費會員</td>
<td>年齡限制</td>
</tr>
</tbody>
</table>
```
---
{%hackmd TCEJNjgqSReJ48GO2Fqlrg %}
{"metaMigratedAt":"2023-06-16T15:19:45.787Z","metaMigratedFrom":"YAML","title":"Python第五週講義 臺中一中電研社","breaks":true,"slideOptions":"{\"theme\":\"sky\",\"transition\":\"convex\"}","contributors":"[{\"id\":\"bd47cc0a-d3e4-4997-b042-3ae3230b8982\",\"add\":23055,\"del\":9267},{\"id\":\"6a5475c5-bfd3-428c-9219-c760b9000deb\",\"add\":35,\"del\":36},{\"id\":\"39148de1-346d-4e2e-81c6-55b8161c633e\",\"add\":3297,\"del\":565}]"}