Wayne Werner Wayne Werner - 2 months ago 42
Python Question

How do I output lists as a table in Jupyter notebook?

I know that I've seen some example somewhere before but for the life of me I cannot find it when googling around.

I have some rows of data:

data = [[1,2,3],
[4,5,6],
[7,8,9],
]


And I want to output this data in a table, e.g.

+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+
| 7 | 8 | 9 |
+---+---+---+


Obviously I could use a library like prettytable or download pandas or something but I'm very disinterested in doing that.

I just want to output my rows as tables in my Jupyter notebook cell. How do I do this?

Answer

I finally re-found the jupyter/IPython documentation that I was looking for.

I needed this:

 from IPython.display import HTML, display

 data = [[1,2,3],
         [4,5,6],
         [7,8,9],
         ]

 display(HTML(
    '<table><tr>{}</tr></table>'.format(
        '</tr><tr>'.join(
            '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in data)
        )
 ))

(I may have slightly mucked up the comprehensions, but display(HTML('some html here')) is what we needed)