gpt4 book ai didi

pandas - 将 Pandas DataFrame 转换为类似字节的对象

转载 作者:行者123 更新时间:2023-12-02 10:40:07 25 4
gpt4 key购买 nike

您好,我正在尝试将 df 转换为二进制并将其存储在变量中。

我的_df:

 df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})

我的代码:

 import io
towrite = io.BytesIO()
df.to_excel(towrite) # write to BytesIO buffer
towrite.seek(0) # reset pointer

我收到AttributeError:'_io.BytesIO'对象没有属性'write_cells'

完整回溯:

AttributeError                            Traceback (most recent call last)
<ipython-input-25-be6ee9d9ede6> in <module>()
1 towrite = io.BytesIO()
----> 2 df.to_excel(towrite) # write to BytesIO buffer
3 towrite.seek(0) # reset pointer
4 encoded = base64.b64encode(towrite.read()) #

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in to_excel(self, excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, encoding, inf_rep, verbose, freeze_panes)
1422 formatter.write(excel_writer, sheet_name=sheet_name, startrow=startrow,
1423 startcol=startcol, freeze_panes=freeze_panes,
-> 1424 engine=engine)
1425
1426 def to_stata(self, fname, convert_dates=None, write_index=True,

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\excel.py in write(self, writer, sheet_name, startrow, startcol, freeze_panes, engine)
624
625 formatted_cells = self.get_formatted_cells()
--> 626 writer.write_cells(formatted_cells, sheet_name,
627 startrow=startrow, startcol=startcol,
628 freeze_panes=freeze_panes)

AttributeError: '_io.BytesIO' object has no attribute 'write_cells'

最佳答案

我通过将 pandas 升级到新版本解决了这个问题。

 import io
towrite = io.BytesIO()
df.to_excel(towrite) # write to BytesIO buffer
towrite.seek(0)
print(towrite)
b''
print(type(towrite))
_io.BytesIO

如果你想查看类似字节的对象,请使用getvalue

print(towrite.getvalue())
b'PK\x03\x04\x14\x00\x00\x00\x08\x00\x00\x00!\x00<\xb

关于pandas - 将 Pandas DataFrame 转换为类似字节的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52089872/

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