社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python sqlite3:有没有办法以numpy数组的形式获得结果?[副本]

user1581390 • 6 年前 • 1592 次点击  

我不是程序员,我做这个纯粹是为了业余爱好。

我找到了一种将numpy数组保存到sqlite数据库的方法

import sqlite3
import numpy

# Array of 4 columns and 100 rows
data = numpy.random.rand(100, 4)

# Create a sample database
conn = sqlite3.connect('sample.db')
cursor = conn.cursor()

# Create a new table with four columns
cursor.execute('''create table data (field1 real, field2 real, field3 real,    field4 real)''')
conn.commit()

# Insert the data array into the 'data' table
cursor.executemany('''insert into data values (?, ?, ?, ?)''', map(tuple,    data.tolist()))
conn.commit()
cursor.close()
conn.close()

但是我有一个问题想找到一种方法来逆转这个过程。 我想从numpy数组中的数据库加载数据..一些建议在哪里找到一个简单的例子?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46880
文章 [ 1 ]  |  最新文章 6 年前
hpaulj
Reply   •   1 楼
hpaulj    8 年前

只需获取所有值。给你一个元组列表。 np.array() 返回到原始数组:

In [12]: cursor.execute('SELECT * from data')
Out[12]: <sqlite3.Cursor at 0xaf8e9d60>
In [13]: alist = cursor.fetchall()
In [14]: len(alist)
Out[14]: 100
In [15]: alist[0]
Out[15]: 
(0.3327498114993416,
 0.6164620040846208,
 0.5099007559772143,
 0.7808234554641948)
In [16]: data1 = np.array(alist)
In [17]: np.allclose(data, data1)
Out[17]: True

这是一个元组列表并不重要。就像一张单子一样好。