繁体   English   中英

如何使用 Pandas 将数据写入带有标题的excel?

[英]How to write data to excel with header using Pandas?

我想写带有标题的excel文件是在此处输入图片说明

我有数据,我想填写excel文件。 那么预期的结果是在此处输入图片说明

这是我的代码,但没有按我的预期显示。 你能帮我修一下吗? 谢谢

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)

这是我的代码的输出

在此处输入图片说明

使用下面的方法,

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()

您应该在 Pandas 中建立一个多级索引来构建您的数据,使其与您想要的输出相匹配:

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')

我还将 id 更改为索引,因为您显然将其用作索引。

(excel文件的格式与您想要的输出有一些小的差异——“男人”和“女人”之间没有空白列,“id”作为索引标签在单独的行上。但是,使用 Pandas 仍然是这一点正确地构建电子表格正确自动生成的数据)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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