将数据从sqlite导出到numpy数组 [英] Exporting data from sqlite to numpy array

查看:192
本文介绍了将数据从sqlite导出到numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是程序员,我纯粹是出于业余爱好.

I'm not a programmer, I do this purely as a hobby..

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

I found a way to save numpy array in to sqlite database

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数组的形式从数据库中加载数据.一些建议在哪里找到一个简单的示例?

But I have a problem about finding a way to reverse the process.. I want to load data from database in numpy array.. Some suggestion where to find a simple example?

推荐答案

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

Just fetch all the values. That gives you a list of tuples. np.array() takes you back to the original 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

它是元组列表的事实并不重要.和列表列表一样好.

The fact that it's a list of tuples doesn't matter. It's just as good as a list of lists.

这篇关于将数据从sqlite导出到numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆