Search code examples
pythonnumpyio

Serialize numpy arrays into an npz string?


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?


Solution

  • 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)