Skip to content

Instantly share code, notes, and snippets.

@taldcroft
Last active May 20, 2020 13:54
Show Gist options
  • Save taldcroft/7597d01e150a5a0894f931ee5bf23172 to your computer and use it in GitHub Desktop.
Save taldcroft/7597d01e150a5a0894f931ee5bf23172 to your computer and use it in GitHub Desktop.
Annotated data tables
table {
table-layout: fixed;
border-collapse: collapse;
border: 3px solid black;
}
th, td {
padding: 5px;
border: 1px solid black;
}
td.bad {
color: red;
}
td.align-right {
text-align: right;
}
#!/usr/bin/env python3
from astropy.table import Table
import jinja2
import string
import numpy as np
data = Table()
n = 10
data['name'] = list(string.ascii_uppercase[:n])
data['val1'] = np.random.uniform(0, 100, n)
data['val2'] = np.random.uniform(0, 100, n)
data['val1'].format = '.2f'
data['val2'].format = '.3f'
status = Table()
status['name'] = [len(x) > 5 for x in data['name']]
status['val1'] = data['val1'] > 50
status['val2'] = data['val2'] > 20
fmt = Table()
td_class = Table()
for name in data.colnames:
td_classes_list = []
for ii in range(len(data)):
td_classes = []
if status[name][ii]:
td_classes.append('bad')
if data[name].dtype.kind in ('i', 'f'):
td_classes.append('align-right')
td_classes_list.append(td_classes)
print(td_classes_list)
td_class[name] = [' '.join(x) for x in td_classes_list]
fmt[name] = data[name].pformat(show_name=False)
with open('template.html') as f:
template = jinja2.Template(f.read())
with open('index.html', 'w') as f:
f.write(template.render(data=fmt, td_class=td_class))
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<table>
<tr>
{% for name in data.colnames -%}
<th>{{name}}</th>
{% endfor -%}
</tr>
{% for ii in range(data|length) -%}
<tr>
{% for name in data.colnames -%}
<td{% if td_class[name][ii] %} class="{{td_class[name][ii]}}"{% endif %}>{{ data[name][ii] }}</td>
{% endfor -%}
</tr>
{% endfor -%}
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment