我有一个包含20列和100行的CSV文件。我想用两个列创建一个SQLite数据库 - 第1列中的日期和温度是第10列。我修改了一些我找到的示例代码,但我不确定如何使用这两列。< / p>
import csv, sqlite3
import sys
filename = sys.argv[-1]
con = sqlite3.connect("my.db")
con.execute("create table stats(date, temperature)")
cur = con.cursor()
stats = csv.reader(open(filename))
con.executemany("insert into stats(date, temperature) values (?, ?)", stats)
con.commit()
答案 0 :(得分:1)
con.executemany("insert into stats(date, temperature) values (?, ?)",
((rec[0], rec[9]) for rec in stats))
答案 1 :(得分:1)
您可以使用pandas 只读取指定的列并将其写入DB
import sqlite3
from pandas.io import sql
import pandas as pd
from StringIO import StringIO
s = """Year,Make,Model
1997,Ford,E350
2000,Mercury,Cougar"""
f = StringIO(s)
df = pd.read_csv(f, usecols = ['Year','Model']) # reads specified cols
# to a DataFrame
con = sqlite3.connect(':memory:')
sql.write_frame(df, name='test', con=con)
print sql.read_frame('select * from test', con) # reads data back
# to DataFrame
出:
Year Model
0 1997 E350
1 2000 Cougar