问题
I want to know how to download as a CSV file a Pandas Dataframe when I'm using a Jupyter Notebok in Watson Studio.
回答1:
I assume, you have created a pandas dataframe and now wondering where can you save the dataframe as csv file and then eventually download that saved csv file to your local machine.
You need to use project api to save the pandas dataframe as csv to project data asset as described in following link:-
# Save dataframe as csv file to storage
project.save_data(data=df.to_csv(index=False),file_name='iris1.csv',overwrite=True)
https://medium.com/ibm-data-science-experience/control-your-dsx-projects-using-python-c69e13880312
Once it is saved as data asset, you can use 3 dots menu next to this data asset in project to download that data asset to your local machine.
I hope it helps.
回答2:
An alternative is to code up a function that first base64-encodes the data and then embeds it into a download link:
# 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)
You would then call that function with the DataFrame as first parameter and it would return the download link. Something similar, but slightly more complicated, also works for Excel files. I have some background information on CSV and Excel download as well as a complete Gist in my blog entry.
来源:https://stackoverflow.com/questions/50572405/download-pandas-dataframe-in-watson-studio