pyd*_*pyd 16 binary pickle bytesio pandas
嗨,我正在尝试将我的 df 转换为二进制并将其存储在一个变量中。
我的_df:
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
Run Code Online (Sandbox Code Playgroud)
我的代码:
import io
towrite = io.BytesIO()
df.to_excel(towrite) # write to BytesIO buffer
towrite.seek(0) # reset pointer
Run Code Online (Sandbox Code Playgroud)
我正进入(状态 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'
Run Code Online (Sandbox Code Playgroud)
pyd*_*pyd 21
我通过将 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
Run Code Online (Sandbox Code Playgroud)
如果你想看到类似字节的对象使用getvalue,
print(towrite.getvalue())
b'PK\x03\x04\x14\x00\x00\x00\x08\x00\x00\x00!\x00<\xb
Run Code Online (Sandbox Code Playgroud)
Pickle是 Pandas 数据帧的可重现格式,但它仅供受信任的用户内部使用。由于安全原因,它不用于与不受信任的用户共享。
import pickle
# Export:
my_bytes = pickle.dumps(df, protocol=4)
# Import:
df_restored = pickle.loads(my_bytes)
Run Code Online (Sandbox Code Playgroud)
这是用 Pandas 1.1.2 测试的。不幸的是,这对于一个非常大的数据帧失败了,但随后的工作是单独酸洗和并行压缩每一列,然后酸洗这个列表。或者,您可以腌制大数据帧的块。
如果您必须使用 CSV 表示:
df.to_csv(index=False).encode()
Run Code Online (Sandbox Code Playgroud)
请注意,使用 CSV 时会丢失各种数据类型。
看到这个答案。请注意,使用 parquet 时会转换各种数据类型。
大多数情况下避免使用它,因为它限制了最大行数和列数。
小智 6
我需要通过 boto3 将文件对象上传到 S3,它不接受 pandas bytes 对象。因此,根据 Asclepius 的答案,我将对象转换为 BytesIO,例如:
from io import BytesIO
data = BytesIO(df.to_csv(index=False).encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11503 次 |
| 最近记录: |