Elie Brosset
Add app
6739f59
import dash_bootstrap_components as dbc
import pandas as pd
from dash import dash_table, html
def table_type(df_column):
if isinstance(df_column.dtype, pd.DatetimeTZDtype):
return ("datetime",)
elif (
isinstance(df_column.dtype, pd.StringDtype)
or isinstance(df_column.dtype, pd.BooleanDtype)
or isinstance(df_column.dtype, pd.CategoricalDtype)
or isinstance(df_column.dtype, pd.PeriodDtype)
):
return "text"
elif (
isinstance(df_column.dtype, pd.SparseDtype)
or isinstance(df_column.dtype, pd.IntervalDtype)
or isinstance(df_column.dtype, pd.Int8Dtype)
or isinstance(df_column.dtype, pd.Int16Dtype)
or isinstance(df_column.dtype, pd.Int32Dtype)
or isinstance(df_column.dtype, pd.Int64Dtype)
):
return "numeric"
else:
return "any"
def number_format(number):
return f"{number:,}".replace(",", " ")
def make_df_table(df, selected_rows=None, id="datatable", page_size=10):
if selected_rows is None:
selected_rows = []
df["id"] = df.index
return dash_table.DataTable(
columns=[
{"name": i, "id": i, "type": table_type(df[i])}
for i in df.columns
if i != "id"
],
data=df.to_dict("records"),
css=[{"selector": "table", "rule": "table-layout: fixed"}],
selected_rows=selected_rows,
id=id,
style_data_conditional=[
{
"if": {"state": "active"},
"backgroundColor": "rgba(5, 51, 69)",
"border": "1px solid rgba(5, 51, 69)",
}
],
active_cell={
"row": 0,
"column": 0,
"column_id": "source",
"row_id": 0,
},
sort_action="native",
sort_mode="multi",
style_cell={
"textAlign": "left",
"height": "fitContent",
"whiteSpace": "pre-line",
"wordWrap": "break-word",
"BackgroundColor": "lightblue",
},
cell_selectable=True,
style_header={
"backgroundColor": "#F3F2F7",
"fontSize": "1.857rem !important",
"fontWeight": "100",
"padding-left": "1rem",
"fontFamily": "sans-serif",
},
style_data={
"backgroundColor": "white",
"fontWeight": "100",
"padding": ".72rem" "2rem",
"padding-left": "1rem",
"fontFamily": "sans-serif",
},
page_current=0,
page_size=page_size,
export_format="xlsx",
)
def make_bs_table(results, size="md", display_index=True):
"""
Function to generate a boostrap table from a dataframe
:param size: Specify table size, options: 'sm', 'md', 'lg'.
:param results: bootstrap table
:type results: pd.Dataframe
:return:
:rtype:
"""
if display_index:
results = results.reset_index()
table_header = [html.Thead(html.Tr([html.Th(c) for c in results.columns]))]
table_body = [
html.Tbody(
list(
html.Tr(
list(
html.Td(round(v, 4) if isinstance(v, float) else v)
for v in data.values
)
)
for i, data in results.iterrows()
)
)
]
table = dbc.Table(
table_header + table_body, bordered=True, size=size, responsive=True
)
return table