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
I used to have the same problem. I could not find anything that would help me so I ended up making the class PrintTable
--code below. There is also an output. The usage is simple:
ptobj = PrintTable(yourdata, column_captions, column_widths, text_aligns)
ptobj.print()
or in one line:
PrintTable(yourdata, column_captions, column_widths, text_aligns).print()
Output:
-------------------------------------------------------------------------------------------------------------
Name | Column 1 | Column 2 | Column 3 | Column 4 | Column 5
-------------------------------------------------------------------------------------------------------------
Very long name 0 | 0 | 0 | 0 | 0 | 0
Very long name 1 | 1 | 2 | 3 | 4 | 5
Very long name 2 | 2 | 4 | 6 | 8 | 10
Very long name 3 | 3 | 6 | 9 | 12 | 15
Very long name 4 | 4 | 8 | 12 | 16 | 20
Very long name 5 | 5 | 10 | 15 | 20 | 25
Very long name 6 | 6 | 12 | 18 | 24 | 30
Very long name 7 | 7 | 14 | 21 | 28 | 35
Very long name 8 | 8 | 16 | 24 | 32 | 40
Very long name 9 | 9 | 18 | 27 | 36 | 45
Very long name 10 | 10 | 20 | 30 | 40 | 50
Very long name 11 | 11 | 22 | 33 | 44 | 55
Very long name 12 | 12 | 24 | 36 | 48 | 60
Very long name 13 | 13 | 26 | 39 | 52 | 65
Very long name 14 | 14 | 28 | 42 | 56 | 70
Very long name 15 | 15 | 30 | 45 | 60 | 75
Very long name 16 | 16 | 32 | 48 | 64 | 80
Very long name 17 | 17 | 34 | 51 | 68 | 85
Very long name 18 | 18 | 36 | 54 | 72 | 90
Very long name 19 | 19 | 38 | 57 | 76 | 95
-------------------------------------------------------------------------------------------------------------
The code for the class PrintTable
# -*- coding: utf-8 -*-
# Class
class PrintTable:
def __init__(self, values, captions, widths, aligns):
if not all([len(values[0]) == len(x) for x in [captions, widths, aligns]]):
raise Exception()
self._tablewidth = sum(widths) + 3*(len(captions)-1) + 4
self._values = values
self._captions = captions
self._widths = widths
self._aligns = aligns
def print(self):
self._printTable()
def _printTable(self):
formattext_head = ""
formattext_cell = ""
for i,v in enumerate(self._widths):
formattext_head += "{" + str(i) + ":<" + str(v) + "} | "
formattext_cell += "{" + str(i) + ":" + self._aligns[i] + str(v) + "} | "
formattext_head = formattext_head[:-3]
formattext_head = " " + formattext_head.strip() + " "
formattext_cell = formattext_cell[:-3]
formattext_cell = " " + formattext_cell.strip() + " "
print("-"*self._tablewidth)
print(formattext_head.format(*self._captions))
print("-"*self._tablewidth)
for w in self._values:
print(formattext_cell.format(*w))
print("-"*self._tablewidth)
Demonstration
# Demonstration
headername = ["Column {}".format(x) for x in range(6)]
headername[0] = "Name"
data = [["Very long name {}".format(x), x, x*2, x*3, x*4, x*5] for x in range(20)]
PrintTable(data, \
headername, \
[70, 10, 10, 10, 10, 10], \
["<",">",">",">",">",">"]).print()
I just discovered that tabulate has a HTML option and is rather simple to use.
Quite similar to Wayne Werner's answer:
from IPython.display import HTML, display
import tabulate
table = [["Sun",696000,1989100000],
["Earth",6371,5973.6],
["Moon",1737,73.5],
["Mars",3390,641.85]]
display(HTML(tabulate.tabulate(table, tablefmt='html')))
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 │
└───┴───────┴─────┘
A general purpose set of functions to render any python data structure (dicts and lists nested together) as HTML.
from IPython.display import HTML, display
def _render_list_html(l):
o = []
for e in l:
o.append('<li>%s</li>' % _render_as_html(e))
return '<ol>%s</ol>' % ''.join(o)
def _render_dict_html(d):
o = []
for k, v in d.items():
o.append('<tr><td>%s</td><td>%s</td></tr>' % (str(k), _render_as_html(v)))
return '<table>%s</table>' % ''.join(o)
def _render_as_html(e):
o = []
if isinstance(e, list):
o.append(_render_list_html(e))
elif isinstance(e, dict):
o.append(_render_dict_html(e))
else:
o.append(str(e))
return '<html><body>%s</body></html>' % ''.join(o)
def render_as_html(e):
display(HTML(_render_as_html(e)))