使用python在sqlite3中存储numpy数组时遇到问题

时间:2022-01-20 21:26:30

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

我试图按照这里显示的最佳答案示例:Python将numpy数组插入sqlite3数据库

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

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.

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

1 个解决方案

#1


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

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

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

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:

那是因为3.x中不存在缓冲区。它实际上并没有在2.x中做任何有用的事情,所以你可以删除它。只需将最后一行替换为:

return out.read()

And now, everything else works perfectly.

现在,其他一切都很完美。

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:

如果你需要兼容旧的2.x和3.x(我不确定是否有任何版本重叠,但可能有...),你可以通过在顶部执行此操作来修复它模块:

try:
    buffer
except NameError:
    buffer = bytes

#1


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

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

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

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:

那是因为3.x中不存在缓冲区。它实际上并没有在2.x中做任何有用的事情,所以你可以删除它。只需将最后一行替换为:

return out.read()

And now, everything else works perfectly.

现在,其他一切都很完美。

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:

如果你需要兼容旧的2.x和3.x(我不确定是否有任何版本重叠,但可能有...),你可以通过在顶部执行此操作来修复它模块:

try:
    buffer
except NameError:
    buffer = bytes