Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Saving array elements in CSV format in Python

I would like to save the elements of I in a CSV format. The current and desired outputs are attached.

import numpy as np
import csv

I=np.array([[0, 1],
       [0, 3],
       [1, 2],
       [1, 4],
       [2, 5],
       [3, 4],
       [3, 6],
       [4, 5],
       [4, 7],
       [5, 8],
       [6, 7],
       [7, 8]])

with open('Test123.csv', 'w') as f:
    writer = csv.writer(f)

    # write the data
    writer.writerows(I.T)

The current output is

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The desired output is

enter image description here

>Solution :

you can try using writerow and create the comma separated

import numpy as np
import csv

I=np.array([[0, 1],
       [0, 3],
       [1, 2],
       [1, 4],
       [2, 5],
       [3, 4],
       [3, 6],
       [4, 5],
       [4, 7],
       [5, 8],
       [6, 7],
       [7, 8]])

with open('Test123.csv', 'w') as f:
    writer = csv.writer(f)

    # write the data
    writer.writerow(map(lambda x: f'{x[0]}, {x[1]}', zip(*I.T)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading