Download CSV from an iPython Notebook

后端 未结 6 1029
一个人的身影
一个人的身影 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:57

    A function that creates a csv download link, based on Coen Jonker's answer and similar to Yasin Zähringer's answer except that it uses IPython.display.FileLink so that there is no need to create html code.

    The function has an optional delete prompt so you can delete the file after download to keep the notebook server clean.

    # Import a module to create a data frame
    import pandas
    # Import a module to display a link to the file
    from IPython.display import FileLink
    # Import a module to delete the file
    import os
    # Create a download function
    def csv_download_link(df, csv_file_name, delete_prompt=True):
        """Display a download link to load a data frame as csv within a Jupyter notebook
    
        Parameters
        ----------
        df : pandas data frame
        csv_file_name : str
        delete_prompt : bool
        """
        df.to_csv(csv_file_name, index=False)
        display(FileLink(csv_file_name))
        if delete_prompt:
            a = input('Press enter to delete the file after you have downloaded it.')
            os.remove(csv_file_name)
    
    # Create an example data frame
    df = pandas.DataFrame({'x':[1,2,3],'y':['a','b','c']})
    # Use the function to diplay a download link
    csv_download_link(df, 'file_name.csv')
    

    This is mostly for people who use jupyter notebooks on their own machine. On a shared machine, the use of os.remove might be problematic depending on how you set up file write permissions.

提交回复
热议问题