[Python筆記] 將 Pandas 的 Dataframe 寫入 Sqlite3

使用 pandas.io 寫入 Sqlite

import sqlite3 as lite
from pandas.io import sql
import pandas as pd

依照 if_exists 分為三種模式寫入sqlite

分別有預設 failed, replace, append

 

#連結sqlite資料庫
cnx = lite.connect('data.db')

#選取dataframe 要寫入的欄位名稱
#欄位名稱需與資料庫的欄位名稱一樣 才有辦法對照寫入
sql_df=df.loc[:,['Column Name A','Column Name A','Column Name A']]

#將 sql_df 資料寫入 Table名稱 Daily_Record 內

#if_exists 預設為 failed 新建一個 Daily_Record table 並寫入 sql_df資料
sql.write_frame(sql_df, name='Daily_Record', con=cnx)

#if_exists 選擇 replace 是Daily_Record 這個 table 已存在資料庫
#將Daily_Record 表刪除並重新創建 寫入 sql_df 的資料
sql.write_frame(sql_df, name='Daily_Record', con=cnx, if_exists='replace')
#if_exists 選擇 appnd 是 Daily_Record 這個 table 已存在資料庫 將 sql_df 的資料 Insert 進去
sql.write_frame(sql_df, name='Daily_Record', con=cnx, if_exists='append')

 

posted @ 2015-11-08 19:47  vickychan222  阅读(6786)  评论(0编辑  收藏  举报