Thursday, December 5, 2013

Store numpy arrays in sqlite

Use numpy.getbuffer (or sqlite3.Binary) in combination with numpy.frombuffer to lug numpy data in and out of the sqlite3 database:
import sqlite3, numpy

r1d = numpy.random.randn(10)

con = sqlite3.connect(':memory:')
con.execute("CREATE TABLE eye(id INTEGER PRIMARY KEY, desc TEXT, data BLOB)")
con.execute("INSERT INTO eye(desc,data) VALUES(?,?)", ("1d", sqlite3.Binary(r1d)))
con.execute("INSERT INTO eye(desc,data) VALUES(?,?)", ("1d", numpy.getbuffer(r1d)))
res = con.execute("SELECT * FROM eye").fetchall()
con.close()

#res ->
#[(1, u'1d', <read-write buffer ptr 0x10371b220, size 80 at 0x10371b1e0>),
# (2, u'1d', <read-write buffer ptr 0x10371b190, size 80 at 0x10371b150>)]

print r1d - numpy.frombuffer(res[0][2])
#->[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

print r1d - numpy.frombuffer(res[1][2])
#->[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

Note that for work where data types other than float and shapes other than 1d are needed you will also need to keep track of dtype and shape and store those in the database so you can pass them to numpy.frombuffer

No comments:

Post a Comment