gpt4 book ai didi

python - Pandas :保存数据框以打开工作簿

转载 作者:行者123 更新时间:2023-11-28 17:36:16 25 4
gpt4 key购买 nike

我有一个打开的工作簿,其中写入了数据。如何添加工作表来写入数据框的内容?

import xlsxwriter
import pandas as pd

workbook = xlsxwriter.Workbook('test.xlsx')
sheet1 = workbook.add_worksheet(name='sheet1')
sheet1.write(0, 0, 'test')
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': ['aa', 'bb', 'cc', 'dd']})
# write df somehow to next sheet. I usually use df.to_excel(filename, engine='xlsxwriter'), but this will create a new file
workbook.close()

最佳答案

正如您在评论中发现的那样,您不能将 XlsxWriter 工作簿对象传递给 pandas to_excel()

作为解决方法,您可以创建一个包含空数据框的工作表,然后访问 XlsxWriter 工作簿和下面的工作表对象。然后,您可以通过 pandas 界面添加额外的工作表。

这是一个基于您的代码的小示例:

import pandas as pd

# Create an pandas excel writer based on xlsxwriter.
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

# Create a worksheet with an empty dataframe so the sheet is empty.
df = pd.DataFrame()
df.to_excel(writer, sheet_name='Sheet1')

# Access the underlying xlsxwriter worksheet and write to it.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.write(0, 0, 'test')

# Create another dataframe with data.
df = pd.DataFrame({'a': [1, 2, 3, 4],
'b': ['aa', 'bb', 'cc', 'dd']})

# Write the dataframe to another worksheet.
df.to_excel(writer, sheet_name='Sheet2')

writer.save()

另见 Working with Python Pandas and XlsxWriter .

关于python - Pandas :保存数据框以打开工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com