熊猫在BytesIO中将df存储到csv

时间:2019-05-21 02:12:36

标签: python pandas io

我想将dfcsv的输出存储在BytesIo()(不是StringIO)的内存对象中,然后将其压缩,这是我的尝试:

import pandas as pd
import numpy as np
import io
import zipfile
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
s_buf = io.BytesIO()
df.to_csv(s_buf)
s_buf.seek(0)
localfile= io.BytesIO()
zf = zipfile.ZipFile(localfile, mode="w",compression=zipfile.ZIP_DEFLATED)
zf.writestr(localfile, s_buf.read())
zf.close()
with open("D:/my_zip.zip", "wb") as f: # use `wb` mode
    f.write(zf.getvalue())

1 个答案:

答案 0 :(得分:1)

我认为这会有所帮助:-

import gzip
from io import BytesIO
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
b_buf = BytesIO()
with gzip.open(b_buf, 'wb') as f:
    f.write(df.to_csv().encode())
b_buf.seek(0)
with open("my_zip.zip", "wb") as f:
    f.write(b_buf.getvalue())