Mike的Python學院

資料庫管理維護、軟體程式設計、Kaggle、SQL指令碼、資料分析、Pandas、資料庫管理、建立資料庫、SQLite、PYTHON資料分析、Python、程式語言

Mike Ku

Learn Code With Mike品牌創辦人

2021/12/30

快速掌握Pandas套件寫入SQLite資料庫的重要方法

本文就以Kaggle網站的2021年富比士億萬富翁資料集(https://www.kaggle.com/roysouravcu/forbes-billionaires-of-2021 )為例,模擬如何將Pandas DataFrame中的資料存入SQLite資料庫。
Q:SQLite如何建立資料庫與資料表?
SQLite是一個免費的輕量型關聯式資料庫,相較於其它大型的企業級資料庫,無需伺服端的安裝,就可以在用戶端直接使用,對於小型的應用程式非常適合。
除此之外,Python也內建了SQLite模組(Module),在專案中直接引用即可,如下範例:
import sqlite3
而Pandas套件則需利用以下指令安裝:
$ pip install pandas
才能夠在專案中進行引用,如下範例:
import pandas as pd
import sqlite3
接著,就可以透過Pandas套件的read_csv()方法(Method),來讀取下載下來的資料集了,如下範例:
import pandas as pd
import sqlite3
df = pd.read_csv('Billionaire.csv') #讀取CSV資料集檔案
print(df)
其中,包含了Name(姓名)、NetWorth(淨值)、Country(國家)、收入來源(Source)及排名(Rank)欄位。而要將Pandas DataFrame中的資料存入SQLite資料庫,就需要先建立資料庫與資料表,這時候利用sqlite3模組(Module)即可達成,如下範例:
import pandas as pd
import sqlite3
df = pd.read_csv('Billionaire.csv')
conn = sqlite3.connect('billionaire.db') #建立資料庫
cursor = conn.cursor()
cursor.execute('CREATE TABLE Billionaire(Name, NetWorth, Country, Source, Rank)') #建立資料表
conn.commit()
以上的動作說明如下:
1.connect()-同時建立資料庫與連線
2.cursor()-建立資料庫操作指標
3.execute()-執行新增資料表的SQL指令
4.commit()-確認完成
而要檢查是否建立成功,可以下載DB Browser for SQLite工具( https://sqlitebrowser.org/dl/ ),點擊「打開資料庫」,選擇剛剛所建立的SQLite資料庫檔(billionaire.db),就可以看到其中的資料表(Billionaire)。
Q:Pandas DataFrame如何存入SQLite資料庫?
有了資料庫與資料表後,利用Pandas DataFrame的to_sql()方法(Method),就能夠將資料寫入SQLite資料庫,如下範例:
df = pd.read_csv('Billionaire.csv')
conn = sqlite3.connect('billionaire.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE Billionaire(Name, NetWorth, Country, Source, Rank)')
conn.commit()
#如果資料表存在,就寫入資料,否則建立資料表
df.to_sql('Billionaire', conn, if_exists='append', index=False)
以上的Pandas DataFrame的to_sql()方法(Method)包含4個關鍵字參數(Keyword Argument),分別為「寫入的資料表名稱」、「連線」、「資料表已存在該如何操作」及「是否寫入Pandas DataFrame索引值」,而其中的「if_exists='append'」意思就是資料表已存在,則將資料直接寫入。
開啟DB Browser for SQLite工具,選擇Billionaire資料表後,切換到Browse Data(瀏覽資料)頁籤,即可看到Pandas DataFrame中的資料成功寫入。
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike(https://www.learncodewithmike.com/2021/05/pandas-and-sqlite.html
)網站觀看更多精彩內容。
3 0 997 2