简体   繁体   中英

How to write data to excel with header using Pandas?

I want to write the excel file with the header is在此处输入图片说明

I have data and I want to fill out the excel file. Then the expected result is在此处输入图片说明

This is my code but it does not show as my expected. Could you help me to fix it? Thanks

from pandas import DataFrame
id =['1','2']
width_man=['12','18']
height_man=['20','55']
age_man=['10','12']
width_woman=['15','11']
height_woman=['40','45']
age_woman=['11','15']

df = DataFrame({'ID': id, 'WIDTH': width_man, 'HEIGHT': height_man, 'AGE': age_man, 'WIDTH': width_woman, 'HEIGHT': height_woman, 'AGE': age_woman,})
df.to_excel('table.xlsx', sheet_name='sheet1', index=False)

THIS IS OUTPUT OF MY CODE

在此处输入图片说明

Use below method,

import pandas as pd

id =['1','2']
width_man=['12','18']
height_man=['20','55']
age_man=['10','12']
width_woman=['15','11']
height_woman=['40','45']
age_woman=['11','15']

df1 = pd.DataFrame({'ID': id, 'WIDTH': width_man, 'HEIGHT': height_man, 'AGE': age_man})
df2 = pd.DataFrame({'ID': id, 'WIDTH': width_woman, 'HEIGHT': height_woman, 'AGE': age_woman})
writer = pd.ExcelWriter('table.xlsx')
df1.to_excel(writer, sheet_name='Sheet1', startrow=1, index=False) 
df2.to_excel(writer, sheet_name='Sheet1',startrow=1,
             startcol=5, index=False)
worksheet = writer.sheets['Sheet1']
worksheet.write_string(0, 2, 'MAN')
worksheet.write_string(0, 6, 'WOMAN')

writer.save()

You should a multi-level index in Pandas to structure your data so that it matches your desired output:

dfm = pd.DataFrame({'WIDTH': width_man, 'HEIGHT': height_man, 'AGE': age_man, },index=id)
dfw = pd.DataFrame({'WIDTH': width_woman, 'HEIGHT': height_woman, 'AGE': age_woman,},index=id)
df = pd.concat([dfm,dfw],axis=1,keys=['man','woman'])
df.to_excel('table.xlsx', sheet_name='sheet1', index=True, index_label='id')

I've also changed id to the index since you're clearly using it as the index.

(The format of the excel file has some small differences to your desired output - no blank column between "man" and "woman", and "id" as the index label is on a separate line. However the point remains that by using Pandas to structure the data correctly the spreadsheet generates correctly and automatically)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM