pandas 用标题将数据框写入excel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34767635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write dataframe to excel with a title
提问by Hamed
I would like to print out a dataframe in Excel. I am using ExcelWriter as follows:
我想在 Excel 中打印出一个数据框。我使用 ExcelWriter 如下:
writer = pd.ExcelWriter('test.xlsx')
df = DataFrame(C,ind) # C is the matrix and ind is the list of corresponding indices
df.to_excel(writer, startcol = 0, startrow = 5)
writer.save()
This produces what I need but in addition I would like to add a title with some text (explanations) for the data on top of the table (startcol=0
,startrow=0
).
这产生了我需要的东西,但此外我想为表格顶部的数据添加一个带有一些文本(解释)的标题(startcol=0
, startrow=0
)。
How can I add a string title using ExcelWriter?
如何使用 ExcelWriter 添加字符串标题?
回答by Fabio Lamanna
You should be able to write text in a cell with the write_stringmethod, adding some reference to XlsxWriterto your code:
您应该能够使用write_string方法在单元格中写入文本,将一些对XlsxWriter 的引用添加到您的代码中:
writer = pd.ExcelWriter('test.xlsx')
df = DataFrame(C,ind) # C is the matrix and ind is the list of corresponding indices
df.to_excel(writer, startcol = 0, startrow = 5)
worksheet = writer.sheets['Sheet1']
worksheet.write_string(0, 0, 'Your text here')
writer.save()
回答by Yannis P.
This will do the trick:
这将解决问题:
In[16]: sheet = writer.sheets['Sheet1'] #change this to your own
In[17]: sheet.write(0,0,"My documentation text")
In[18]: writer.save()