These tables are created using the itable package https://github.com/mgymrek/itable.
These examples are originally described in this post before I had created the separate itable
package. Usage is identical except for the change in the package name.
In [16]:
import pandas as pd
import itable
In [17]:
# Create an example data frame
df = pd.DataFrame({"x":[1,2,3], "y":[6,4,3], "z":["testing","pretty","tables"], "f":[0.023432, 0.234321,0.5555]})
In [18]:
# Display a simple table
itable.PrettyTable(df)
Out[18]:
In [19]:
# Give it a theme and center the table
itable.PrettyTable(df, tstyle=itable.TableStyle(theme="theme1"), center=True)
Out[19]:
In [20]:
# Set cell style using a CellStyle object
pt = itable.PrettyTable(df, tstyle=itable.TableStyle(theme="theme1"), center=True)
cs = itable.CellStyle()
cs.set("background-color", "red")
cs.set("color", "white")
pt.set_cell_style(style=cs)
pt
Out[20]:
In [21]:
# Only for a subset of rows/columns
pt = itable.PrettyTable(df, tstyle=itable.TableStyle(theme="theme1"), center=True)
cs = itable.CellStyle()
cs.set("background-color", "red")
cs.set("color", "white")
pt.set_cell_style(style=cs, rows=[1,2], cols=[2])
pt
Out[21]:
In [22]:
# Set styles using keywords (these are all CSS properties, just replace "-" with "_")
pt = itable.PrettyTable(df, tstyle=itable.TableStyle(theme="theme1"), center=True)
pt.set_cell_style(font_weight="bold", color="purple", background_color="yellow", rows=[1], cols=[2,3])
pt
Out[22]:
In [23]:
# Set the header style. corner sets the corner cell
# "indices" applies the style only to certain indices
pt = itable.PrettyTable(df, tstyle=itable.TableStyle(theme="theme1"), center=True, header_row=True)
pt.set_row_header_style(color="blue")
pt.set_col_header_style(background_color="white", font_weight="bold", indices=[2])
pt.set_corner_style(background_color="red")
pt
Out[23]:
In [24]:
# Update current styles
pt = itable.PrettyTable(df, tstyle=itable.TableStyle(theme="theme1"), center=True, header_row=True)
pt.set_cell_style(font_weight="bold", color="purple", background_color="yellow", rows=[1], cols=[2,3])
pt.update_cell_style(background_color="pink", rows=[1], cols=[3])
pt.update_row_header_style(background_color="blue", indices=[0])
pt.update_col_header_style(color="red")
pt.update_corner_style(background_color="purple")
pt
Out[24]:
In [25]:
# Set cell formats
df = pd.DataFrame({"FloatColumn": [0.0324234, 0.23432111, 0.555555], "SciNotColumn":[1e10, 4.232e-6, 53e-8]})
pt = itable.PrettyTable(df, tstyle=itable.TableStyle(theme="theme1"), center=True)
pt.set_cell_style(cols=[0], format_function=lambda x: "%.3f"%x)
def SciNot(x):
xx = "%.2E"%x
base, exp = xx.split("E")
return "%s × 10<sup>%s</sup>"%(base, int(exp))
pt.set_cell_style(cols=[1], format_function=SciNot)
pt
Out[25]: