HTML export#
To get the HTML representation of a Pandas DataFrame df as an interactive DataTable, you can use to_html_datatable as below:
from IPython.display import HTML, display
import itables
df = itables.sample_dfs.get_countries()
html = itables.to_html_datatable(df.head(3), display_logo_when_loading=False)
You can then save the html variable to a text file (note: if you’re writing an HTML application, you could consider using Shiny or Streamlit instead), or print it:
print(html)
<!--| quarto-html-table-processing: none -->
<table id="itables_e58d3521_b77c_47c4_ab97_d2fdc94fd7a8"><tbody><tr>
<td style="vertical-align:middle; text-align:left">
Loading ITables v2.7.0 from the internet...
(need <a href=https://mwouts.github.io/itables/troubleshooting.html>help</a>?)</td>
</tr></tbody></table>
<link href="https://www.unpkg.com/dt_for_itables@2.5.0/dt_bundle.css" rel="stylesheet">
<script type="module">
import { ITable, jQuery as $ } from 'https://www.unpkg.com/dt_for_itables@2.5.0/dt_bundle.js';
document.querySelectorAll("#itables_e58d3521_b77c_47c4_ab97_d2fdc94fd7a8:not(.dataTable)").forEach(table => {
if (!(table instanceof HTMLTableElement))
return;
let dt_args = {"layout": {"topStart": null, "topEnd": null, "bottomStart": null, "bottomEnd": null}, "order": [], "text_in_header_can_be_selected": true, "classes": ["display", "nowrap", "compact"], "style": {"table-layout": "auto", "width": "auto", "margin": "auto", "caption-side": "bottom"}, "table_html": "<table><thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>region</th>\n <th>country</th>\n <th>capital</th>\n <th>longitude</th>\n <th>latitude</th>\n </tr>\n <tr>\n <th>code</th>\n <th></th>\n <th></th>\n <th></th>\n <th></th>\n <th></th>\n </tr>\n </thead></table>", "data_json": "[[\"AW\", \"Latin America & Caribbean \", \"Aruba\", \"Oranjestad\", [\"-70.0167\", 1], [\"12.51670\", 2]], [\"AF\", \"South Asia\", \"Afghanistan\", \"Kabul\", [\"69.1761\", 3], [\"34.52280\", 3]], [\"AO\", \"Sub-Saharan Africa \", \"Angola\", \"Luanda\", [\"13.2420\", 2], [\"-8.81155\", 1]]]", "columnDefs": [{"targets": [4, 5], "render": "\n function (data, type, row, meta) {\n return type === 'sort' ? data[1] : data[0];\n }\n "}], "keys_to_be_evaluated": [["columnDefs", 0, "render"]]};
new ITable(table, dt_args);
});
</script>
or display it, like show does:
display(HTML(html))
| Loading ITables v2.7.0 from the internet... (need help?) |
The connected argument
The to_html_datatable function has a connected argument which defaults to what you set in init_notebook_mode (it’s True if you didn’t call it).
With
connected=Trueyou get an autonomous HTML fragment that loadsdt_for_itablesfrom the InternetWith
connected=False, the HTML snippet works only after you add the output ofgenerate_init_offline_itables_html()to your HTML document