Download CSV from an iPython Notebook

后端 未结 6 1030
一个人的身影
一个人的身影 2020-12-02 23:17

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

6条回答
  •  一个人的身影
    2020-12-02 23:44

    You can use the fact that the notebook can display html for objects, and data urls, to make the content of a csv downloadable:

    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 "csv file".format(csvData)
    
    CSV()
    

提交回复
热议问题