我運行iPython Notebook服務器,並希望用戶能夠將熊貓數據框下載爲csv文件,以便他們可以在自己的環境中使用它。沒有個人數據,所以如果解決方案涉及將文件寫入服務器(我可以這樣做)然後下載該文件,我會很高興。從iPython筆記本下載CSV
回答
可以使用的事實,筆記本電腦可以爲對象顯示HTML和數據的URL,做一個CSV下載的內容:
import urllib
class CSV(object):
def _repr_html_(self):
html = []
html.append("{},{},{}".format(
"user",
"age",
"city"
)
)
html.append("{},{},{}".format(
"Alice",
"39",
"New York"
)
)
html.append("{},{},{}".format(
"Bob",
"30",
"Denver"
)
)
html.append("{},{},{}".format(
"Carol",
"27",
"Tulsa"
)
)
export = '\n'.join(html)
export = urllib.quote(export.encode("utf-8"))
csvData = 'data:application/csv;charset=utf-8,' + export
return "<a download='export.csv' href='{}' target='_blank'>csv file</a>".format(csvData)
CSV()
如何使用從IPython中的Filelinks類?我使用它來直接從Jupyter筆記本提供數據訪問。假設你的數據在數據幀大熊貓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/')
運行此作爲筆記本電池,其結果將是鏈接文件列表直接從筆記本電腦下載。當然,'/path/to'
需要可供筆記本用戶使用。
如果你想避免在服務器上存儲的CSV,您可以使用在客戶端創建CSV此Javascript替代:
from IPython.display import Javascript
js_download = """
var csv = '%s';
var filename = 'results.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
""" % data_in_dataframes.to_csv(index=False).replace('\n','\\n').replace("'","\'")
Javascript(js_download)
基本上,它創建從PD在python CSV字符串數據幀並在一個小型的js腳本中使用它,並打開一個保存對話框將其保存在用戶計算機上。我在我的iPython env中測試過,它的功能就像一個魅力!
請注意,我正在逃避\n
。如果我不這樣做,那麼js腳本字符串將具有寫在多行上的CSV變量。
例如,print "var csv = '%s'" % industries_revenues.to_csv(index=False).replace('\n','\\n')
結果如下:
var csv = 'Industry,sum_Amount\nBanking,65892584.0\n(...)Finance,20211917.0\n'
代替print "var csv = '%s'" % industries_revenues.to_csv(index=False)
沒有\n
逃逸是一個多內襯,因此出錯的JavaScript結果:
var csv = 'Industry,sum_Amount
Banking,65892584.0
(...)
Finance,20211917.0
'
我也難逃'
不在JavaScript中打破可變字符串。
我收到Javascript錯誤添加輸出! SyntaxError:missing;在聲明之前 查看您的瀏覽器Javascript控制檯瞭解更多詳情。 – AlexLordThorsen
對於您可以使用下面的代碼不會太大表:
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)
- 1. 從URL加載iPython/Jupyter筆記本
- 2. 分配從IPython筆記本
- 3. IPython筆記本錯誤:加載筆記本時出錯
- 4. 加載IPython Jupyter筆記本時出錯:
- 5. iPython筆記本沒有加載
- 6. 「load_breast_cancer」無法加載IPython的筆記本
- 7. Jupyter(IPython的筆記本),隱藏加載
- 8. Ipython筆記本無法加載
- 9. 運行IPython筆記本
- 10. IPython筆記本遊戲
- 11. Heroku上的IPython筆記本
- 12. 測試IPython筆記本
- 13. IPython筆記本安全
- 14. ipython筆記本中的ASCIIMathMl
- 15. 在IPython的筆記本
- 16. 在IPython中/ Jupyter筆記本
- 17. ipython筆記本中的OptionParser?
- 18. Ipython筆記本丟失
- 19. ipython筆記本未啓動
- 20. IPython筆記本在生產
- 21. 從ipython筆記本運行scp
- 22. 從python模塊中使用ipython magics在筆記本中加載
- 23. 在IPython的另一個筆記本中包含筆記本?
- 24. 無法打開IPython筆記本中的現有筆記本
- 25. iPython筆記本自動創建新的空白筆記本
- 26. 在現有筆記本服務器上打開ipython筆記本
- 27. 在anaconda ipython筆記本命令打開jupyter筆記本?
- 28. 如何在ipython筆記本中創建新筆記本?
- 29. IPython的筆記本電腦連接到外部的筆記本
- 30. Groovy筆記本電腦相當於IPython筆記本
我不認爲IPython中具有任何功能來解決你在問什麼,但你總是代碼Python中的例程執行下載,並將其包含在用戶的筆記本中。只是一個想法。希望能幫助到你。 – lrnzcig
謝謝lrnzcig:這就是它對我的看法。我可以嘗試你的建議。 –
嗨,是否可以使用'pd.to_csv()'將數據框寫入csv,然後直接從ipython服務器打開csv,然後選擇file> Download? – johnchase