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?
To show the full data without any hiding, you can use pd. set_option('display. max_rows', 500) and pd.
Jupyter Notebook can print the output of each cell just below the cell. When you have a lot of output you can reduce the amount of space it takes up by clicking on the left side panel of the output. This will turn the output into a scrolling window.
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 |
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
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)
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 │
└───┴───────┴─────┘
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With