Show DataFrame as table in iPython Notebook

I am using iPython notebook. When I do this:

df 

I get a beautiful table with cells. However, if I do this:

 df1 df2 

he does not print the first beautiful table. If I try this:

 print df1 print df2 

It prints the table in a different format, which spills the columns and makes the output very high.

Is there a way to get it to print beautiful tables for both datasets?

+177
pandas printing ipython-notebook jupyter-notebook display
Nov 11 '14 at 19:40
source share
5 answers

You will need to use the HTML() or display() functions from the IPython display module:

 from IPython.display import display, HTML # Assuming that dataframes df1 and df2 are already defined: print "Dataframe 1:" display(df1) print "Dataframe 2:" display(HTML(df2.to_html())) 

Please note: if you just print df1.to_html() you will get raw HTML code.

You can also import from IPython.core.display with the same effect.

+291
Apr 16 '15 at 4:39 on
source share
 from IPython.display import display display(df) # OR print df.to_html() 
+40
Feb 13 '15 at 7:28
source share

This answer is based on tip 2 of this blog post: 28 Jupyter Notebook Tips, Tricks, and Labels

You can add the following code to the top of the laptop.

 from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" 

This tells Jupyter to print the results for any variable or statement on its own line. This way you can execute a cell containing only

 df1 df2 

and he "will print beautiful tables for both datasets."

+31
Feb 22 '17 at 13:26
source share

It seems you can just display both dfs using the comma between them on the display. I noticed this on some laptops on github. This code is from Jake VanderPlas laptop.

 class display(object): """Display HTML representation of multiple objects""" template = """<div style="float: left; padding: 10px;"> <p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1} </div>""" def __init__(self, *args): self.args = args def _repr_html_(self): return '\n'.join(self.template.format(a, eval(a)._repr_html_()) for a in self.args) def __repr__(self): return '\n\n'.join(a + '\n' + repr(eval(a)) for a in self.args) 

display('df', "df2")

+4
Apr 14 '17 at 23:04 on
source share

I prefer not to mess with HTML and use as much of the built-in infrastructure as possible. You can use the output widget with an Hbox or VBox:

 import ipywidgets as widgets from IPython import display import pandas as pd import numpy as np # sample data df1 = pd.DataFrame(np.random.randn(8, 3)) df2 = pd.DataFrame(np.random.randn(8, 3)) # create output widgets widget1 = widgets.Output() widget2 = widgets.Output() # render in output widgets with widget1: display.display(df1) with widget2: display.display(df2) # create HBox hbox = widgets.HBox([widget1, widget2]) # render hbox hbox 

This outputs:

enter image description here

+4
Mar 04 '19 at 6:11
source share



All Articles