Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Storing df to csv in BytesIO

Tags:

python

io

pandas

I want to store the output of df to csv in Memory Object of BytesIo() (Not StringIO) and then zip it and here is my attempt:

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())
like image 488
Virus Avatar asked May 21 '19 02:05

Virus


People also ask

How do I export DF from pandas to CSV?

By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.

Can pandas write to CSV?

Pandas is a very powerful and popular framework for data analysis and manipulation. One of the most striking features of Pandas is its ability to read and write various types of files including CSV and Excel.

What is CSV buffer?

The concept is the same, a table with functions to create or read files, this time XML/CSV files instead of Excel files. Just like with the Excel Buffer table, the XML buffer and CSV buffer table should be used as temporary tables.

What function do we need to use to convert DataFrame to .CSV file?

Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.


1 Answers

I think this would be helpful:-

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())
like image 163
Tech at The Sparks Foundation Avatar answered Sep 20 '22 18:09

Tech at The Sparks Foundation