NumPy save some arrays at once

前端 未结 1 1022
既然无缘
既然无缘 2020-12-15 17:09

I working on different shapes of arrays and I want to save them all with numpy.save, so, consider I have

mat1 = numpy.arange(8).reshape(4, 2)
         


        
相关标签:
1条回答
  • 2020-12-15 17:43

    If you'd like to save multiple arrays in the same format as np.save, use np.savez.

    For example:

    import numpy as np
    
    arr1 = np.arange(8).reshape(2, 4)
    arr2 = np.arange(10).reshape(2, 5)
    np.savez('mat.npz', name1=arr1, name2=arr2)
    
    data = np.load('mat.npz')
    print data['name1']
    print data['name2']
    

    If you have several arrays, you can expand the arguments:

    import numpy as np
    
    data = [np.arange(8).reshape(2, 4), np.arange(10).reshape(2, 5)]
    np.savez('mat.npz', *data)
    
    container = np.load('mat.npz')
    data = [container[key] for key in container]
    

    Note that the order is not preserved. If you do need to preserve order, you might consider using pickle instead.

    If you use pickle, be sure to specify the binary protocol, otherwise the you'll write things using ascii pickle, which is particularly inefficient for numpy arrays. With a binary protocol, ndarrays more or less pickle to the same format as np.save/np.savez. For example:

    # Note: This is Python2.x specific. It's identical except for the import on 3.x
    import cPickle as pickle
    import numpy as np
    
    data = [np.arange(8).reshape(2, 4), np.arange(10).reshape(2, 5)]
    
    with open('mat.pkl', 'wb') as outfile:
        pickle.dump(data, outfile, pickle.HIGHEST_PROTOCOL)
    
    with open('mat.pkl', 'rb') as infile:
        result = pickle.load(infile)
    

    In this case, result and data will have identical contents and the order of the input list of arrays will be preserved.

    0 讨论(0)
提交回复
热议问题