Home > Enterprise >  writing multiple lists as multiple row and column in a csv file python
writing multiple lists as multiple row and column in a csv file python

Time:04-12

hi I have some doubts regarding writing lists as CSV

I have multiple lists like following

head = ["name","roll_no","age"]
name = ["mohan","naveen","deepan"]
roll_no = [2087,2083,2090]
age = [23,23,24] 

I need CSV file output as the head list must header of the columns

name     roll_no    age

mohan     2087       23
naveen    2083       23
deepan    2090       24

here is the code that I tried:

    def write_csv(self, data, header_list):
        my_df = pd.DataFrame(data)
        my_df.to_csv(path_or_buf='my_csv.csv', index=True, header=header_list)
      

Any help would be appreciated

CodePudding user response:

Try:

head = ["name", "roll_no", "age"]
name = ["mohan", "naveen", "deepan"]
roll_no = [2087, 2083, 2090]
age = [23, 23, 24]

df = pd.DataFrame(zip(name, roll_no, age), columns=head)
print(df)
df.to_csv("data.csv", index=False)

Prints:

     name  roll_no  age
0   mohan     2087   23
1  naveen     2083   23
2  deepan     2090   24

and saves data.csv (screenshot from LibreOffice):

enter image description here

  • Related