使用python在sqlite3中存储numpy数组时遇到问题 [英] Trouble storing numpy array in sqlite3 with python

查看:99
本文介绍了使用python在sqlite3中存储numpy数组时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循此处显示为最佳答案的示例: Python将numpy数组插入sqlite3数据库

I'm trying to follow the example shown as the top answer here: Python insert numpy array into sqlite3 database

起初我以为是我的代码,但是我尝试完全复制并粘贴答案代码,但仍然遇到相同的错误:

At first I thought it was my code, but I've tried copying and pasting the answer code exactly and I'm still getting the same error:

OSError: Failed to interpret file <_io.BytesIO object at 0x02B87C00> as a pickle

在convert_array函数中似乎存在一个问题,即numpy无法将其识别为已保存的文件(或者可能是adapt_array函数没有正确存储它的问题?).我正在使用Python 3.4.3.2和SQLite 3.8.9.只是好奇是否有人在尝试运行上面链接的答案中的代码时能确认自己遇到相同的错误,特别是如果有人对如何解决并使其正常工作有见识.

It seems there is a problem in the convert_array function that numpy isn't recognizing it as a saved file (or maybe a problem with adapt_array function that isn't storing it properly?). I am using Python 3.4.3.2 and SQLite 3.8.9. Just curious if anyone can confirm that they are getting the same error when they try to run the code in the linked answer above, and especially if anyone has insights on how to fix it and make it work.

推荐答案

unutbu的代码唯一的问题是他的adapt_array在Python 3中引发了异常:

The only problem with unutbu's code is that his adapt_array raises an exception in Python 3:

def adapt_array(arr):
    out = io.BytesIO()
    np.save(out, arr)
    out.seek(0)
    # http://stackoverflow.com/a/3425465/190597 (R. Hill)
    return buffer(out.read())

这是因为 buffer 在3中不存在. X.在2.x中,它实际上并没有做任何有用的事情,因此您可以将其删除.只需将最后一行替换为:

That's because buffer doesn't exist in 3.x. And it isn't actually doing anything useful here in 2.x, so you can just remove it. Just replace that last line with:

return out.read()

现在,其他所有功能都可以正常运行.

And now, everything else works perfectly.

如果您需要与较早的2.x以及3.x兼容(我不确定是否是否存在与此重叠的任何版本,但是可能存在……),您可以改为为此,请在模块顶部对其进行修复:

If you need compatibility with older 2.x and also with 3.x (I'm not sure if there are any versions where this overlaps, but there might be…), you can instead fix it by doing this at the top of the module:

try:
    buffer
except NameError:
    buffer = bytes

这篇关于使用python在sqlite3中存储numpy数组时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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