Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:将数据框写入excel文件*对象*(不是文件)?_Python_Pandas - Fatal编程技术网

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

Python 熊猫:将数据框写入excel文件*对象*(不是文件)?,python,pandas,Python,Pandas,我有一个数据框,我想转换成excel文件,并使用HTTP返回它。Dataframe的to_excel方法接受路径或ExcelWriter,后者反过来引用路径 有没有办法将数据帧转换为文件对象,而不将其写入磁盘?这可以使用标准库中的对象完成: import pandas from io import BytesIO # Create Random Data for example cols = ["col1", "col2"] df = pandas.DataFrame.from_records

我有一个数据框,我想转换成excel文件,并使用HTTP返回它。Dataframe的
to_excel
方法接受路径或
ExcelWriter
,后者反过来引用路径


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

这可以使用标准库中的对象完成:

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()

尝试
df.to_string
和python
io.StringIO
He,检查这个问题是,我想先将其转换为excel格式,而不仅仅是将数据帧转换为字节