python - 使用 SQLite 的 NumPy 数组

标签 python arrays sqlite numpy scipy

我在 Python 中看到的最常见的 SQLite 接口(interface)是 sqlite3,但是有什么可以很好地与 NumPy 数组或 recarrays 一起工作的吗?我的意思是一个识别数据类型并且不需要逐行插入并提取到 NumPy (rec) 数组中的...?有点像 RDBsqldf 库中的 R 的 SQL 函数,如果有人熟悉这些(他们将整个表或表的子集导入/导出/附加到 R 或从 R数据表)。

最佳答案

为什么不给 redis 试试?

您感兴趣的两个平台的驱动程序可用——python(redis,通过包索引] 2)和 R(rredisCRAN) .

redis 的天才之处在于,它会神奇地识别 NumPy 数据类型,并允许您插入和提取多维 NumPy 数组,就好像它们是 native Redis 数据类型一样,而它的天才之处在于只需几行代码即可轻松创建此类界面。

在 python 中有(至少)几个关于 redis 的教程; DeGizmo blog 上的那个特别好。

import numpy as NP

# create some data
A = NP.random.randint(0, 10, 40).reshape(8, 5)

# a couple of utility functions to (i) manipulate NumPy arrays prior to insertion 
# into redis db for more compact storage & 
# (ii) to restore the original NumPy data types upon retrieval from redis db
fnx2 = lambda v : map(int, list(v))
fnx = lambda v : ''.join(map(str, v))

# start the redis server (e.g. from a bash prompt)
$> cd /usr/local/bin      # default install directory for 'nix
$> redis-server           # starts the redis server

# start the redis client:
from redis import Redis
r0 = Redis(db=0, port=6379, host='localhost')       # same as: r0 = Redis()

# to insert items using redis 'string' datatype, call 'set' on the database, r0, and
# just pass in a key, and the item to insert
r0.set('k1', A[0,:])

# row-wise insertion the 2D array into redis, iterate over the array:
for c in range(A.shape[0]):
    r0.set( "k{0}".format(c), fnx(A[c,:]) )

# or to insert all rows at once
# use 'mset' ('multi set') and pass in a key-value mapping: 
x = dict([sublist for sublist in enumerate(A.tolist())])
r0.mset(x1)

# to retrieve a row, pass its key to 'get'
>>> r0.get('k0')
  '63295'

# retrieve the entire array from redis:
kx = r0.keys('*')           # returns all keys in redis database, r0

for key in kx :
    r0.get(key)

# to retrieve it in original form:
A = []
for key in kx:
    A.append(fnx2(r0.get("{0}".format(key))))

>>> A = NP.array(A)
>>> A
  array([[ 6.,  2.,  3.,  3.,  9.],
         [ 4.,  9.,  6.,  2.,  3.],
         [ 3.,  7.,  9.,  5.,  0.],
         [ 5.,  2.,  6.,  3.,  4.],
         [ 7.,  1.,  5.,  0.,  2.],
         [ 8.,  6.,  1.,  5.,  8.],
         [ 1.,  7.,  6.,  4.,  9.],
         [ 6.,  4.,  1.,  3.,  6.]])

关于python - 使用 SQLite 的 NumPy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7901853/

相关文章:

python - 在单元测试中将 JSON 发布到 Flask 端点时出现错误请求

android - 使用like的cursorloader选择查询

OCaml 的 Sqlite 绑定(bind)

python - 如何让 Flask 默认使用 Python 3

python - 为什么我的 for 循环没有迭代完整的 pandas 列表

php - 如何将两个值合并/合并到同一个数组中的单个键中

arrays - 仅在 freemarker 中创建 "object"(无 JAVA 等)?

ios - 有没有一种方法可以在FMDB中“启动泵”,因此可以更快地进行操作

python - torch.stack() 和 torch.cat() 函数有什么区别?

c - 如何编写递归函数的迭代版本?