Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing a matrix to a text file in python

When writing to a text file using the following code it shows following output :-

import numpy as np

a = np.random.randint(1, 1000, size =(100, 30),dtype='int64')
print(a)
np.savetxt('filename.txt', a)

Output :-

5.100000000000000000e+01 1.530000000000000000e+02 7.290000000000000000e+02 4.180000000000000000e+02 6.700000000000000000e+02 4.410000000000000000e+02 6.230000000000000000e+02 1.970000000000000000e+02 8.120000000000000000e+02 5.770000000000000000e+02 3.790000000000000000e+02 8.970000000000000000e+02 5.890000000000000000e+02 6.140000000000000000e+02 9.500000000000000000e+01

I want 51 153 and son on as values in text file instead of these.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to specify format (fmt) if you are not happy with numpy.savetxt‘s default %.18e. Use %d if you just want simple integers, consider following simple example

import numpy as np
arr = np.array([[51,153],[729,51]])
np.savetxt('array.txt', arr, fmt='%d')

creates array.txt with following content

51 153
729 51
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading