熊猫:将数据框写入 excel 文件 *object*(不是文件)?

blu*_*ote 5 python pandas

我有一个数据框,我想将其转换为 excel 文件,并使用 HTTP 返回它。Dataframe 的to_excel方法接受路径或ExcelWriter,而后者又指的是路径。

有没有办法将数据帧转换为文件对象,而不将其写入磁盘?

Ale*_*lex 10

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())
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我将对象写入文件,以便您可以验证它是否有效。如果您只想返回内存中的原始二进制数据,您需要的是:

in_memory_fp.seek(0,0)
binary_xl = in_memory_fp.read()
Run Code Online (Sandbox Code Playgroud)