Home > Back-end >  Exporting Pandas Dataframe as CSV
Exporting Pandas Dataframe as CSV

Time:03-08

This is a question concerning how to allow a user to export a Pandas dataframe to CSV format in Python 3.

For context, I have a Django view that accepts POST requests from jQuery, such that when a user clicks on a button on my website, it triggers a POST request to that Django view and performs some filtering to generate a Pandas dataframe. I want the users to be able to export the dataframe on their end, not into my personal local machine/project directory.

I make a sharp distinction between "downloading" and "exporting". Downloading can be easily done through the pd.to_csv method and basically saves the CSV file into a specified directory within my local machine (or my project folder, in fact). The problem is that the behavior I want is "exporting", which I define as when a user, upon clicking a button, is able to get the dataframe on their local machine.

The way I do "exporting" currently is by converting the Dataframe to an HTML table element, returning the HTML as the response of the POST request to jQuery, and use vanilla JS to inspect the table element to export the data on the user's end, following a protocol similar to How do I export html table data as .csv file?. The problem, however, is that when the dataframe grows too big, it becomes impossible to inspect the associated table element to generate a CSV file.

Any suggestion for exporting a Pandas dataframe to CSV is appreciated - it could be an original solution, in fact.

CodePudding user response:

try this in your view function

import csv
import pandas as pd

def get(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="{filename}.csv"'.format(filename='myname')
    writer = csv.writer(response)
    df = pd.DataFrame([{"name": "haha", "age": 18}, {"name": "haha", "age": 18}])
    writer.writerow([column for column in df.columns])
    writer.writerows(df.values.tolist())
    return response
        

CodePudding user response:

df.to_csv(diractory/file_name.csv')
  • Related