本文共 925 字,大约阅读时间需要 3 分钟。
为了将numpy数组存储到SQLite数据库并读取出来,可以按照以下步骤进行操作:
安装必要的库:
numpy和sqlite3库。pip install numpy sqlite3
创建内存数据库:
import sqlite3conn = sqlite3.connect(':memory:', isolation_level=None)cursor = conn.cursor()创建数据库表:
test2的表,字段arr使用BLOB类型来存储二维数组:cursor.execute("create table test2 (arr BLOB)")将numpy数组存储到数据库:
x = np.arange(12).reshape(2, 6)
json.dumps()将numpy数组转换为JSON字符串并插入表中:cursor.execute("insert into test2 (arr) values (?)", (json.dumps(x.tolist()),))conn.commit()读取数据:
arr字段的值:cursor.execute("select arr from test2")data = cursor.fetchall()print(data)print(type(data))
将读取到的数据转换为numpy数组:
json.loads()将JSON字符串转换为列表,然后再将其转换为numpy数组:my_list = json.loads(data[0][0])temp = np.array(my_list)print(temp)print(type(temp))
关闭数据库连接:
cursor.close()conn.close()
通过以上步骤,可以成功地将numpy数组存储到SQLite数据库,并在需要时读取和转换回来。确保在处理数据库时注意异常处理,以避免潜在的错误。
转载地址:http://vvofk.baihongyu.com/