0

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)

3
  • 1
    a is 1-dimensional. It does not have rows. Commented Jan 5, 2022 at 21:08
  • Yes, it's 1D, but the error tells me it's 0D, it should still work with 1D. Commented Jan 5, 2022 at 21:14
  • In you example a is 1-d, but row is 0-d. Commented Jan 5, 2022 at 21:16

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.