How do I output lists as a table in Jupyter notebook?
Solution 1:
There is a nice trick: wrap the data with pandas DataFrame.
import pandas as pd
data = [[1, 2], [3, 4]]
pd.DataFrame(data, columns=["Foo", "Bar"])
It displays data like:
| Foo | Bar |
0 | 1 | 2 |
1 | 3 | 4 |
Solution 2:
I just discovered that tabulate has a HTML option and is rather simple to use.
Update: As of Jupyter v6 and later, the returned table
should just render via the output cell:
import tabulate
data = [["Sun",696000,1989100000],
["Earth",6371,5973.6],
["Moon",1737,73.5],
["Mars",3390,641.85]]
table = tabulate.tabulate(data, tablefmt='html')
table
As for Jupyter v5 or earlier, you may need to be more explicit, similar to Werner's answer:
from IPython.display import HTML, display
display(HTML(table))
Still looking for something simple to use to create more complex table layouts like with latex syntax and formatting to merge cells and do variable substitution in a notebook:
Allow references to Python variables in Markdown cells #2958
Solution 3:
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)
Solution 4:
tabletext fit this well
import tabletext
data = [[1,2,30],
[4,23125,6],
[7,8,999],
]
print tabletext.to_text(data)
result:
┌───┬───────┬─────┐
│ 1 │ 2 │ 30 │
├───┼───────┼─────┤
│ 4 │ 23125 │ 6 │
├───┼───────┼─────┤
│ 7 │ 8 │ 999 │
└───┴───────┴─────┘
Solution 5:
If you don't mind using a bit of html, something like this should work.
from IPython.display import HTML, display
def display_table(data):
html = "<table>"
for row in data:
html += "<tr>"
for field in row:
html += "<td><h4>%s</h4></td>"%(field)
html += "</tr>"
html += "</table>"
display(HTML(html))
And then use it like this
data = [[1,2,3],[4,5,6],[7,8,9]]
display_table(data)