0

I am trying to save a list sigma1 containing a numpy array in CSV format. In the current output, the data is saved in multiple rows without commas. In the expected output, I want the data to be saved in a single row with commas, exactly like sigma1.

import numpy as np
import csv

sigma1= [np.array([[0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109]])]


with open('Data_sigma.csv', 'w') as f:
     writer = csv.writer(f)
     print(sigma1)
     f.writelines('sigma'+ '\n')
     f.write(str(sigma1))

The current output is

enter image description here

The expected output is

enter image description here

1
  • If you write out the NumPy array to your CSV file the expected output will simply contain each value separated by a comma (no np.array) i.e. [0.02109],[0.02109],[0.02109],[0.02109],[0.02109],[0.02109],[0.02109],[0.02109],[0.02109],[0.02109],[0.02109],[0.02109] Commented Aug 31, 2022 at 6:10

1 Answer 1

1

In your code, you are using the file to write your lines rather than the csv writer. Use the csv writer with the writerow function to write a single row to the CSV file:

with open('Data_sigma.csv', 'w') as f:
     writer = csv.writer(f)
     writer.writerow(sigma1[0])

Note, as sigma1 is a list containing the NumPy array, we have written out sigma1[0]. If you have multiple NumPy arrays in sigma1 then you can write all of these out to your file using writerows as follows:

with open('Data_sigma.csv', 'w') as f:
     writer = csv.writer(f)
     writer.writerows(sigma1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.