[英]pandas: write dataframe to excel file *object* (not file)?
我有一個要轉換為excel文件的數據框,並使用HTTP返回。 數據框的to_excel
方法可以接受路徑,也可以接受ExcelWriter
,而后者又是指路徑。
有什么方法可以將數據幀轉換為文件對象,而無需將其寫入磁盤?
可以使用標准庫中的BytesIO
對象完成此操作:
import pandas
from io import BytesIO
# Create Random Data for example
cols = ["col1", "col2"]
df = pandas.DataFrame.from_records([{k: 0.0 for k in cols} for _ in range(25)])
# Create an in memory binary file object, and write the dataframe to it.
in_memory_fp = BytesIO()
df.to_excel(in_memory_fp)
# Write the file out to disk to demonstrate that it worked.
in_memory_fp.seek(0,0)
with open("my_file.xlsx", 'wb') as f:
f.write(in_memory_fp.read())
在上面的示例中,我將對象寫到了文件中,以便您可以驗證它是否有效。 如果只想將原始二進制數據返回到內存中,則需要做的是:
in_memory_fp.seek(0,0)
binary_xl = in_memory_fp.read()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.