Last active
June 6, 2023 12:51
-
-
Save data-henrik/f0f780147a646e34d7720c5982cc46ef to your computer and use it in GitHub Desktop.
Python snippet to download pandas Data Frame as CSV or Excel from notebook in IBM Watson Studio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Define functions to download as CSV or Excel | |
from IPython.display import HTML | |
import pandas as pd | |
import base64, io | |
# Download as CSV: data frame, optional title and filename | |
def create_download_link_csv(df, title = "Download CSV file", filename = "data.csv"): | |
# generate in-memory CSV, then base64-encode it | |
csv = df.to_csv(index=False) | |
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) | |
# Download as Excel: data frame, optional title and filename | |
def create_download_link_excel(df, title = "Download Excel file", filename = "data.xlsx"): | |
# to_excel() does not work to string buffer directly | |
output = io.BytesIO() | |
# Use the BytesIO object as the filehandle | |
writer = pd.ExcelWriter(output, engine='xlsxwriter') | |
# Write the data frame to the BytesIO object and save it | |
df.to_excel(writer, sheet_name='Sheet1') | |
writer.save() | |
excel_data = output.getvalue() | |
b64 = base64.b64encode(excel_data) | |
payload = b64.decode() | |
html = '<a download="{filename}" href="data:text/xml;base64,{payload}" target="_blank">{title}</a>' | |
html = html.format(payload=payload,title=title,filename=filename) | |
return HTML(html) | |
# Later, in another cell: | |
# Download as CSV | |
create_download_link_csv(usa_df,"Download my data","sample.csv") | |
# Download as MS Excel file | |
create_download_link_excel(usa_df,"Download data for Excel","allcountry.xlsx") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment