Module hela.plots.html_displays
Expand source code
from __future__ import annotations
from pandas import DataFrame
class HTMLDisplay:
def __init__(self, html_str):
self.html_str = html_str
def _repr_html_(self):
return self.html_str
class DFDisplay(DataFrame):
def __str__(self):
return self.to_string(index=False)
@property
def _constructor(self) -> DFDisplay:
"""Required property when inheriting a pandas dataframe"""
return DFDisplay
def __repr__(self):
return self.__str__()
def _repr_html_(self):
max_chars = 50
hover_data_df = self.copy().astype(str).applymap(
lambda x: x.replace('"', "'")
)
out_pdf = self.copy().astype(str).applymap(
lambda x: x if len(x) < max_chars else x[:max_chars - 3] + '...'
)
hoverbox_props = (
'border: 2px solid #000000;' # Box border size
'border-radius: 0.4em;' # Box corners smoothness
'position:absolute;' # Where the box should pop up
'z-index: 1;' # Where the object should end up (on top)
'visibility: hidden;' # The default visibility mode
'background-color: white;' # Background color of box
'color: #000000;' # Text color
'font-size: 1.1em;' # Font size
'max-width: 80ch;' # Maximum number of characters per row
'overflow-wrap: break-word;' # How to handle text overflow
'padding: 0.8em;' # Padding between box and text
'transform: translate(0px, -24px);'
)
return (
out_pdf
.style
.set_table_attributes('class="dataframe"')
.set_tooltips(hover_data_df, props=hoverbox_props)
.to_html()
)
Classes
class DFDisplay (data=None, index: Axes | None = None, columns: Axes | None = None, dtype: Dtype | None = None, copy: bool | None = None)-
Two-dimensional, size-mutable, potentially heterogeneous tabular data.
Data structure also contains labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.
Parameters
data:ndarray (structuredorhomogeneous), Iterable, dict,orDataFrame-
Dict can contain Series, arrays, constants, dataclass or list-like objects. If data is a dict, column order follows insertion-order. If a dict contains Series which have an index defined, it is aligned by its index. This alignment also occurs if data is a Series or a DataFrame itself. Alignment is done on Series/DataFrame inputs.
If data is a list of dicts, column order follows insertion-order.
index:Indexorarray-like- Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided.
columns:Indexorarray-like- Column labels to use for resulting frame when data does not have them, defaulting to RangeIndex(0, 1, 2, …, n). If data contains column labels, will perform column selection instead.
dtype:dtype, defaultNone- Data type to force. Only a single dtype is allowed. If None, infer.
copy:boolorNone, defaultNone-
Copy data from inputs. For dict data, the default of None behaves like
copy=True. For DataFrame or 2d ndarray input, the default of None behaves likecopy=False. If data is a dict containing one or more Series (possibly of different dtypes),copy=Falsewill ensure that these inputs are not copied.Changed in version: 1.3.0
See Also
DataFrame.from_records- Constructor from tuples, also record arrays.
DataFrame.from_dict- From dicts of Series, arrays, or dicts.
read_csv- Read a comma-separated values (csv) file into DataFrame.
read_table- Read general delimited file into DataFrame.
read_clipboard- Read text from clipboard into DataFrame.
Notes
Please reference the :ref:
User Guide <basics.dataframe>for more information.Examples
Constructing DataFrame from a dictionary.
>>> d = {'col1': [1, 2], 'col2': [3, 4]} >>> df = pd.DataFrame(data=d) >>> df col1 col2 0 1 3 1 2 4Notice that the inferred dtype is int64.
>>> df.dtypes col1 int64 col2 int64 dtype: objectTo enforce a single dtype:
>>> df = pd.DataFrame(data=d, dtype=np.int8) >>> df.dtypes col1 int8 col2 int8 dtype: objectConstructing DataFrame from a dictionary including Series:
>>> d = {'col1': [0, 1, 2, 3], 'col2': pd.Series([2, 3], index=[2, 3])} >>> pd.DataFrame(data=d, index=[0, 1, 2, 3]) col1 col2 0 0 NaN 1 1 NaN 2 2 2.0 3 3 3.0Constructing DataFrame from numpy ndarray:
>>> df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), ... columns=['a', 'b', 'c']) >>> df2 a b c 0 1 2 3 1 4 5 6 2 7 8 9Constructing DataFrame from a numpy ndarray that has labeled columns:
>>> data = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], ... dtype=[("a", "i4"), ("b", "i4"), ("c", "i4")]) >>> df3 = pd.DataFrame(data, columns=['c', 'a']) ... >>> df3 c a 0 3 1 1 6 4 2 9 7Constructing DataFrame from dataclass:
>>> from dataclasses import make_dataclass >>> Point = make_dataclass("Point", [("x", int), ("y", int)]) >>> pd.DataFrame([Point(0, 0), Point(0, 3), Point(2, 3)]) x y 0 0 0 1 0 3 2 2 3Constructing DataFrame from Series/DataFrame:
>>> ser = pd.Series([1, 2, 3], index=["a", "b", "c"]) >>> df = pd.DataFrame(data=ser, index=["a", "c"]) >>> df 0 a 1 c 3>>> df1 = pd.DataFrame([1, 2, 3], index=["a", "b", "c"], columns=["x"]) >>> df2 = pd.DataFrame(data=df1, index=["a", "c"]) >>> df2 x a 1 c 3Expand source code
class DFDisplay(DataFrame): def __str__(self): return self.to_string(index=False) @property def _constructor(self) -> DFDisplay: """Required property when inheriting a pandas dataframe""" return DFDisplay def __repr__(self): return self.__str__() def _repr_html_(self): max_chars = 50 hover_data_df = self.copy().astype(str).applymap( lambda x: x.replace('"', "'") ) out_pdf = self.copy().astype(str).applymap( lambda x: x if len(x) < max_chars else x[:max_chars - 3] + '...' ) hoverbox_props = ( 'border: 2px solid #000000;' # Box border size 'border-radius: 0.4em;' # Box corners smoothness 'position:absolute;' # Where the box should pop up 'z-index: 1;' # Where the object should end up (on top) 'visibility: hidden;' # The default visibility mode 'background-color: white;' # Background color of box 'color: #000000;' # Text color 'font-size: 1.1em;' # Font size 'max-width: 80ch;' # Maximum number of characters per row 'overflow-wrap: break-word;' # How to handle text overflow 'padding: 0.8em;' # Padding between box and text 'transform: translate(0px, -24px);' ) return ( out_pdf .style .set_table_attributes('class="dataframe"') .set_tooltips(hover_data_df, props=hoverbox_props) .to_html() )Ancestors
- pandas.core.frame.DataFrame
- pandas.core.generic.NDFrame
- pandas.core.base.PandasObject
- pandas.core.accessor.DirNamesMixin
- pandas.core.indexing.IndexingMixin
- pandas.core.arraylike.OpsMixin
class HTMLDisplay (html_str)-
Expand source code
class HTMLDisplay: def __init__(self, html_str): self.html_str = html_str def _repr_html_(self): return self.html_str