Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download CSV from an iPython Notebook

I run an iPython Notebook server, and would like users to be able to download a pandas dataframe as a csv file so that they can use it in their own environment. There's no personal data, so if the solution involves writing the file at the server (which I can do) and then downloading that file, I'd be happy with that.

like image 342
Tom Slee Avatar asked Aug 08 '15 14:08

Tom Slee


People also ask

How do I download a dataset from Jupyter Notebook?

Step 1: Visit the Kaggle website and Select the Dataset tab. Step 2: Select any Dataset and Click on the Download. Step 3: The downloaded file will be in Zip form, Unzip it. Step 4: Upload to Your Jupyter Notebook.

How do I export files from a Jupyter Notebook?

The Jupyter Notebook has an option to export the notebook to many formats. It can be accessed by clicking File -> Download as -> PDF via LaTeX (or PDF via HTML - not visible in the screenshot). This approach requires you to install some additional packages.


2 Answers

How about using the FileLinks class from IPython? I use this to provide access to data directly from Jupyter notebooks. Assuming your data is in pandas dataframe p_df:

from IPython.display import FileLink, FileLinks  p_df.to_csv('/path/to/data.csv', index=False) p_df.to_excel('/path/to/data.xlsx', index=False)  FileLinks('/path/to/') 

Run this as a notebook cell and the result will be a list of links to files downloadable directly from the notebook. '/path/to' needs to be accessible for the notebook user of course.

like image 111
Coen Jonker Avatar answered Sep 17 '22 18:09

Coen Jonker


For not too large tables you can use the following code:

import base64 import pandas as pd from IPython.display import HTML  def create_download_link( df, title = "Download CSV file", filename = "data.csv"):     csv = df.to_csv()     b64 = base64.b64encode(csv.encode())     payload = b64.decode()     html = '<a download="{filename}" href="data:text/csv;base64,{payload}" target="_blank">{title}</a>'     html = html.format(payload=payload,title=title,filename=filename)     return HTML(html)  df = pd.DataFrame(data = [[1,2],[3,4]], columns=['Col 1', 'Col 2']) create_download_link(df) 
like image 43
Yasin Zähringer Avatar answered Sep 17 '22 18:09

Yasin Zähringer