FF123456
FF123456

Reputation: 83

csv file to excel, resulting in messy table

I want to convert my csv file to excel, but the first line of the csv get read as header

I first created a csv with the lists below then I used pandas to convert it to excel

import pandas as pd

id=["id",1,2,3,4,5]
name=["name","Salma","Ahmad","Manar","Mustapha","Zainab"]
age=["age",14,12,15,13,10]

#this is how i created the csv file
Csv='path/csvfile.csv'
open_csv=open(Csv, 'w')
outfile=cvs.writer(open_csv)
outfile.writerows([id]+[name]+[age])
open_csv.close()

#Excel file
Excel='path/Excelfile.xlsx'
Excel_open=open(Excel, 'w')
csv_file=pd.read_csv(Csv)
csv_file.to_excel(Excel)

This is what I get from this code "Results" I want the Id title to be in the same column as name and age

Upvotes: 1

Views: 97

Answers (1)

I would suggest this instead:

import pandas as pd

df = pd.DataFrame({
                   "id": [1,2,3,4,5],
                   "name":["Salma","Ahmad","Manar","Mustapha","Zainab"],
                   "age":[14,12,15,13,10]
                  })

excel_file = df.to_excel("excel_file.xlsx", index=False)

In this way you can create a dataframe more easily and understandable.

Upvotes: 1

Related Questions