Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize numpy arrays into an npz string?

Tags:

python

io

numpy

I'm looking for a way to generate a compressed binary string out of multiple numpy arrays with different types. :D The method recommended in this question:

Storing and loading numpy arrays as files

Is to use the following:

np.savez_compressed('file_name_here.npz', arr_a = a, arr_b = b)

But the caveat is that I need the actual string directly and don't have a path to save it to. Is there any simple way to directly generate the binary string without saving to disk? Is there some kind of work around to do this?

like image 891
AturSams Avatar asked Feb 09 '23 20:02

AturSams


1 Answers

You could simply save the compressed array to a StringIO object and read it back,

from cStringIO import StringIO
import numpy as np

x = np.ones(10)

f = StringIO()
np.savez_compressed(f, x=x)
f.seek(0)
out = f.read()

print(out)
like image 200
rth Avatar answered Feb 13 '23 22:02

rth