Home > Mobile >  Writing numpy array in a text file
Writing numpy array in a text file

Time:01-06

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)

CodePudding user response:

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

CodePudding user response:

The first attempt does not work because a is a one-dimensional array, so "row" loops over each element of a, meaning "row" is a 0D array. Since np.savetxt() only works for one or two dimensional array, it fails.

  •  Tags:  
  • Related