Caleb Madrigal

Programming, Hacking, Math, and Art

 

Display List as Table in IPython Notebook

IPython Notebook provides hook methods like _repr_html_ which can be defined by Python objects to allow richer representations. Here's an example:

In [1]:
class ListTable(list):
    """ Overridden list class which takes a 2-dimensional list of 
        the form [[1,2,3],[4,5,6]], and renders an HTML Table in 
        IPython Notebook. """
    
    def _repr_html_(self):
        html = ["<table>"]
        for row in self:
            html.append("<tr>")
            
            for col in row:
                html.append("<td>{0}</td>".format(col))
            
            html.append("</tr>")
        html.append("</table>")
        return ''.join(html)
In [23]:
import random
table = ListTable()
table.append(['x', 'y', 'x-y', '(x-y)^2'])
for i in xrange(7):
    x = random.uniform(0, 10)
    y = random.uniform(0, 10)
    table.append([x, y, x-y, (x-y)**2])
table
Out[23]:
xyx-y(x-y)^2
7.131001150966.414548906890.7164522440680.51330381803
2.205109836499.08155522913-6.8764453926447.285501238
6.028809502670.4523853999795.576424102731.0965057731
2.400551150694.26670665801-1.866155507323.48253637751
8.045378157429.77588474573-1.730506588312.99465305217
8.015288222531.957247896666.0580403258736.6998525898
0.9055181535361.91330142109-1.007783267551.01562711436

The 6 rich representions currently supported by IPython Notebook are:

  • HTML
  • JSON
  • PNG
  • JPEG
  • SVG
  • LaTeX

For more information, check out this IPython Notebook (by the IPython team).

Comments