Home > OS >  Storing arrays in a csv file in Python
Storing arrays in a csv file in Python

Time:01-30

I am saving the identity array A to a csv file. But for n=83, I see that the array is saved to a single row as shown below. However, for n=84, the array is saved but in a weird format as shown below. How can I save the array for n=84 and for much larger n in the same format as for n=83?

import numpy as np
import csv

A=np.identity(n)
print(A)

with open(rf"output.csv", 'w') as f:
    writer = csv.writer(f)
    writer.writerow([[A]])

The data when n=83

enter image description here

The data when n=84

enter image description here

CodePudding user response:

I'm not sure about the functionality of double brackets, [[A]] but by iterating manually, line by line, it seems to be working:

import csv
A = [[I, I*2, I*3] for I in range(1, 50)] # test data
with open(rf"output,csv", 'w') as f:
    writer = csv.writer(f)
    for i in A:
        writer.writerow(i)
    

CodePudding user response:

Try with numpy display options:

import re

with (np.printoptions(threshold=np.inf, linewidth=np.inf),
      open('output.csv', 'w') as f):
    writer = csv.writer(f)
    A_repr = re.sub('\s ', ' ', repr(A))
    writer.writerow([[A_repr]])

CodePudding user response:

IIUC, just add newline="" to enter image description here

  • Related