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

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)))

Leave a Reply