【问题标题】:Convert Pandas DataFrame to bytes-like object将 Pandas DataFrame 转换为类似字节的对象
【发布时间】:2019-02-04 23:25:55
【问题描述】:

您好,我正在尝试将我的 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' 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:\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'

【问题讨论】:

  • 我只是测试了你的代码,并且在 windows 下的 pandas 0.23.4 中运行良好。
  • jezrael,当我打印(towrite) 时它只打印b'' 为什么不打印b'/x0/....' 我需要返回二进制数据,我怎样才能得到它
  • @pyd - 我通过df = pd.read_excel(towrite) 对其进行测试,然后它返回DataFrame。也许一些python问题?我在 python 3.6 下测试它
  • 我通过towrite.getvalue()解决了它,感谢您的帮助@jezrael

标签: pandas binary pickle bytesio


【解决方案1】:

我通过将 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

【讨论】:

【解决方案2】:

泡菜

Pickle 是 Pandas 数据帧的可重现格式,但仅供受信任用户内部使用。出于安全原因,它不用于与不受信任的用户共享。

import pickle

# Export:
my_bytes = pickle.dumps(df, protocol=4)

# Import:
df_restored = pickle.loads(my_bytes)

这是用 Pandas 1.1.2 测试的。不幸的是,对于一个非常大的数据帧,这失败了,但是起作用的是单独腌制和并行压缩每一列,然后腌制这个列表。或者,您可以腌制大数据帧的块。

CSV

如果您必须使用 CSV 表示:

df.to_csv(index=False).encode()

请注意,使用 CSV 时会丢失各种数据类型。

镶木地板

this answer。请注意,使用 parquet 时会转换各种数据类型。

Excel

尽量避免使用它,因为它限制了max number of rows and columns

【讨论】:

  • 谢谢。我一直允许用户保存 dtypes 的字典,但在阅读本文后,我将切换到坚持 parquet towardsdatascience.com/…
猜你喜欢
  • 2018-02-14
  • 2015-09-15
  • 2017-01-13
  • 1970-01-01
  • 2021-02-23
  • 2021-05-13
  • 2017-03-16
  • 2019-01-14
  • 1970-01-01
相关资源
最近更新 更多