iPython - Display full dataframe in new tab

2019-05-01 17:13发布

问题:

in Jupyter, using Pandas, is there a way to show an entire dataframe in a new tab of the navigator?

When I want to control a dataframe, I usually export it in .csv and then open in Excel.
I am looking for a faster way, but I am not willing to display the full frame into my Notebook, as it make it unreadable.

Since the normal output of a frame is an HTML table, I wonder how we can show this table elsewhere than in the Notebook.

回答1:

You could use javascript together with ipython.display to open a new window and show the whole dataframe in it. The advantage is that you can do that several times without the need to create actual HTML files in between or to reload the window. My solution for that question automatically updates the opened window and kind of emulates the View() function from R/RStudio:

from IPython.display import HTML
def View(df):
    css = """<style>
    table { border-collapse: collapse; border: 3px solid #eee; }
    table tr th:first-child { background-color: #eeeeee; color: #333; font-weight: bold }
    table thead th { background-color: #eee; color: #000; }
    tr, th, td { border: 1px solid #ccc; border-width: 1px 0 0 1px; border-collapse: collapse;
    padding: 3px; font-family: monospace; font-size: 10px }</style>
    """
    s  = '<script type="text/Javascript">'
    s += 'var win = window.open("", "Title", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=780, height=200, top="+(screen.height-400)+", left="+(screen.width-840));'
    s += 'win.document.body.innerHTML = \'' + (df.to_html() + css).replace("\n",'\\') + '\';'
    s += '</script>'
    return(HTML(s+css))

View(df)


回答2:

I found my answer: save the frame as a html page with .to_html and then open it with regular python function webbrowser:

import webbrowser
...
df.to_html("frame.html")
url = "http://localhost:8888/files/notebook/frame.html"
webbrowser.open(url,new=2)