75
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
6
The code below will encode it as base64. It will handle numpy arrays of any type/size without needing to remember what it was. It will also handle other arbitrary objects that can be pickled.
import numpy as np
import pickle
import codecs
obj = np.random.normal(size=(10, 10))
obj_base64string = codecs.encode(pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL), "base64").decode('latin1')
obj_reconstituted = pickle.loads(codecs.decode(obj_base64string.encode('latin1'), "base64"))
You can remove .decode(‘latin1’) and .encode(‘latin1’) if you just want the raw bytes.
- [Django]-How can I check the size of a collection within a Django template?
- [Django]-Why won't Django use IPython?
- [Django]-Variable subtraction in django templates
Source:stackexchange.com