#----------------------------------------------------- #範例13-5:查詢有缺值的資料 #------------------------------------------------- #(1)步驟1:建議:mySQL範例要在anaconda裡面測試(不要再cola測試) #要先安裝:python 3.x版本的安裝mysql的指令:pip install pymysql #(2)步驟2:安裝mySQL #安裝: wamp或xamp #帳號為root,密碼不設定 #(3)步驟3:建立mydb資料庫,匯入scorechi資料表 #(4)步驟4:連線mydb資料庫指令 #import pymysql #conn = pymysql.connect(host="localhost",user="root", password="", db="ch09") #(5)步驟5:查詢scorechi資料表,轉成df指令 #import pandas as pd #df = pd.read_sql_query("select * from books", conn) #------------------------------ #練習1:將excel檔案(scorenull.xlsx)轉成csv,匯入mydb資料庫 #------------------------------ #(1)下載檔案:https://acupun.site/lecture/pandas/example/chp10/pratice/scoreNull.xlsx #(2)將excel檔案(scoreNull.xlsx)轉成csv #(3)轉成編碼 = utf8檔案 #(4)建立mydb資料庫 #(5)匯入,scoreNull.csv #------------------------------ #練習2:讀取mySQL資料庫 #------------------------------ #連線mydb資料庫指令 import pymysql conn = pymysql.connect(host='localhost', user='root', password='', db='mydb') #查詢scorenull資料表,轉成df指令 import pandas as pd df = pd.read_sql_query("select * from scorenull", conn) print() print("2-1.顯示全部資料=\n", df) #------------------------------ #練習3:查詢欄位『數學』有缺值的資料 #(1)缺值有2種可能: # 第1種:null (傳統資料庫,若是沒有輸入值,就會以null格式儲存) # 第2種:空字串(由csv匯入mySQL的資料庫,缺值,會被記錄成空字串'') #SQL:查詢欄位『數學』有缺值 =>df2 = pd.read_sql_query("select * from scorenull where 數學 IS NULL", conn) #Pandas:查詢欄位『數學』有缺值 => df[ a1 = df['數學'].isnull() ] #SQL:查詢欄位『數學』有空字串 => df2 = pd.read_sql_query("select * from scorenull where 數學 =''", conn) #Pandas:查詢欄位『數學』有空字串,方法1 => df[ df['數學']=='' ] #------------------------------ print() df2 = pd.read_sql_query("select * from scorenull where 數學 IS NULL", conn) print("3-1.SQL:查詢欄位『數學』有缺值的資料=\n", df2) print() a1 = df['數學'].isnull() print("3-2.Pandas:查詢欄位『數學』有缺值的資料,方法1 =\n", df[a1]) #結果:發現沒有查到缺值資料 #原因:由csv匯入mySQL的資料庫,缺值,會被記錄成空字串'' print() print('印出第5位同學的數學分數=', df['數學'][4]) print('看第5位同學數學的資料型態=', type(df['數學'][4])) #結果:缺值被記錄成:str:空字串(不是null) print() df2 = pd.read_sql_query("select * from scorenull where 數學 =''", conn) print("3-3.SQL:查詢欄位『數學』有空字串的資料=\n", df2) print() a1 = df['數學']=='' print("3-4.Pandas:查詢欄位『數學』有空字串的資料,方法1 =\n", df[a1]) print() print("3-5.Pandas:查詢欄位『中文』有空字串的資料,方法2 =\n", df.query("中文 == ''")) #關閉連線 conn.close() #--------------------------------------------------------------------