1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.