Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python 補充 Python基本使用 p2-18 CSV檔案存取應用 p19-27 矩陣輸出入 p28-36(csv+numpy)

Similar presentations


Presentation on theme: "Python 補充 Python基本使用 p2-18 CSV檔案存取應用 p19-27 矩陣輸出入 p28-36(csv+numpy)"— Presentation transcript:

1 Python 補充 Python基本使用 p2-18 CSV檔案存取應用 p19-27 矩陣輸出入 p28-36(csv+numpy)
(pandas+numpy+matplotlib) 4 2 3 1 矩陣輸出入 p28-36(csv+numpy)

2 Python簡介 Python是1989年的聖誕節前後,由荷蘭的程式設計師Guido van Rossum所開發的。Python名稱是來自於BBC 的show: “Monty Python’s Flying Circus” Python的程式碼易讀、開放、跨平台、眾多的函數可運用,國外很多大學都把Python當作第一個程式語言來學習。 Python應用範圍很廣,從兒童程式教學、網站功能測試、大數據分析、物聯網、機器學習等,非常廣泛。例如Google 、Dropbox、NASA等單位,都將其當作主力的程式語言。

3 下載Python http://www.python.org

4 Python3.6

5 Windows x86-64 executable installer

6 左邊的IDLE 整合式開發學習環境介面比右邊的互動式介面方便使用

7 Python語法說明 >>>字號為輸入指令的提示符號 # 字號之後為註解,程式不會執行,多行註解則以’’’單引號前後框住
不必宣告變數型態,變數或函數名稱可以是英數字加底線,第一個字必須是英文,有大小寫的差異 行尾的冒號(:)表示縮排,開始使用4個空白鍵(或一個tab鍵)做為縮排,用來劃分程式的執行區塊 一行指令太長可用接續符號\ 拆成兩行

8 算術、比較、邏輯運算子 + 加、 - 減、 * 乘、 / 除 ** 次方 // 整除 % 餘數 | 或運算子OR ^ 互斥運算子XOR
& 且運算子AND > 、 >= 、< 、 <= 、 == 、!=

9 資料型別 整數 浮點數 字串 複數:5+J、5+2j 邏輯值:True、False 容器型別(Container Type) :
 Lists(串列)、 Tuples(序組)、 Set(集合)、 Dictionary(字典)

10 直接輸入指令或複製至新增檔案

11 執行程式檔(.py)的指令 程式中不能使用_ ,而且必須用print指令來顯示

12 簡單的程式

13 變數型態和其可用的函數

14 string和一維 list型別

15 多維度list型別

16 dictionary、tuple和set型別

17 函數與呼叫在同個py檔案

18 函數與呼叫在不同py檔案

19 CSV檔案存取

20 #method 1 Reader:field number read (0 TO N)
import csv with open("d:\\stella\\python\\input1.txt","r") as rd: input1=csv.reader(rd,delimiter=' ') #default , next(input1) #skip header with open("d:\\stella\\python\\output1.txt","w") as wr: output1=csv.writer(wr) output1.writerow(["id","sex","bmi"]) for row in input1: print(row) bmi=float(row[2])/((float(row[1])/100) ** 2) output1.writerow([row[0],row[3],round(bmi,2)])

21 #method 2 DictReader: field names read
import csv with open("d:\\stella\\python\\input1.txt","r") as rd: input1=csv.DictReader(rd,delimiter=' ') #default , next(input1) #skip header with open("d:\\stella\\python\\output1.txt","w") as wr: output1=csv.writer(wr) output1.writerow(["id","sex","bmi"]) for row in input1: print(row) bmi=float(row['weight'])/((float(row['height']) /100) ** 2) output1.writerow([row[‘id’],row[‘sex’], round(bmi,2)])

22 編輯路徑變數以安裝第三方套組 為了在cmd執行python, 需加入此路徑: C:\Users\user\AppData\Local\Programs\Python\Python36 為了在cmd執行pip, 需加入此路徑 : C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts 在命令提示字元下安裝第三方套組 C:>pip install numpy (pip list 用來查詢已安裝的套組)

23 從控制台編輯路徑變數

24 安裝第三方套組>pip install numpy

25 CVS讀入整個檔案 #method 3 Reader: all file import csv #內建套組
import numpy as np #第三方套組 with open("d:\\stella\\python\\input1.txt","r") as rd: input1=csv.reader(rd,delimiter=' ') #default , fields=next(input1) #skip header X=[] for row in input1: X.append(row)

26 選取記錄和欄位(數字並不方便) X=np.array(X) print(fields) print(X) print(X[1])
print(X[range(2)]) print(X[[0,2]]) print(X[:,1]) print(X[:,range(2)]) print(X[:,[0,3]])

27 篩選執行結果

28 矩陣相加相乘(用和不用numpy)

29 不用numpy的矩陣相加 相乘 def matrixAdd(A, B): # 將矩陣C的二維串列的每個元素初始化為0 C = []
for i in range(len(A)): C.append([]) for j in range(len(A[0])): C[i].append(0) # 進行矩陣相加 for j in range(len(A[i])): C[i][j] = A[i][j] + B[i][j] return C

30 def matrixMul(A, B): # D[i][k]=A[i][j]xB[j][k] # i=len(A), j=len(A[0]) or len(B), k=len(B[0]) D = [] for i in range(len(A)): D.append([]) for j in range(len(B[0])): D[i].append(0) for k in range(len(B[0])): subtotal=0 for j in range(len(A[0])): subtotal = subtotal+A[i][j]*B[j][k] D[i][k] = subtotal return D

31 def printMatrix(matrix):
for i in range(len(matrix)): for j in range(len(matrix[0])): print(matrix[i][j], '\t',end=" ") print('\n') A=[[1,2,3],[4,5,6],[7,8,9]] B=[[1,1,1],[2,2,2],[3,3,3]] C = matrixAdd(A, B) printMatrix(C) D = matrixMul(A, B) printMatrix(D)

32 使用numpy的矩陣相加 相乘 import numpy as np
A=np.array([[1,2,3],[4,5,6],[7,8,9]]) B=np.array([[1,1,1],[2,2,2],[3,3,3]]) C=A+B # only elements-wise multiply D=A*B or D=np.multiply(A,B) # matrix multiply #E=np.matmul(A,B) or E=np.dot(A,B) print(E)

33 讀入整個矩陣 import csv import numpy as np
with open("d:\\stella\\python\\matrix.txt“ ,"r") as rd: reader=csv.reader(rd,delimiter=' ') X=[] for row in reader: X.append(row) X=np.array(X,dtype=int) print(X)

34 列印對角線 # diag line #列數 len(X) #行數 len(X[i]) for i in range(len(X)):
for j in range(len(X[i])): if (i==j): print(X[i][j])

35 矩陣相加後輸出 Y=np.array([[1,1,1],[2,2,2],[3,3,3]]) Z=X+Y
with open(“d:\\stella\\python\\matrixout.txt”, "w") as wr: writer=csv.writer(wr,delimiter='\t') for row in Z: writer.writerow(row)

36 矩陣輸入輸出執行結果 print(Z) print(Z[1]) print(Z[range(2)]) print(Z[[0,2]])

37 乳腺癌醫學診斷應用 本範例檔wdbc.txt的乳腺癌(Breast Cancer Diagnostic)的診斷資料,取自美國加州大學歐文分校的機械學習資料庫 Wisconsin大學臨床研究中心於1995年蒐集569例乳腺癌症的病患實際診斷資料,診斷的方式是對於可疑的乳腺腫塊使用細針穿刺的技術 (Fine Needle Aspirate, FNA)蒐集數位化圖像並加以計算

38 乳腺癌醫學診斷欄位說明 wdbc.txt的欄位計有32項,分別是 1. 識別號碼(ID number):識別號碼
2. 診斷結果(Diagnosis):惡性(M = malignant)、良性(B = benign) 3-32. 這30項資料是計算每一個細胞核的真實資料測量值,包含以下的內容:半徑(radius)、紋理(texture)周長(perimeter)、範圍(area)、平滑度(smoothness)、緊密度(compactness)、凹陷部分的程度(concavity)、凹陷部分的數量(concave points) 、對稱度(symmetry) 、碎型維度(fractal dimension)

39 wdbc (pandas+numpy)

40 import pandas as pd import numpy as np import matplotlib.pyplot as plt wdbc=pd.read_csv("d:\\stella\\R\\wdbc.txt") print(wdbc[:10]) print("mean of c7=",np.mean(wdbc['c7'])) print(wdbc[['id','diagnosis']][:10]) df2=wdbc[['id','diagnosis']][:10] df2.to_csv("d:\\stella\\python\\wdbc.txt") print(wdbc.describe()) print(wdbc[wdbc["diagnosis"] =='B'][:10])

41 鳶尾花分類應用 這個鳶尾花(Iris)資料集是非常著名的生物資訊資料集之一,取自美國加州大學歐文分校的機械學習資料庫, 資料的筆數計有150筆,共有五個欄位,這裡使用的iris_all.txt則只有10筆: 1. 花萼長度(Sepal Length):計算單位是公分。 2. 花萼寬度(Sepal Width):計算單位是公分。 3. 花瓣長度(Petal Length) :計算單位是公分。 4. 花瓣寬度(Petal Width):計算單位是公分。 5. 類別(Class):可分為Setosa,Versicolour和Virginica三個品種

42 iris(pandas+numpy+matplotlib)

43 直方圖

44 長條圖

45 圓餅圖

46 iris=pd.read_csv(“d:\\stella\\R\\iris_all.txt”, sep=" ")
print(iris) print(iris.describe()) print("Mean of Sepal Length=",np.mean(iris['Sepal.Length'])) print(iris[iris["Spec.Pred"] =='virginica']) x=iris['Sepal.Length'] y=iris['Petal.Length']

47 plt.plot(x,y,"ro") plt.show() plt.hist(z) items, counts = np.unique(iris["Spec.Pred"], return_counts=True) print(np.asarray((items, counts))) plt.bar(items, counts) plt.pie(counts,labels=items, autopct= "%.1f%%")


Download ppt "Python 補充 Python基本使用 p2-18 CSV檔案存取應用 p19-27 矩陣輸出入 p28-36(csv+numpy)"

Similar presentations


Ads by Google