Download Pandas DataFrame as a CSV file

A note when you're building a web server in Python and want to download Pandas DataFrame as a CSV file.

body = df.to_csv(index=False).encode('utf_8_sig')
headers = {
    'Content-Type': 'text/csv',
    'Content-Disposition': 'attachment; filename="data.csv"',
}
return web.Response(body=body, headers=headers)

This is an example of aiohttp Server, but I think it's the same for other frameworks.

--pandas.DataFrame.to_csv will return the CSV string as it is if you do not specify the output destination --If the CSV file is expected to be opened in Excel, encode it with ʻutf_8_sig(UTF-8 with BOM) so that the characters will not be garbled. --You can specify the file name at the time of download by adding theContent-Disposition` header. --Encoding is required when using Japanese file names

This is the point.

Recommended Posts

Download Pandas DataFrame as a CSV file
Read CSV file: pandas
Output the output result of sklearn.metrics.classification_report as a CSV file
Download csv file with python
[Pandas] Save DataFrame as JSON, load JSON as DataFrame
[Python] How to store a csv file as one-dimensional array data
DataFrame of pandas From creating a DataFrame from two lists to writing a file
Read CSV file with python (Download & parse CSV file)
AHC task (3) Read CSV as a dictionary
[Pandas_flavor] Add a method of Pandas DataFrame
Create a dataframe from excel using pandas
[pandas] .csv file reading and display method
How to read a CSV file with Python 2/3
[Introduction to Pandas] Read a csv file without a column name and give it a column name
Save the setting conditions as a CSV file using UDF Manager in OCTA
I tried reading a CSV file using Python
Draw a graph with matplotlib from a csv file
Save Pandas DataFrame as .csv.gz in Amazon S3
Download the csv file created by Google Colaboratory
A python script that imports a dated csv file into BigQuery as a time partition table
Every time I try to read a csv file using pandas, I get a numpy error.
When reading a csv file with read_csv of pandas, the first column becomes index
How to convert JSON file to CSV file with Python Pandas
How to display DataFrame as a table in Markdown
[Python] A memo to write CSV vertically with Pandas
Python script to create a JSON file from a CSV file
Reading pandas format file
Read Python csv file
Python application: Pandas # 3: Dataframe
Create a new csv with pandas based on the local csv
[Python] Open the csv file in the folder specified by pandas
Put the lists together in pandas to make a DataFrame
A handy function to add a column anywhere in a Pandas DataFrame
[Python] How to scrape a local html file and output it as CSV using Beautiful Soup