如何将Pandas DataFrame转换为类似字节的对象
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将Pandas DataFrame转换为类似字节的对象相关的知识,希望对你有一定的参考价值。
您好我正在尝试将我的df转换为二进制并将其存储在变量中。
my_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' object has no attribute '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:ProgramDataAnaconda3libsite-packagespandascoreframe.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:ProgramDataAnaconda3libsite-packagespandasioformatsexcel.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'PKx03x04x14x00x00x00x08x00x00x00!x00<xb
以上是关于如何将Pandas DataFrame转换为类似字节的对象的主要内容,如果未能解决你的问题,请参考以下文章
将Dask包的Pandas DataFrame转换为单个Dask DataFrame
如何将 sql 查询转换为 Pandas Dataframe 和 PySpark Dataframe
如何将 scala spark.sql.dataFrame 转换为 Pandas 数据框