This post is written as an IPython Notebook page, you can continue reading below or open it inside nbviewer.
Tag: pandas
This is a modification of write_frame() function in pandas.io.sql which for some reason was giving me errors, so I’ve amended it slightly for my specific need. Has been tested and works with Python 2.7.3 and Python 3.2.3 on Ubuntu 12.10 and Windows XP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/usr/bin/env python def df2sqlite(dataframe, db_name = "import.sqlite", tbl_name = "import"): import sqlite3 conn=sqlite3.connect(db_name) cur = conn.cursor() wildcards = ','.join(['?'] * len(dataframe.columns)) data = [tuple(x) for x in dataframe.values] cur.execute("drop table if exists %s" % tbl_name) col_str = '"' + '","'.join(dataframe.columns) + '"' cur.execute("create table %s (%s)" % (tbl_name, col_str)) cur.executemany("insert into %s values(%s)" % (tbl_name, wildcards), data) conn.commit() conn.close() |