我可以将带浮点数的Numpy数组保存到sqlite3,但不能保存带整数的数组:
import sqlite3
import numpy as np
db = sqlite3.connect('database.db')
database = db.cursor()
database.execute("CREATE TABLE table_name "
"(round INT, id INT, PRIMARY KEY(round, id))")
row_to_write = np.array([1])
dtype = str(row_to_write.dtype)
if dtype.startswith('float'):
database.execute("ALTER TABLE table_name ADD data FLOAT;")
elif dtype.startswith('int'):
database.execute("ALTER TABLE table_name ADD data INTEGER;")
insert_str = "INSERT INTO table_name (round, id, data) VALUES (0, 0, ?);"
database.execute(insert_str, row_to_write)
结果:
InterfaceError: Error binding parameter 0 - probably unsupported type.
如果我指定浮点数组而不是工作 row_to_write = np.array([1.1])
答案 0 :(得分:8)
Numpy正在使用一些自定义整数数据类型来有效地将数据打包到内存中。由于sqlite不熟悉这些类型,因此您必须事先告诉它如何处理它们:
>>> for t in (np.int8, np.int16, np.int32, np.int64,
... np.uint8, np.uint16, np.uint32, np.uint64):
... sqlite3.register_adapter(t, long)
...
>>> cur.execute("insert into foo(bar) values(?)", np.array([1]))
<sqlite3.Cursor object at 0x027A7620>
答案 1 :(得分:0)
在使用值之前,您可以在数组上调用tolist
:
>>> import numpy as np
>>> x = np.array([1,2,3])
>>> type(x[0])
<type 'numpy.int64'>
>>> y = x.tolist()
>>> y
[1, 2, 3]
>>> type(y[0])
<type 'int'>