python - Numpy 数组到 base64 并返回到 Numpy 数组 - Python

标签 python django arrays numpy base64

我现在正试图弄清楚如何从 base64 数据中恢复一个 numpy 数组。这个问题和答案表明这是可能的:Reading numpy arrays outside of Python但没有给出例子。

以下面的代码为例,如果我知道数组的dtype和形状,如何从base64数据中获取Numpy数组?

import base64
import numpy as np

t = np.arange(25, dtype=np.float64)
s = base64.b64encode(t)
r = base64.decodestring(s)
q = ????? 

我想要一个 python 语句将 q 设置为 dtype float64 的 numpy 数组,因此结果是一个与 t 相同的数组。这是编码和解码的数组的样子:

>>> t = np.arange(25,dtype=np.float64)
>>> t
array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,
    11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,
    22.,  23.,  24.])
>>> s=base64.b64encode(t)
>>> s
'AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxAAAAAAAAALkAAAAAAAAAwQAAAAAAAADFAAAAAAAAAMkAAAAAAAAAzQAAAAAAAADRAAAAAAAAANUAAAAAAAAA2QAAAAAAAADdAAAAAAAAAOEA='
>>> r = base64.decodestring(s)
>>> r
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x18@\x00\x00\x00\x00\x00\x00\x1c@\x00\x00\x00\x00\x00\x00 @\x00\x00\x00\x00\x00\x00"@\x00\x00\x00\x00\x00\x00$@\x00\x00\x00\x00\x00\x00&@\x00\x00\x00\x00\x00\x00(@\x00\x00\x00\x00\x00\x00*@\x00\x00\x00\x00\x00\x00,@\x00\x00\x00\x00\x00\x00.@\x00\x00\x00\x00\x00\x000@\x00\x00\x00\x00\x00\x001@\x00\x00\x00\x00\x00\x002@\x00\x00\x00\x00\x00\x003@\x00\x00\x00\x00\x00\x004@\x00\x00\x00\x00\x00\x005@\x00\x00\x00\x00\x00\x006@\x00\x00\x00\x00\x00\x007@\x00\x00\x00\x00\x00\x008@'
>>> q = np.array( ????

我问的原因是因为我正在做一个项目,我想在一个由 django 提供支持的应用程序中的 MySQL 数据库中存储大量 Numpy 数组。

使用这个 django 片段,我可以将 base64 数据存储在文本字段中:http://djangosnippets.org/snippets/1669/

我想将数组作为 base64 写入数据库,而不是将数组转换为 unicode 字符串。

最佳答案

import base64
import numpy as np

t = np.arange(25, dtype=np.float64)
s = base64.b64encode(t)
r = base64.decodebytes(s)
q = np.frombuffer(r, dtype=np.float64)

print(np.allclose(q, t))
# True

关于python - Numpy 数组到 base64 并返回到 Numpy 数组 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6485790/

相关文章:

python - 在 Python MySQL 中执行 INSERT 查询的正确方法是什么?

django - 从自定义包含模板标签中访问 STATIC_URL

带有 mod_wsgi 的 Django 返回 403 错误

python - 为什么要使用 tf.train.Server 并行执行多个 tf.Session()?

python - 使用 Python 的 Windows 应用程序

arrays - 如何按位置对 postgresql 数组的元素求和?

arrays - 如何通过组合 column_names 列表和 numpy 数组然后添加更多列来创建 pandas DataFrame?

arrays - 如何在Elasticsearch数组列表中查询精确值(带空格)

python - 使用python打开rar文件并读取csv文件

python - Django objects.filter() values_list() vs python list comprehension for __in query