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 numpy array in a text file

I have encountered an error while trying to write a numpy error into a text file. To put the question the below code

import numpy as np

a = np.arange(1,10)
sigma = open("sample",'w')
for row in a:
    np.savetxt(sigma,row)
sigma.close()

gives an error ValueError: Expected 1D or 2D array, got 0D array instead

I worked around it with this code:

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

a = np.arange(1,10)
sigma = open("sample",'w')
np.savetxt(sigma,a, newline="\n")
sigma.close()

But I still do not now why my first attempt didn’t work. Why my array appears 0D? (I’m using python 3.9.9)

>Solution :

As is mentioned in the comments, the for loop is your problem, this is because when you iterate over a one dimensional array you get scalars:

import numpy as np

a = np.arange(1,10)
sigma = open("sample",'w')
np.savetxt(sigma,a)
sigma.close()

Result:


1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
4.000000000000000000e+00
5.000000000000000000e+00
6.000000000000000000e+00
7.000000000000000000e+00
8.000000000000000000e+00
9.000000000000000000e+00
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