Home > database >  Array in a specific format in csv file using Python
Array in a specific format in csv file using Python

Time:03-14

I am trying to save the array inv_r in a specific format in a csv file. The current and the desired formats are attached.

import numpy as np
import csv

inv_r=np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],
                [16,17,18,19,20],
                [21,22,23,24,25]])
data = [inv_r]

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

    # write the data
    writer.writerows(zip(inv_r))

The current format is

enter image description here

The desired format is

enter image description here

CodePudding user response:

You need to remove the zip, first of all, so that each element get its own cell.

To remove the blank lines between each row, you need to add newline='' to the open call. See the footnote in the documentation for the csv library here for an explanation as to why this is necessary.

  • Related