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

Slides:



Advertisements
Similar presentations
第一單元 建立java 程式.
Advertisements

Pygame 講者:張浩軒.
JAVA 程式設計 資訊管理系 - 網路組.
陳維魁 博士 儒林圖書公司 第九章 資料抽象化 陳維魁 博士 儒林圖書公司.
TQC+ JAVA全國教師研習會 PLWeb 程式設計練習平台 簡介.
程式語言的基礎 Input Output Program 世代 程式語言 第一世代 Machine language 第二世代
臺北市立大學 資訊科學系(含碩士班) 賴阿福
程式設計概論 1.1 程式設計概論 程式語言的演進 物件導向程式 程式開發流程 1.2 C++開發工具
Java簡介.
Visual C++ introduction
簡易C++除錯技巧 長庚大學機械系
C Shell Programming.
JDK 安裝教學 (for Win7) Soochow University
2 C++ 程式概論 2.1 C++ 程式結構 程式註解 // 插入標題檔 #include 2-3
Python程式設計入門
保留字與識別字.
Working with Databases (II) 靜宜大學資管系 楊子青
Java程式概觀.
C語言簡介 日期 : 2018/12/2.
生物資訊程式語言應用 Part 3 Perl Language.
類別(class) 類別class與物件object.
SQL Stored Procedure SQL 預存程序.
R教學 安裝RStudio 羅琪老師.
ASP.NET基本設計與操作 建國科技大學 資管系 饒瑞佶 2007年.
安裝JDK 安裝Eclipse Eclipse 中文化
Android App簡介及 App Inventor 2體驗 靜宜大學資管系 楊子青
雲端計算.
Java 程式設計 講師:FrankLin.
用Python建模与数据处理 俞熹 2017/1.
程式設計實習課(四) ----C 函數運用----
Python 基本介紹.
Java程式設計 Eclipse.
第一單元 建立java 程式.
App Inventor 2初體驗 靜宜大學資管系 楊子青
INDEX 資訊學科種子教師研習 課程說明 教學活動計畫.
第三章 資料型態與輸出控制 本章學習目標 認識Matlab的基本資料型態 練習資料型態的轉換 學習如何控制Matlab的輸出格式
第一個cordova project Cordova project建立與平台設定,均藉由cli(command line interface來完成 建立project請打開命令提示字元視窗應輸入下列命令 cordova create hello tw.edu.stust.mis.hello HelloWorld.
|07 函數.
雲端計算.
JAVA 程式設計 資訊管理系 - 網路組.
輸入&輸出 函數 P20~P21.
第一次Labview就上手 參考書籍: LabVIEW for Everyone (Jeffrey Travis/Jim Kring)
Presenter: Chih-Hsun Wang Date: 2015/9/15
挑戰C++程式語言 ──第8章 進一步談字元與字串
VS.NET 2003 IDE.
GridView操作 (II).
認識常數與變數 學習C++所提供的各種基本資料型態 瞭解溢位的發生 學習認識資料型態之間的轉換
如何使用Gene Ontology 網址:
雲端計算.
挑戰C++程式語言 ──第7章 輸入與輸出.
函數應用(二)與自定函數.
陣列與結構.
第 4 章 認識 SQL 語言與資料型別.
簡單Java介紹.
1757: Secret Chamber at Mount Rushmore
資料表示方法 資料儲存單位.
安裝JDK 配置windows win7 環境變數
大数据应用人才培养系列教材 Python语言 刘 鹏 张 燕 总主编 李肖俊 主编 刘 河 钟 涛 副主编.
Programming & Language Telling the computer what to do
Test for R Data Processing & Graphics
開發Java程式語言的工具 JDK.
單元三:敘述統計 內容: * 統計量的計算 * 直方圖的繪製.
ABAP Basic Concept (2) 運算子 控制式與迴圈 Subroutines Event Block
String類別 在C語言中提供兩種支援字串的方式 可以使用傳統以null結尾的字元陣列 使用string類別
SQLite資料庫 靜宜大學資管系 楊子青.
C語言程式設計 老師:謝孟諺 助教:楊斯竣.
Unix指令4-文字編輯與程式撰寫.
方法(Method) 函數.
ABAP Basic Concept (2) 運算子 控制式與迴圈 Subroutines Event Block
InputStreamReader Console Scanner
Presentation transcript:

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

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

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

Python3.6

Windows x86-64 executable installer

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

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

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

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

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

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

簡單的程式

變數型態和其可用的函數

string和一維 list型別

多維度list型別

dictionary、tuple和set型別

函數與呼叫在同個py檔案

函數與呼叫在不同py檔案

CSV檔案存取

#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)])

#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)])

編輯路徑變數以安裝第三方套組 為了在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 用來查詢已安裝的套組)

從控制台編輯路徑變數

安裝第三方套組>pip install numpy

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)

選取記錄和欄位(數字並不方便) 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]])

篩選執行結果

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

不用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

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

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)

使用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)

讀入整個矩陣 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)

列印對角線 # 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])

矩陣相加後輸出 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)

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

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

乳腺癌醫學診斷欄位說明 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)

wdbc (pandas+numpy)

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])

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

iris(pandas+numpy+matplotlib)

直方圖

長條圖

圓餅圖

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']

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%%")