Last active
February 3, 2018 04:51
-
-
Save HHammond/22bf58c8f1a163d1f9ef to your computer and use it in GitHub Desktop.
Pandas Pretty Table CSS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
from functools import partial | |
def summary(df, fn=np.sum, axis=0, name='Total', | |
table_class_prefix='dataframe-summary'): | |
"""Append a summary row or column to DataFrame. | |
Input: | |
------ | |
df : Dataframe to be summarized | |
fn : Summary function applied over each column | |
axis : Axis to summarize on (1: by row, 0: by column) | |
name : Index or column label for summary | |
table_class_prefix : Custom css class for dataframe | |
Returns: | |
-------- | |
Dataframe with applied summary. | |
""" | |
total = df.apply(fn, axis=axis).to_frame(name) | |
table_class = "" | |
if axis == 0: | |
total = total.T | |
table_class = "{}-row".format(table_class_prefix) | |
elif axis == 1: | |
table_class = "{}-col".format(tbale_class_prefix) | |
out = pd.concat([df, total], axis=axis) | |
# Patch to_html function to use custom css class | |
out.to_html = partial(out.to_html, classes=table_class) | |
return out |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from numbers import Number | |
def as_percent(v, precision='0.2'): | |
"""Convert number to percentage string.""" | |
if isinstance(v, Number): | |
return "{{:{}%}}".format(precision).format(v) | |
else: | |
raise TypeError("Numeric type required") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Add to ~/.ipython/profile_default/static/custom/custom.css */ | |
/* Pretty Pandas Dataframes */ | |
.dataframe * {border-color: #c0c0c0 !important;} | |
.dataframe th{background: #eee;} | |
.dataframe td{text-align: right; min-width:5em;} | |
/* Format summary rows */ | |
.dataframe-summary-row tr:last-child, | |
.dataframe-summary-col td:last-child{ | |
background: #eee; | |
font-weight: 500; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment