Saving and loading a Numpy matrix in python

Can someone give me an example of how to save a 2-dimensional matrix in a file and reload it for future use?

+10
python file numpy
source share
2 answers
>>> import numpy >>> mat = numpy.matrix("1 2 3; 4 5 6; 7 8 9") >>> mat.dump("my_matrix.dat") >>> mat2 = numpy.load("my_matrix.dat") 
+23
source share

you can expand your matrix:

  >> import numpy >> import pickle >> b=numpy.matrix('1 2; 3 4') >> f=open('test','w') >> pickle.dump(b, f) >> f.close() >> f2 = open('test', 'r') >> s = pickle.load(f2) >> f2.close() >> s matrix([[1, 2], [3, 4]]) 

Tamas answer is much better than this: numpy matrixes objects have a direct method for sorting them.

In any case, keep in mind that the pickle library is a general tool for saving python objects, including classes.

+5
source share

All Articles