Skip to content

Instantly share code, notes, and snippets.

@frank-yifei-wang
Created August 29, 2019 16:55
Show Gist options
  • Save frank-yifei-wang/b627019cd73b768b0dd82624f5260d5b to your computer and use it in GitHub Desktop.
Save frank-yifei-wang/b627019cd73b768b0dd82624f5260d5b to your computer and use it in GitHub Desktop.
View Pandas DataFrame in a pop-up window/tab rendered with JavaScript and CSS code. Similar to RStudio's 'View' function.
from IPython.display import HTML
def view(df=None, title: str = 'DataFrame', fs: int = 12):
"""View Pandas DataFrame in a pop-up window/tab rendered with JavaScript and CSS code. Similar to RStudio's 'View' function.
Args:
df: DataFrame to view
title: title of the pop-up (to help distinguish if there are multiple pop-ups)
fs: font size in pixels
Examples:
>>> view(df)
>>> filename = 'my_dataset.csv'
>>> df = pd.read_csv(filename)
>>> view(df, fs=14, title='DataFrame from: ' + filename)
"""
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: font_size }</style>
""".replace('font_size', str(fs)+'px')
s = '<script type="text/Javascript">'
s += 'var win = window.open("", "_blank", "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 += 'setTimeout(function(){ win.document.title = "' + title + '"; }, 0);'
s += 'win.document.body.innerHTML = \'' + (df.to_html() + css).replace("\n",'\\') + '\';'
s += '</script>'
return(HTML(s+css))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment