【发布时间】:2018-11-07 09:41:13
【问题描述】:
我想知道在 Watson Studio 中使用 Jupyter Notebok 时如何将 Pandas Dataframe 下载为 CSV 文件。
【问题讨论】:
标签: watson-studio
我想知道在 Watson Studio 中使用 Jupyter Notebok 时如何将 Pandas Dataframe 下载为 CSV 文件。
【问题讨论】:
标签: watson-studio
我假设,您已经创建了一个 pandas 数据框,现在想知道在哪里可以将数据框保存为 csv 文件,然后最终将保存的 csv 文件下载到您的本地计算机。
您需要使用项目 api 将 pandas 数据框另存为 csv 到项目数据资产,如以下链接所述:-
# 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
保存为数据资产后,您可以使用项目中此数据资产旁边的 3 点菜单将该数据资产下载到本地计算机。
希望对你有帮助。
【讨论】:
另一种方法是编写一个函数,首先对数据进行 base64 编码,然后将其嵌入到下载链接中:
# 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)
然后您可以使用 DataFrame 作为第一个参数调用该函数,它会返回下载链接。类似但稍微复杂一点的东西也适用于 Excel 文件。我有一些background information on CSV and Excel download as well as a complete Gist in my blog entry。
【讨论】: