Numpy Array to base64 and back to Numpy Array - Python
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
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.