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:
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