python numpy矩阵转base64_numpy的阵列到Base64和回numpy的阵列 - 的Python

I am now trying to figure out how I can recover a numpy array from base64 data. This question and answer suggest it is possible: Reading numpy arrays outside of Python but an example is not given.

Using the code below as an example, how can I get a Numpy array from the base64 data if I know the dtype and the shape of the array?

import base64

import numpy as np

t = np.arange(25, dtype=np.float64)

s = base64.b64encode(t)

r = base64.decodestring(s)

q = ?????

I want a python statement to set q as a numpy array of dtype float64 so the result is an array identical to t. This is what the arrays encoded and decoded look like:

>>> 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( ????

The reason I am asking is because I am working on a project where I would like to store a lot of Numpy arrays in a MySQL database in an app powered by django.

Using this django snippet I can store base64 data in a textfield: http://djangosnippets.org/snippets/1669/

I want to write the arrays to the database as base64 instead of converting the arrays to a string of unicode.

Thanks for your help.

解决方案import base64

import numpy as np

t = np.arange(25, dtype=np.float64)

s = base64.b64encode(t)

r = base64.decodestring(s)

q = np.frombuffer(r, dtype=np.float64)

print(np.allclose(q, t))

# True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值