Convert Pandas DataFrame to bytes-like object

前端 未结 2 910
孤城傲影
孤城傲影 2021-01-04 23:05

Hi I am trying to convert my df to binary and store it in a variable.

my_df:

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

my code

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 23:44

    I solved the issue by upgrading pandas to newer version.

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

    if you want to see the bytes-like object use getvalue,

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

提交回复
热议问题