将字符串/文本和 pandas 数据框写入Excel [英] Write strings/text and pandas dataframe to excel

查看:199
本文介绍了将字符串/文本和 pandas 数据框写入Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样将一些文本和数据框保存到一个excel文件中:

I'd like to save some text and a dataframe to an excel file like that:

因此,我有以下变量:

text1 = "some text here"
text2 = "other text here"
df = pd.DataFrame({"a": [1,2,3,4,5], "b": [6,7,8,9,10], "c": [11,12,13,14,15]})

正如我已经发现的那样,可以使用xlsxwriter来执行此操作,这意味着我基本上必须遍历整个数据帧,以将每个条目写入excel工作簿中的不同单元格.这很麻烦.

As I've figured out there is the possibility to use the xlsxwriter to do this which means that I basically have to iterate over the whole dataframe to write each entry to a different cell in the excel workbook. This is quite cumbersome.

因此,我认为必须有一种更简单的方法来执行此操作;像这样的东西:

So, I thought there must an easier way to do this; something like this:

writer = pd.ExcelWriter("test.xlsx", engine="xlsxwriter")
writer.write(text1, startrow=0, startcol=0)
writer.write(text1, startrow=1, startcol=0)
df.to_excel(writer, startrow=4, startcol=0)

有没有更简单的方法?

推荐答案

您需要 write :

text1 = "some text here"
text2 = "other text here"
df = pd.DataFrame({"a": [1,2,3,4,5], "b": [6,7,8,9,10], "c": [11,12,13,14,15]})

writer = pd.ExcelWriter("test.xlsx")
df.to_excel(writer, startrow=4, startcol=0)

worksheet = writer.sheets['Sheet1']
worksheet.write(0, 0, text1)
worksheet.write(1, 0, text2)
#another solution
#worksheet.write_string(0, 0, text1)
#worksheet.write_string(1, 0, text2)

writer.save()

这篇关于将字符串/文本和 pandas 数据框写入Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆