2017-10-18 85 views
1

我有大量.csv文件,我想放在sqlite數據庫中。大多數文件包含相同的列名稱,但有一些文件具有額外的列。從具有不同列名的csv文件創建sqlite表

,我試過的代碼是(改變爲通用):

import os  
import pandas as pd 
import sqlite3 

conn = sqlite3.connect('test.db') 
cur = conn.cursor() 

os.chdir(dir) 
for file in os.listdir(dir): 
    df = pd.read_csv(file) 
    df.to_sql('X', conn, if_exists = 'append') 

當它遇到同列的文件是不是在桌子X我得到的錯誤:

OperationalError: table X has no column named ColumnZ

如何更改我的代碼以將新列添加到表中,並用NaN填充以前的行?

回答

0

如果所有DataFrames可以放入RAM,你可以這樣做:

import glob 

files = glob.glob(r'/path/to/csv_files/*.csv') 

df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True) 
df.to_sql('X', conn, if_exists = 'replace') 

演示:

In [22]: d1 
Out[22]: 
    a b 
0 0 1 
1 2 3 

In [23]: d2 
Out[23]: 
    a b c 
0 1 2 3 
1 4 5 6 

In [24]: d3 
Out[24]: 
    x b 
0 11 12 
1 13 14 

In [25]: pd.concat([d1,d2,d3], ignore_index=True) 
Out[25]: 
    a b c  x 
0 0.0 1 NaN NaN 
1 2.0 3 NaN NaN 
2 1.0 2 3.0 NaN 
3 4.0 5 6.0 NaN 
4 NaN 12 NaN 11.0 
5 NaN 14 NaN 13.0 

或者您可以將所有的列存儲爲列表和循環檢查是否有新的DF有額外的列並將這些列添加到SQLite DB,使用SQLite ALTER TABLE statement

ALTER TABLE tab_name ADD COLUMN ... 
+0

不幸的是我無法適應RAM中的所有文件。我喜歡你的方法,有沒有辦法使用chunk方法並在每個'df.to_sql'後轉儲'df'來釋放RAM?我已經嘗試了'del df',但是這並沒有解放RAM。 –

相關問題