pandas.io.formats.style.Styler.hide_columns   Styler.hide_columns(subset=None, level=None, names=False)[source]

Hide the column headers or specific keys in the columns from rendering. This method has dual functionality:
 if subset is None then the entire column headers row, or specific levels, will be hidden whilst the data-values remain visible. if a subset is given then those specific columns, including the data-values will be hidden, whilst the column headers row remains visible.
  Changed in version 1.3.0.   ..deprecated:: 1.4.0

This method should be replaced by hide(axis="columns", **kwargs)    Parameters

subset:label, array-like, IndexSlice, optional

A valid 1d input or single key along the columns axis within DataFrame.loc[:, <subset>], to limit data to before applying the function.
level:int, str, list

The level(s) to hide in a MultiIndex if hiding the entire column headers row. Cannot be used simultaneously with subset.  New in version 1.4.0.
names:bool

Whether to hide the column index name(s), in the case all column headers, or some levels, are visible.  New in version 1.4.0.     Returns

self:Styler

    See also  Styler.hide

Hide the entire index / columns, or specific rows / columns.


pandas.io.formats.style.Styler.hide_index   Styler.hide_index(subset=None, level=None, names=False)[source]

Hide the entire index, or specific keys in the index from rendering. This method has dual functionality:
 if subset is None then the entire index, or specified levels, will be hidden whilst displaying all data-rows. if a subset is given then those specific rows will be hidden whilst the index itself remains visible.
  Changed in version 1.3.0.   Deprecated since version 1.4.0: This method should be replaced by hide(axis="index", **kwargs)   Parameters

subset:label, array-like, IndexSlice, optional

A valid 1d input or single key along the index axis within DataFrame.loc[<subset>, :], to limit data to before applying the function.
level:int, str, list

The level(s) to hide in a MultiIndex if hiding the entire index. Cannot be used simultaneously with subset.  New in version 1.4.0.
names:bool

Whether to hide the index name(s), in the case the index or part of it remains visible.  New in version 1.4.0.     Returns

self:Styler

    See also  Styler.hide

Hide the entire index / columns, or specific rows / columns.


pandas.io.formats.style.Styler.highlight_between   Styler.highlight_between(subset=None, color='yellow', axis=0, left=None, right=None, inclusive='both', props=None)[source]

Highlight a defined range with a style.  New in version 1.3.0.   Parameters

subset:label, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.
color:str, default ‘yellow’

Background color to use for highlighting.
axis:{0 or ‘index’, 1 or ‘columns’, None}, default 0

If left or right given as sequence, axis along which to apply those boundaries. See examples.
left:scalar or datetime-like, or sequence or array-like, default None

Left bound for defining the range.
right:scalar or datetime-like, or sequence or array-like, default None

Right bound for defining the range.
inclusive:{‘both’, ‘neither’, ‘left’, ‘right’}

Identify whether bounds are closed or open.
props:str, default None

CSS properties to use for highlighting. If props is given, color is not used.    Returns

self:Styler

    See also  Styler.highlight_null

Highlight missing values with a style.  Styler.highlight_max

Highlight the maximum with a style.  Styler.highlight_min

Highlight the minimum with a style.  Styler.highlight_quantile

Highlight values defined by a quantile with a style.    Notes If left is None only the right bound is applied. If right is None only the left bound is applied. If both are None all values are highlighted. axis is only needed if left or right are provided as a sequence or an array-like object for aligning the shapes. If left and right are both scalars then all axis inputs will give the same result. This function only works with compatible dtypes. For example a datetime-like region can only use equivalent datetime-like left and right arguments. Use subset to control regions which have multiple dtypes. Examples Basic usage
>>> df = pd.DataFrame({
...     'One': [1.2, 1.6, 1.5],
...     'Two': [2.9, 2.1, 2.5],
...     'Three': [3.1, 3.2, 3.8],
... })
>>> df.style.highlight_between(left=2.1, right=2.9)
     Using a range input sequnce along an axis, in this case setting a left and right for each column individually
>>> df.style.highlight_between(left=[1.4, 2.4, 3.4], right=[1.6, 2.6, 3.6],
...     axis=1, color="#fffd75")
     Using axis=None and providing the left argument as an array that matches the input DataFrame, with a constant right
>>> df.style.highlight_between(left=[[2,2,3],[2,2,3],[3,3,3]], right=3.5,
...     axis=None, color="#fffd75")
     Using props instead of default background coloring
>>> df.style.highlight_between(left=1.5, right=3.5,
...     props='font-weight:bold;color:#e83e8c')


pandas.io.formats.style.Styler.highlight_max   Styler.highlight_max(subset=None, color='yellow', axis=0, props=None)[source]

Highlight the maximum with a style.  Parameters

subset:label, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.
color:str, default ‘yellow’

Background color to use for highlighting.
axis:{0 or ‘index’, 1 or ‘columns’, None}, default 0

Apply to each column (axis=0 or 'index'), to each row (axis=1 or 'columns'), or to the entire DataFrame at once with axis=None.
props:str, default None

CSS properties to use for highlighting. If props is given, color is not used.  New in version 1.3.0.     Returns

self:Styler

    See also  Styler.highlight_null

Highlight missing values with a style.  Styler.highlight_min

Highlight the minimum with a style.  Styler.highlight_between

Highlight a defined range with a style.  Styler.highlight_quantile

Highlight values defined by a quantile with a style.


pandas.io.formats.style.Styler.highlight_min   Styler.highlight_min(subset=None, color='yellow', axis=0, props=None)[source]

Highlight the minimum with a style.  Parameters

subset:label, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.
color:str, default ‘yellow’

Background color to use for highlighting.
axis:{0 or ‘index’, 1 or ‘columns’, None}, default 0

Apply to each column (axis=0 or 'index'), to each row (axis=1 or 'columns'), or to the entire DataFrame at once with axis=None.
props:str, default None

CSS properties to use for highlighting. If props is given, color is not used.  New in version 1.3.0.     Returns

self:Styler

    See also  Styler.highlight_null

Highlight missing values with a style.  Styler.highlight_max

Highlight the maximum with a style.  Styler.highlight_between

Highlight a defined range with a style.  Styler.highlight_quantile

Highlight values defined by a quantile with a style.


pandas.io.formats.style.Styler.highlight_null   Styler.highlight_null(null_color='red', subset=None, props=None)[source]

Highlight missing values with a style.  Parameters

null_color:str, default ‘red’

subset:label, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.  New in version 1.1.0.
props:str, default None

CSS properties to use for highlighting. If props is given, color is not used.  New in version 1.3.0.     Returns

self:Styler

    See also  Styler.highlight_max

Highlight the maximum with a style.  Styler.highlight_min

Highlight the minimum with a style.  Styler.highlight_between

Highlight a defined range with a style.  Styler.highlight_quantile

Highlight values defined by a quantile with a style.


pandas.io.formats.style.Styler.highlight_quantile   Styler.highlight_quantile(subset=None, color='yellow', axis=0, q_left=0.0, q_right=1.0, interpolation='linear', inclusive='both', props=None)[source]

Highlight values defined by a quantile with a style.  New in version 1.3.0.   Parameters

subset:label, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.
color:str, default ‘yellow’

Background color to use for highlighting.
axis:{0 or ‘index’, 1 or ‘columns’, None}, default 0

Axis along which to determine and highlight quantiles. If None quantiles are measured over the entire DataFrame. See examples.
q_left:float, default 0

Left bound, in [0, q_right), for the target quantile range.
q_right:float, default 1

Right bound, in (q_left, 1], for the target quantile range.
interpolation:{‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}

Argument passed to Series.quantile or DataFrame.quantile for quantile estimation.
inclusive:{‘both’, ‘neither’, ‘left’, ‘right’}

Identify whether quantile bounds are closed or open.
props:str, default None

CSS properties to use for highlighting. If props is given, color is not used.    Returns

self:Styler

    See also  Styler.highlight_null

Highlight missing values with a style.  Styler.highlight_max

Highlight the maximum with a style.  Styler.highlight_min

Highlight the minimum with a style.  Styler.highlight_between

Highlight a defined range with a style.    Notes This function does not work with str dtypes. Examples Using axis=None and apply a quantile to all collective data
>>> df = pd.DataFrame(np.arange(10).reshape(2,5) + 1)
>>> df.style.highlight_quantile(axis=None, q_left=0.8, color="#fffd75")
...
     Or highlight quantiles row-wise or column-wise, in this case by row-wise
>>> df.style.highlight_quantile(axis=1, q_left=0.8, color="#fffd75")
...
     Use props instead of default background coloring
>>> df.style.highlight_quantile(axis=None, q_left=0.2, q_right=0.8,
...     props='font-weight:bold;color:#e83e8c')


pandas.io.formats.style.Styler.loader   Styler.loader=<jinja2.loaders.PackageLoader object>


pandas.io.formats.style.Styler.pipe   Styler.pipe(func, *args, **kwargs)[source]

Apply func(self, *args, **kwargs), and return the result.  Parameters

func:function

Function to apply to the Styler. Alternatively, a (callable, keyword) tuple where keyword is a string indicating the keyword of callable that expects the Styler.
*args:optional

Arguments passed to func.
**kwargs:optional

A dictionary of keyword arguments passed into func.    Returns
 object :

The value returned by func.      See also  DataFrame.pipe

Analogous method for DataFrame.  Styler.apply

Apply a CSS-styling function column-wise, row-wise, or table-wise.    Notes Like DataFrame.pipe(), this method can simplify the application of several user-defined functions to a styler. Instead of writing:
f(g(df.style.set_precision(3), arg1=a), arg2=b, arg3=c)
  users can write:
(df.style.set_precision(3)
   .pipe(g, arg1=a)
   .pipe(f, arg2=b, arg3=c))
  In particular, this allows users to define functions that take a styler object, along with other parameters, and return the styler after making styling changes (such as calling Styler.apply() or Styler.set_properties()). Using .pipe, these user-defined style “transformations” can be interleaved with calls to the built-in Styler interface. Examples
>>> def format_conversion(styler):
...     return (styler.set_properties(**{'text-align': 'right'})
...                   .format({'conversion': '{:.1%}'}))
  The user-defined format_conversion function above can be called within a sequence of other style modifications:
>>> df = pd.DataFrame({'trial': list(range(5)),
...                    'conversion': [0.75, 0.85, np.nan, 0.7, 0.72]})
>>> (df.style
...    .highlight_min(subset=['conversion'], color='yellow')
...    .pipe(format_conversion)
...    .set_caption("Results with minimum conversion highlighted."))
...


pandas.io.formats.style.Styler.render   Styler.render(sparse_index=None, sparse_columns=None, **kwargs)[source]

Render the Styler including all applied styles to HTML.  Deprecated since version 1.4.0.   Parameters

sparse_index:bool, optional

Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row. Defaults to pandas.options.styler.sparse.index value.
sparse_columns:bool, optional

Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row. Defaults to pandas.options.styler.sparse.columns value.  **kwargs

Any additional keyword arguments are passed through to self.template.render. This is useful when you need to provide additional variables for a custom template.    Returns

rendered:str

The rendered HTML.     Notes This method is deprecated in favour of Styler.to_html. Styler objects have defined the _repr_html_ method which automatically calls self.to_html() when it’s the last item in a Notebook cell. When calling Styler.render() directly, wrap the result in IPython.display.HTML to view the rendered HTML in the notebook. Pandas uses the following keys in render. Arguments passed in **kwargs take precedence, so think carefully if you want to override them:  head cellstyle body uuid table_styles caption table_attributes


pandas.io.formats.style.Styler.set_caption   Styler.set_caption(caption)[source]

Set the text added to a <caption> HTML element.  Parameters

caption:str, tuple

For HTML output either the string input is used or the first element of the tuple. For LaTeX the string input provides a caption and the additional tuple input allows for full captions and short captions, in that order.    Returns

self:Styler


pandas.io.formats.style.Styler.set_na_rep   Styler.set_na_rep(na_rep)[source]

Set the missing data representation on a Styler.  New in version 1.0.0.   Deprecated since version 1.3.0.   Parameters

na_rep:str

  Returns

self:Styler

   Notes This method is deprecated. See Styler.format()


pandas.io.formats.style.Styler.set_precision   Styler.set_precision(precision)[source]

Set the precision used to display values.  Deprecated since version 1.3.0.   Parameters

precision:int

  Returns

self:Styler

   Notes This method is deprecated see Styler.format.


pandas.io.formats.style.Styler.set_properties   Styler.set_properties(subset=None, **kwargs)[source]

Set defined CSS-properties to each <td> HTML element within the given subset.  Parameters

subset:label, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.
**kwargs:dict

A dictionary of property, value pairs to be set for each cell.    Returns

self:Styler

   Notes This is a convenience methods which wraps the Styler.applymap() calling a function returning the CSS-properties independently of the data. Examples
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_properties(color="white", align="right")
>>> df.style.set_properties(**{'background-color': 'yellow'})
  See Table Visualization user guide for more details.


pandas.io.formats.style.Styler.set_sticky   Styler.set_sticky(axis=0, pixel_size=None, levels=None)[source]

Add CSS to permanently display the index or column headers in a scrolling frame.  Parameters

axis:{0 or ‘index’, 1 or ‘columns’}, default 0

Whether to make the index or column headers sticky.
pixel_size:int, optional

Required to configure the width of index cells or the height of column header cells when sticking a MultiIndex (or with a named Index). Defaults to 75 and 25 respectively.
levels:int, str, list, optional

If axis is a MultiIndex the specific levels to stick. If None will stick all levels.    Returns

self:Styler

   Notes This method uses the CSS ‘position: sticky;’ property to display. It is designed to work with visible axes, therefore both:
 styler.set_sticky(axis=”index”).hide(axis=”index”) styler.set_sticky(axis=”columns”).hide(axis=”columns”)
 may produce strange behaviour due to CSS controls with missing elements.


pandas.io.formats.style.Styler.set_table_attributes   Styler.set_table_attributes(attributes)[source]

Set the table attributes added to the <table> HTML element. These are items in addition to automatic (by default) id attribute.  Parameters

attributes:str

  Returns

self:Styler

    See also  Styler.set_table_styles

Set the table styles included within the <style> HTML element.  Styler.set_td_classes

Set the DataFrame of strings added to the class attribute of <td> HTML elements.    Examples
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_table_attributes('class="pure-table"')
# ... <table class="pure-table"> ...


pandas.io.formats.style.Styler.set_table_styles   Styler.set_table_styles(table_styles=None, axis=0, overwrite=True, css_class_names=None)[source]

Set the table styles included within the <style> HTML element. This function can be used to style the entire table, columns, rows or specific HTML selectors.  Parameters

table_styles:list or dict

If supplying a list, each individual table_style should be a dictionary with selector and props keys. selector should be a CSS selector that the style will be applied to (automatically prefixed by the table’s UUID) and props should be a list of tuples with (attribute, value). If supplying a dict, the dict keys should correspond to column names or index values, depending upon the specified axis argument. These will be mapped to row or col CSS selectors. MultiIndex values as dict keys should be in their respective tuple form. The dict values should be a list as specified in the form with CSS selectors and props that will be applied to the specified row or column.  Changed in version 1.2.0.
axis:{0 or ‘index’, 1 or ‘columns’, None}, default 0

Apply to each column (axis=0 or 'index'), to each row (axis=1 or 'columns'). Only used if table_styles is dict.  New in version 1.2.0.
overwrite:bool, default True

Styles are replaced if True, or extended if False. CSS rules are preserved so most recent styles set will dominate if selectors intersect.  New in version 1.2.0.
css_class_names:dict, optional

A dict of strings used to replace the default CSS classes described below.  New in version 1.4.0.     Returns

self:Styler

    See also  Styler.set_td_classes

Set the DataFrame of strings added to the class attribute of <td> HTML elements.  Styler.set_table_attributes

Set the table attributes added to the <table> HTML element.    Notes The default CSS classes dict, whose values can be replaced is as follows:
css_class_names = {"row_heading": "row_heading",
                   "col_heading": "col_heading",
                   "index_name": "index_name",
                   "col": "col",
                   "col_trim": "col_trim",
                   "row_trim": "row_trim",
                   "level": "level",
                   "data": "data",
                   "blank": "blank}
  Examples
>>> df = pd.DataFrame(np.random.randn(10, 4),
...                   columns=['A', 'B', 'C', 'D'])
>>> df.style.set_table_styles(
...     [{'selector': 'tr:hover',
...       'props': [('background-color', 'yellow')]}]
... )
  Or with CSS strings
>>> df.style.set_table_styles(
...     [{'selector': 'tr:hover',
...       'props': 'background-color: yellow; font-size: 1em;'}]
... )
  Adding column styling by name
>>> df.style.set_table_styles({
...     'A': [{'selector': '',
...            'props': [('color', 'red')]}],
...     'B': [{'selector': 'td',
...            'props': 'color: blue;'}]
... }, overwrite=False)
  Adding row styling
>>> df.style.set_table_styles({
...     0: [{'selector': 'td:hover',
...          'props': [('font-size', '25px')]}]
... }, axis=1, overwrite=False)
  See Table Visualization user guide for more details.


pandas.io.formats.style.Styler.set_td_classes   Styler.set_td_classes(classes)[source]

Set the DataFrame of strings added to the class attribute of  HTML elements.  Parameters

classes:DataFrame

DataFrame containing strings that will be translated to CSS classes, mapped by identical column and index key values that must exist on the underlying Styler data. None, NaN values, and empty strings will be ignored and not affect the rendered HTML.    Returns

self:Styler

    See also  Styler.set_table_styles

Set the table styles included within the '
'
'
'
'
'
0
'
'
'
'
'
'
1
'
'
'
'
'


pandas.io.formats.style.Styler.set_tooltips   Styler.set_tooltips(ttips, props=None, css_class=None)[source]

Set the DataFrame of strings on Styler generating :hover tooltips. These string based tooltips are only applicable to  HTML elements, and cannot be used for column or index headers.  New in version 1.3.0.   Parameters

ttips:DataFrame

DataFrame containing strings that will be translated to tooltips, mapped by identical column and index values that must exist on the underlying Styler data. None, NaN values, and empty strings will be ignored and not affect the rendered HTML.
props:list-like or str, optional

List of (attr, value) tuples or a valid CSS string. If None adopts the internal default values described in notes.
css_class:str, optional

Name of the tooltip class used in CSS, should conform to HTML standards. Only useful if integrating tooltips with external CSS. If None uses the internal default value ‘pd-t’.    Returns

self:Styler

   Notes Tooltips are created by adding  to each data cell and then manipulating the table level CSS to attach pseudo hover and pseudo after selectors to produce the required the results. The default properties for the tooltip CSS class are:  visibility: hidden position: absolute z-index: 1 background-color: black color: white transform: translate(-20px, -20px)  The property ‘visibility: hidden;’ is a key prerequisite to the hover functionality, and should always be included in any manual properties specification, using the props argument. Tooltips are not designed to be efficient, and can add large amounts of additional HTML for larger tables, since they also require that cell_ids is forced to True. Examples Basic application
>>> df = pd.DataFrame(data=[[0, 1], [2, 3]])
>>> ttips = pd.DataFrame(
...    data=[["Min", ""], [np.nan, "Max"]], columns=df.columns, index=df.index
... )
>>> s = df.style.set_tooltips(ttips).to_html()
  Optionally controlling the tooltip visual display
>>> df.style.set_tooltips(ttips, css_class='tt-add', props=[
...     ('visibility', 'hidden'),
...     ('position', 'absolute'),
...     ('z-index', 1)])
>>> df.style.set_tooltips(ttips, css_class='tt-add',
...     props='visibility:hidden; position:absolute; z-index:1;')
...


pandas.io.formats.style.Styler.set_uuid   Styler.set_uuid(uuid)[source]

Set the uuid applied to id attributes of HTML elements.  Parameters

uuid:str

  Returns

self:Styler

   Notes Almost all HTML elements within the table, and including the <table> element are assigned id attributes. The format is T_uuid_<extra> where <extra> is typically a more specific identifier, such as row1_col2.


pandas.io.formats.style.Styler.template_html   Styler.template_html=<Template 'html.tpl'>


pandas.io.formats.style.Styler.template_html_style   Styler.template_html_style=<Template 'html_style.tpl'>


pandas.io.formats.style.Styler.template_html_table   Styler.template_html_table=<Template 'html_table.tpl'>


pandas.io.formats.style.Styler.template_latex   Styler.template_latex=<Template 'latex.tpl'>


pandas.io.formats.style.Styler.text_gradient   Styler.text_gradient(cmap='PuBu', low=0, high=0, axis=0, subset=None, vmin=None, vmax=None, gmap=None)[source]

Color the text in a gradient style. The text color is determined according to the data in each column, row or frame, or by a given gradient map. Requires matplotlib.  Parameters

cmap:str or colormap

Matplotlib colormap.
low:float

Compress the color range at the low end. This is a multiple of the data range to extend below the minimum; good values usually in [0, 1], defaults to 0.
high:float

Compress the color range at the high end. This is a multiple of the data range to extend above the maximum; good values usually in [0, 1], defaults to 0.
axis:{0 or ‘index’, 1 or ‘columns’, None}, default 0

Apply to each column (axis=0 or 'index'), to each row (axis=1 or 'columns'), or to the entire DataFrame at once with axis=None.
subset:label, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.
text_color_threshold:float or int

This argument is ignored (only used in background_gradient). Luminance threshold for determining text color in [0, 1]. Facilitates text visibility across varying background colors. All text is dark if 0, and light if 1, defaults to 0.408.
vmin:float, optional

Minimum data value that corresponds to colormap minimum value. If not specified the minimum value of the data (or gmap) will be used.  New in version 1.0.0.
vmax:float, optional

Maximum data value that corresponds to colormap maximum value. If not specified the maximum value of the data (or gmap) will be used.  New in version 1.0.0.
gmap:array-like, optional

Gradient map for determining the text colors. If not supplied will use the underlying data from rows, columns or frame. If given as an ndarray or list-like must be an identical shape to the underlying data considering axis and subset. If given as DataFrame or Series must have same index and column labels considering axis and subset. If supplied, vmin and vmax should be given relative to this gradient map.  New in version 1.3.0.     Returns

self:Styler

    See also  Styler.background_gradient

Color the background in a gradient style.    Notes When using low and high the range of the gradient, given by the data if gmap is not given or by gmap, is extended at the low end effectively by map.min - low * map.range and at the high end by map.max + high * map.range before the colors are normalized and determined. If combining with vmin and vmax the map.min, map.max and map.range are replaced by values according to the values derived from vmin and vmax. This method will preselect numeric columns and ignore non-numeric columns unless a gmap is supplied in which case no preselection occurs. Examples
>>> df = pd.DataFrame(columns=["City", "Temp (c)", "Rain (mm)", "Wind (m/s)"],
...                   data=[["Stockholm", 21.6, 5.0, 3.2],
...                         ["Oslo", 22.4, 13.3, 3.1],
...                         ["Copenhagen", 24.5, 0.0, 6.7]])
  Shading the values column-wise, with axis=0, preselecting numeric columns
>>> df.style.text_gradient(axis=0)
     Shading all values collectively using axis=None
>>> df.style.text_gradient(axis=None)
     Compress the color map from the both low and high ends
>>> df.style.text_gradient(axis=None, low=0.75, high=1.0)
     Manually setting vmin and vmax gradient thresholds
>>> df.style.text_gradient(axis=None, vmin=6.7, vmax=21.6)
     Setting a gmap and applying to all columns with another cmap
>>> df.style.text_gradient(axis=0, gmap=df['Temp (c)'], cmap='YlOrRd')
...
     Setting the gradient map for a dataframe (i.e. axis=None), we need to explicitly state subset to match the gmap shape
>>> gmap = np.array([[1,2,3], [2,3,4], [3,4,5]])
>>> df.style.text_gradient(axis=None, gmap=gmap,
...     cmap='YlOrRd', subset=['Temp (c)', 'Rain (mm)', 'Wind (m/s)']
... )


pandas.io.formats.style.Styler.to_excel   Styler.to_excel(excel_writer, sheet_name='Sheet1', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, encoding=None, inf_rep='inf', verbose=True, freeze_panes=None)[source]

Write Styler to an Excel sheet. To write a single Styler to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an ExcelWriter object with a target file name, and specify a sheet in the file to write to. Multiple sheets may be written to by specifying unique sheet_name. With all data written to the file it is necessary to save the changes. Note that creating an ExcelWriter object with a file name that already exists will result in the contents of the existing file being erased.  Parameters

excel_writer:path-like, file-like, or ExcelWriter object

File path or existing ExcelWriter.
sheet_name:str, default ‘Sheet1’

Name of sheet which will contain DataFrame.
na_rep:str, default ‘’

Missing data representation.
float_format:str, optional

Format string for floating point numbers. For example float_format="%.2f" will format 0.1234 to 0.12.
columns:sequence or list of str, optional

Columns to write.
header:bool or list of str, default True

Write out the column names. If a list of string is given it is assumed to be aliases for the column names.
index:bool, default True

Write row names (index).
index_label:str or sequence, optional

Column label for index column(s) if desired. If not specified, and header and index are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex.
startrow:int, default 0

Upper left cell row to dump data frame.
startcol:int, default 0

Upper left cell column to dump data frame.
engine:str, optional

Write engine to use, ‘openpyxl’ or ‘xlsxwriter’. You can also set this via the options io.excel.xlsx.writer, io.excel.xls.writer, and io.excel.xlsm.writer.  Deprecated since version 1.2.0: As the xlwt package is no longer maintained, the xlwt engine will be removed in a future version of pandas.
merge_cells:bool, default True

Write MultiIndex and Hierarchical Rows as merged cells.
encoding:str, optional

Encoding of the resulting excel file. Only necessary for xlwt, other writers support unicode natively.
inf_rep:str, default ‘inf’

Representation for infinity (there is no native representation for infinity in Excel).
verbose:bool, default True

Display more information in the error logs.
freeze_panes:tuple of int (length 2), optional

Specifies the one-based bottommost row and rightmost column that is to be frozen.
storage_options:dict, optional

Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec. Please see fsspec and urllib for more details.  New in version 1.2.0.       See also  to_csv

Write DataFrame to a comma-separated values (csv) file.  ExcelWriter

Class for writing DataFrame objects into excel sheets.  read_excel

Read an Excel file into a pandas DataFrame.  read_csv

Read a comma-separated values (csv) file into DataFrame.    Notes For compatibility with to_csv(), to_excel serializes lists and dicts to strings before writing. Once a workbook has been saved it is not possible to write further data without rewriting the whole workbook. Examples Create, write to and save a workbook:
>>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
...                    index=['row 1', 'row 2'],
...                    columns=['col 1', 'col 2'])
>>> df1.to_excel("output.xlsx")
  To specify the sheet name:
>>> df1.to_excel("output.xlsx",
...              sheet_name='Sheet_name_1')
  If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object:
>>> df2 = df1.copy()
>>> with pd.ExcelWriter('output.xlsx') as writer:
...     df1.to_excel(writer, sheet_name='Sheet_name_1')
...     df2.to_excel(writer, sheet_name='Sheet_name_2')
  ExcelWriter can also be used to append to an existing Excel file:
>>> with pd.ExcelWriter('output.xlsx',
...                     mode='a') as writer:
...     df.to_excel(writer, sheet_name='Sheet_name_3')
  To set the library that is used to write the Excel file, you can pass the engine keyword (the default engine is automatically chosen depending on the file extension):
>>> df1.to_excel('output1.xlsx', engine='xlsxwriter')


pandas.io.formats.style.Styler.to_html   Styler.to_html(buf=None, *, table_uuid=None, table_attributes=None, sparse_index=None, sparse_columns=None, bold_headers=False, caption=None, max_rows=None, max_columns=None, encoding=None, doctype_html=False, exclude_styles=False, **kwargs)[source]

Write Styler to a file, buffer or string in HTML-CSS format.  New in version 1.3.0.   Parameters

buf:str, path object, file-like object, or None, default None

String, path object (implementing os.PathLike[str]), or file-like object implementing a string write() function. If None, the result is returned as a string.
table_uuid:str, optional

Id attribute assigned to the <table> HTML element in the format: <table id="T_<table_uuid>" ..> If not given uses Styler’s initially assigned value.
table_attributes:str, optional

Attributes to assign within the <table> HTML element in the format: <table .. <table_attributes> > If not given defaults to Styler’s preexisting value.
sparse_index:bool, optional

Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row. Defaults to pandas.options.styler.sparse.index value.  New in version 1.4.0.
sparse_columns:bool, optional

Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each column. Defaults to pandas.options.styler.sparse.columns value.  New in version 1.4.0.
bold_headers:bool, optional

Adds “font-weight: bold;” as a CSS property to table style header cells.  New in version 1.4.0.
caption:str, optional

Set, or overwrite, the caption on Styler before rendering.  New in version 1.4.0.
max_rows:int, optional

The maximum number of rows that will be rendered. Defaults to pandas.options.styler.render.max_rows/max_columns.  New in version 1.4.0.
max_columns:int, optional

The maximum number of columns that will be rendered. Defaults to pandas.options.styler.render.max_columns, which is None. Rows and columns may be reduced if the number of total elements is large. This value is set to pandas.options.styler.render.max_elements, which is 262144 (18 bit browser rendering).  New in version 1.4.0.
encoding:str, optional

Character encoding setting for file output, and HTML meta tags. Defaults to pandas.options.styler.render.encoding value of “utf-8”.
doctype_html:bool, default False

Whether to output a fully structured HTML file including all HTML elements, or just the core <style> and <table> elements.
exclude_styles:bool, default False

Whether to include the <style> element and all associated element class and id identifiers, or solely the <table> element without styling identifiers.  **kwargs

Any additional keyword arguments are passed through to the jinja2 self.template.render process. This is useful when you need to provide additional variables for a custom template.    Returns
 str or None

If buf is None, returns the result as a string. Otherwise returns None.      See also  DataFrame.to_html

Write a DataFrame to a file, buffer or string in HTML format.


pandas.io.formats.style.Styler.to_latex   Styler.to_latex(buf=None, *, column_format=None, position=None, position_float=None, hrules=None, clines=None, label=None, caption=None, sparse_index=None, sparse_columns=None, multirow_align=None, multicol_align=None, siunitx=False, environment=None, encoding=None, convert_css=False)[source]

Write Styler to a file, buffer or string in LaTeX format.  New in version 1.3.0.   Parameters

buf:str, path object, file-like object, or None, default None

String, path object (implementing os.PathLike[str]), or file-like object implementing a string write() function. If None, the result is returned as a string.
column_format:str, optional

The LaTeX column specification placed in location: \begin{tabular}{<column_format>} Defaults to ‘l’ for index and non-numeric data columns, and, for numeric data columns, to ‘r’ by default, or ‘S’ if siunitx is True.
position:str, optional

The LaTeX positional argument (e.g. ‘h!’) for tables, placed in location: \\begin{table}[<position>].
position_float:{“centering”, “raggedleft”, “raggedright”}, optional

The LaTeX float command placed in location: \begin{table}[<position>] \<position_float> Cannot be used if environment is “longtable”.
hrules:bool

Set to True to add \toprule, \midrule and \bottomrule from the {booktabs} LaTeX package. Defaults to pandas.options.styler.latex.hrules, which is False.  Changed in version 1.4.0.
clines:str, optional

Use to control adding \cline commands for the index labels separation. Possible values are:
 None: no cline commands are added (default). “all;data”: a cline is added for every index value extending the width of the table, including data entries. “all;index”: as above with lines extending only the width of the index entries. “skip-last;data”: a cline is added for each index value except the last level (which is never sparsified), extending the widtn of the table. “skip-last;index”: as above with lines extending only the width of the index entries.
  New in version 1.4.0.
label:str, optional

The LaTeX label included as: \label{<label>}. This is used with \ref{<label>} in the main .tex file.
caption:str, tuple, optional

If string, the LaTeX table caption included as: \caption{<caption>}. If tuple, i.e (“full caption”, “short caption”), the caption included as: \caption[<caption[1]>]{<caption[0]>}.
sparse_index:bool, optional

Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row. Defaults to pandas.options.styler.sparse.index, which is True.
sparse_columns:bool, optional

Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each column. Defaults to pandas.options.styler.sparse.columns, which is True.
multirow_align:{“c”, “t”, “b”, “naive”}, optional

If sparsifying hierarchical MultiIndexes whether to align text centrally, at the top or bottom using the multirow package. If not given defaults to pandas.options.styler.latex.multirow_align, which is “c”. If “naive” is given renders without multirow.  Changed in version 1.4.0.
multicol_align:{“r”, “c”, “l”, “naive-l”, “naive-r”}, optional

If sparsifying hierarchical MultiIndex columns whether to align text at the left, centrally, or at the right. If not given defaults to pandas.options.styler.latex.multicol_align, which is “r”. If a naive option is given renders without multicol. Pipe decorators can also be added to non-naive values to draw vertical rules, e.g. “|r” will draw a rule on the left side of right aligned merged cells.  Changed in version 1.4.0.
siunitx:bool, default False

Set to True to structure LaTeX compatible with the {siunitx} package.
environment:str, optional

If given, the environment that will replace ‘table’ in \\begin{table}. If ‘longtable’ is specified then a more suitable template is rendered. If not given defaults to pandas.options.styler.latex.environment, which is None.  New in version 1.4.0.
encoding:str, optional

Character encoding setting. Defaults to pandas.options.styler.render.encoding, which is “utf-8”.
convert_css:bool, default False

Convert simple cell-styles from CSS to LaTeX format. Any CSS not found in conversion table is dropped. A style can be forced by adding option –latex. See notes.    Returns
 str or None

If buf is None, returns the result as a string. Otherwise returns None.      See also  Styler.format

Format the text display value of cells.    Notes Latex Packages For the following features we recommend the following LaTeX inclusions:
Feature Inclusion
sparse columns none: included within default {tabular} environment
sparse rows \usepackage{multirow}
hrules \usepackage{booktabs}
colors \usepackage[table]{xcolor}
siunitx \usepackage{siunitx}
bold (with siunitx)
 \usepackage{etoolbox} \robustify\bfseries \sisetup{detect-all = true} (within {document})

italic (with siunitx)
 \usepackage{etoolbox} \robustify\itshape \sisetup{detect-all = true} (within {document})

environment \usepackage{longtable} if arg is “longtable” | or any other relevant environment package
hyperlinks \usepackage{hyperref}    Cell Styles LaTeX styling can only be rendered if the accompanying styling functions have been constructed with appropriate LaTeX commands. All styling functionality is built around the concept of a CSS (<attribute>, <value>) pair (see Table Visualization), and this should be replaced by a LaTeX (<command>, <options>) approach. Each cell will be styled individually using nested LaTeX commands with their accompanied options. For example the following code will highlight and bold a cell in HTML-CSS:
>>> df = pd.DataFrame([[1,2], [3,4]])
>>> s = df.style.highlight_max(axis=None,
...                            props='background-color:red; font-weight:bold;')
>>> s.to_html()
  The equivalent using LaTeX only commands is the following:
>>> s = df.style.highlight_max(axis=None,
...                            props='cellcolor:{red}; bfseries: ;')
>>> s.to_latex()
  Internally these structured LaTeX (<command>, <options>) pairs are translated to the display_value with the default structure: \<command><options> <display_value>. Where there are multiple commands the latter is nested recursively, so that the above example highlighed cell is rendered as \cellcolor{red} \bfseries 4. Occasionally this format does not suit the applied command, or combination of LaTeX packages that is in use, so additional flags can be added to the <options>, within the tuple, to result in different positions of required braces (the default being the same as --nowrap):
Tuple Format Output Structure
(<command>,<options>) \<command><options> <display_value>
(<command>,<options> --nowrap) \<command><options> <display_value>
(<command>,<options> --rwrap) \<command><options>{<display_value>}
(<command>,<options> --wrap) {\<command><options> <display_value>}
(<command>,<options> --lwrap) {\<command><options>} <display_value>
(<command>,<options> --dwrap) {\<command><options>}{<display_value>}    For example the textbf command for font-weight should always be used with –rwrap so ('textbf', '--rwrap') will render a working cell, wrapped with braces, as \textbf{<display_value>}. A more comprehensive example is as follows:
>>> df = pd.DataFrame([[1, 2.2, "dogs"], [3, 4.4, "cats"], [2, 6.6, "cows"]],
...                   index=["ix1", "ix2", "ix3"],
...                   columns=["Integers", "Floats", "Strings"])
>>> s = df.style.highlight_max(
...     props='cellcolor:[HTML]{FFFF00}; color:{red};'
...           'textit:--rwrap; textbf:--rwrap;'
... )
>>> s.to_latex()
     Table Styles Internally Styler uses its table_styles object to parse the column_format, position, position_float, and label input arguments. These arguments are added to table styles in the format:
set_table_styles([
    {"selector": "column_format", "props": f":{column_format};"},
    {"selector": "position", "props": f":{position};"},
    {"selector": "position_float", "props": f":{position_float};"},
    {"selector": "label", "props": f":{{{label.replace(':','§')}}};"}
], overwrite=False)
  Exception is made for the hrules argument which, in fact, controls all three commands: toprule, bottomrule and midrule simultaneously. Instead of setting hrules to True, it is also possible to set each individual rule definition, by manually setting the table_styles, for example below we set a regular toprule, set an hline for bottomrule and exclude the midrule:
set_table_styles([
    {'selector': 'toprule', 'props': ':toprule;'},
    {'selector': 'bottomrule', 'props': ':hline;'},
], overwrite=False)
  If other commands are added to table styles they will be detected, and positioned immediately above the ‘\begin{tabular}’ command. For example to add odd and even row coloring, from the {colortbl} package, in format \rowcolors{1}{pink}{red}, use:
set_table_styles([
    {'selector': 'rowcolors', 'props': ':{1}{pink}{red};'}
], overwrite=False)
  A more comprehensive example using these arguments is as follows:
>>> df.columns = pd.MultiIndex.from_tuples([
...     ("Numeric", "Integers"),
...     ("Numeric", "Floats"),
...     ("Non-Numeric", "Strings")
... ])
>>> df.index = pd.MultiIndex.from_tuples([
...     ("L0", "ix1"), ("L0", "ix2"), ("L1", "ix3")
... ])
>>> s = df.style.highlight_max(
...     props='cellcolor:[HTML]{FFFF00}; color:{red}; itshape:; bfseries:;'
... )
>>> s.to_latex(
...     column_format="rrrrr", position="h", position_float="centering",
...     hrules=True, label="table:5", caption="Styled LaTeX Table",
...     multirow_align="t", multicol_align="r"
... )
     Formatting To format values Styler.format() should be used prior to calling Styler.to_latex, as well as other methods such as Styler.hide() for example:
>>> s.clear()
>>> s.table_styles = []
>>> s.caption = None
>>> s.format({
...    ("Numeric", "Integers"): '\${}',
...    ("Numeric", "Floats"): '{:.3f}',
...    ("Non-Numeric", "Strings"): str.upper
... })
                Numeric      Non-Numeric
          Integers   Floats    Strings
L0    ix1       $1   2.200      DOGS
      ix2       $3   4.400      CATS
L1    ix3       $2   6.600      COWS

>>> s.to_latex()
\begin{tabular}{llrrl}
{} & {} & \multicolumn{2}{r}{Numeric} & {Non-Numeric} \\
{} & {} & {Integers} & {Floats} & {Strings} \\
\multirow[c]{2}{*}{L0} & ix1 & \\$1 & 2.200 & DOGS \\
 & ix2 & \$3 & 4.400 & CATS \\
L1 & ix3 & \$2 & 6.600 & COWS \\
\end{tabular}
  CSS Conversion This method can convert a Styler constructured with HTML-CSS to LaTeX using the following limited conversions.
CSS Attribute CSS value LaTeX Command LaTeX Options
font-weight
 bold bolder
 bfseries bfseries
font-style
 italic oblique
 itshape slshape
background-color
 red #fe01ea #f0e rgb(128,255,0) rgba(128,0,0,0.5) rgb(25%,255,50%)   cellcolor
 {red}–lwrap [HTML]{FE01EA}–lwrap [HTML]{FF00EE}–lwrap [rgb]{0.5,1,0}–lwrap [rgb]{0.5,0,0}–lwrap [rgb]{0.25,1,0.5}–lwrap
color
 red #fe01ea #f0e rgb(128,255,0) rgba(128,0,0,0.5) rgb(25%,255,50%)   color
 {red} [HTML]{FE01EA} [HTML]{FF00EE} [rgb]{0.5,1,0} [rgb]{0.5,0,0} [rgb]{0.25,1,0.5}      It is also possible to add user-defined LaTeX only styles to a HTML-CSS Styler using the --latex flag, and to add LaTeX parsing options that the converter will detect within a CSS-comment.
>>> df = pd.DataFrame([[1]])
>>> df.style.set_properties(
...     **{"font-weight": "bold /* --dwrap */", "Huge": "--latex--rwrap"}
... ).to_latex(convert_css=True)
\begin{tabular}{lr}
{} & {0} \\
0 & {\bfseries}{\Huge{1}} \\
\end{tabular}
  Examples Below we give a complete step by step example adding some advanced features and noting some common gotchas. First we create the DataFrame and Styler as usual, including MultiIndex rows and columns, which allow for more advanced formatting options:
>>> cidx = pd.MultiIndex.from_arrays([
...     ["Equity", "Equity", "Equity", "Equity",
...      "Stats", "Stats", "Stats", "Stats", "Rating"],
...     ["Energy", "Energy", "Consumer", "Consumer", "", "", "", "", ""],
...     ["BP", "Shell", "H&M", "Unilever",
...      "Std Dev", "Variance", "52w High", "52w Low", ""]
... ])
>>> iidx = pd.MultiIndex.from_arrays([
...     ["Equity", "Equity", "Equity", "Equity"],
...     ["Energy", "Energy", "Consumer", "Consumer"],
...     ["BP", "Shell", "H&M", "Unilever"]
... ])
>>> styler = pd.DataFrame([
...     [1, 0.8, 0.66, 0.72, 32.1678, 32.1678**2, 335.12, 240.89, "Buy"],
...     [0.8, 1.0, 0.69, 0.79, 1.876, 1.876**2, 14.12, 19.78, "Hold"],
...     [0.66, 0.69, 1.0, 0.86, 7, 7**2, 210.9, 140.6, "Buy"],
...     [0.72, 0.79, 0.86, 1.0, 213.76, 213.76**2, 2807, 3678, "Sell"],
... ], columns=cidx, index=iidx).style
  Second we will format the display and, since our table is quite wide, will hide the repeated level-0 of the index:
>>> styler.format(subset="Equity", precision=2)
...       .format(subset="Stats", precision=1, thousands=",")
...       .format(subset="Rating", formatter=str.upper)
...       .format_index(escape="latex", axis=1)
...       .format_index(escape="latex", axis=0)
...       .hide(level=0, axis=0)
  Note that one of the string entries of the index and column headers is “H&M”. Without applying the escape=”latex” option to the format_index method the resultant LaTeX will fail to render, and the error returned is quite difficult to debug. Using the appropriate escape the “&” is converted to “\&”. Thirdly we will apply some (CSS-HTML) styles to our object. We will use a builtin method and also define our own method to highlight the stock recommendation:
>>> def rating_color(v):
...     if v == "Buy": color = "#33ff85"
...     elif v == "Sell": color = "#ff5933"
...     else: color = "#ffdd33"
...     return f"color: {color}; font-weight: bold;"
>>> styler.background_gradient(cmap="inferno", subset="Equity", vmin=0, vmax=1)
...       .applymap(rating_color, subset="Rating")
  All the above styles will work with HTML (see below) and LaTeX upon conversion:    However, we finally want to add one LaTeX only style (from the {graphicx} package), that is not easy to convert from CSS and pandas does not support it. Notice the –latex flag used here, as well as –rwrap to ensure this is formatted correctly and not ignored upon conversion.
>>> styler.applymap_index(
...     lambda v: "rotatebox:{45}--rwrap--latex;", level=2, axis=1
... )
  Finally we render our LaTeX adding in other options as required:
>>> styler.to_latex(
...     caption="Selected stock correlation and simple statistics.",
...     clines="skip-last;data",
...     convert_css=True,
...     position_float="centering",
...     multicol_align="|c|",
...     hrules=True,
... )
\begin{table}
\centering
\caption{Selected stock correlation and simple statistics.}
\begin{tabular}{llrrrrrrrrl}
\toprule
 &  & \multicolumn{4}{|c|}{Equity} & \multicolumn{4}{|c|}{Stats} & Rating \\
 &  & \multicolumn{2}{|c|}{Energy} & \multicolumn{2}{|c|}{Consumer} &
\multicolumn{4}{|c|}{} &  \\
 &  & \rotatebox{45}{BP} & \rotatebox{45}{Shell} & \rotatebox{45}{H\&M} &
\rotatebox{45}{Unilever} & \rotatebox{45}{Std Dev} & \rotatebox{45}{Variance} &
\rotatebox{45}{52w High} & \rotatebox{45}{52w Low} & \rotatebox{45}{} \\
\midrule
\multirow[c]{2}{*}{Energy} & BP & {\cellcolor[HTML]{FCFFA4}}
\color[HTML]{000000} 1.00 & {\cellcolor[HTML]{FCA50A}} \color[HTML]{000000}
0.80 & {\cellcolor[HTML]{EB6628}} \color[HTML]{F1F1F1} 0.66 &
{\cellcolor[HTML]{F68013}} \color[HTML]{F1F1F1} 0.72 & 32.2 & 1,034.8 & 335.1
& 240.9 & \color[HTML]{33FF85} \bfseries BUY \\
 & Shell & {\cellcolor[HTML]{FCA50A}} \color[HTML]{000000} 0.80 &
{\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 &
{\cellcolor[HTML]{F1731D}} \color[HTML]{F1F1F1} 0.69 &
{\cellcolor[HTML]{FCA108}} \color[HTML]{000000} 0.79 & 1.9 & 3.5 & 14.1 &
19.8 & \color[HTML]{FFDD33} \bfseries HOLD \\
\cline{1-11}
\multirow[c]{2}{*}{Consumer} & H\&M & {\cellcolor[HTML]{EB6628}}
\color[HTML]{F1F1F1} 0.66 & {\cellcolor[HTML]{F1731D}} \color[HTML]{F1F1F1}
0.69 & {\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 &
{\cellcolor[HTML]{FAC42A}} \color[HTML]{000000} 0.86 & 7.0 & 49.0 & 210.9 &
140.6 & \color[HTML]{33FF85} \bfseries BUY \\
 & Unilever & {\cellcolor[HTML]{F68013}} \color[HTML]{F1F1F1} 0.72 &
{\cellcolor[HTML]{FCA108}} \color[HTML]{000000} 0.79 &
{\cellcolor[HTML]{FAC42A}} \color[HTML]{000000} 0.86 &
{\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 & 213.8 & 45,693.3 &
2,807.0 & 3,678.0 & \color[HTML]{FF5933} \bfseries SELL \\
\cline{1-11}
\bottomrule
\end{tabular}
\end{table}


pandas.io.formats.style.Styler.use   Styler.use(styles)[source]

Set the styles on the current Styler. Possibly uses styles from Styler.export.  Parameters

styles:dict(str, Any)

 List of attributes to add to Styler. Dict keys should contain only:

 “apply”: list of styler functions, typically added with apply or applymap. “table_attributes”: HTML attributes, typically added with set_table_attributes. “table_styles”: CSS selectors and properties, typically added with set_table_styles. “hide_index”: whether the index is hidden, typically added with hide_index, or a boolean list for hidden levels. “hide_columns”: whether column headers are hidden, typically added with hide_columns, or a boolean list for hidden levels. “hide_index_names”: whether index names are hidden. “hide_column_names”: whether column header names are hidden. “css”: the css class names used.       Returns

self:Styler

    See also  Styler.export

Export the non data dependent attributes to the current Styler.    Examples
>>> styler = DataFrame([[1, 2], [3, 4]]).style
>>> styler2 = DataFrame([[9, 9, 9]]).style
>>> styler.hide(axis=0).highlight_max(axis=1)
>>> export = styler.export()
>>> styler2.use(export)


pandas.io.formats.style.Styler.where   Styler.where(cond, value, other=None, subset=None, **kwargs)[source]

Apply CSS-styles based on a conditional function elementwise.  Deprecated since version 1.3.0.  Updates the HTML representation with a style which is selected in accordance with the return value of a function.  Parameters

cond:callable

cond should take a scalar, and optional keyword arguments, and return a boolean.
value:str

Applied when cond returns true.
other:str

Applied when cond returns false.
subset:label, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.
**kwargs:dict

Pass along to cond.    Returns

self:Styler

    See also  Styler.applymap

Apply a CSS-styling function elementwise.  Styler.apply

Apply a CSS-styling function column-wise, row-wise, or table-wise.    Notes This method is deprecated. This method is a convenience wrapper for Styler.applymap(), which we recommend using instead. The example:
>>> df = pd.DataFrame([[1, 2], [3, 4]])
>>> def cond(v, limit=4):
...     return v > 1 and v != limit
>>> df.style.where(cond, value='color:green;', other='color:red;')
...
  should be refactored to:
>>> def style_func(v, value, other, limit=4):
...     cond = v > 1 and v != limit
...     return value if cond else other
>>> df.style.applymap(style_func, value='color:green;', other='color:red;')
...


pandas.io.json.build_table_schema   pandas.io.json.build_table_schema(data, index=True, primary_key=None, version=True)[source]

Create a Table schema from data.  Parameters

data:Series, DataFrame

index:bool, default True

Whether to include data.index in the schema.
primary_key:bool or None, default True

Column names to designate as the primary key. The default None will set ‘primaryKey’ to the index level or levels if the index is unique.
version:bool, default True

Whether to include a field pandas_version with the version of pandas that last revised the table schema. This version can be different from the installed pandas version.    Returns

schema:dict

   Notes See Table Schema for conversion types. Timedeltas as converted to ISO8601 duration format with 9 decimal places after the seconds field for nanosecond precision. Categoricals are converted to the any dtype, and use the enum field constraint to list the allowed values. The ordered attribute is included in an ordered field. Examples
>>> df = pd.DataFrame(
...     {'A': [1, 2, 3],
...      'B': ['a', 'b', 'c'],
...      'C': pd.date_range('2016-01-01', freq='d', periods=3),
...     }, index=pd.Index(range(3), name='idx'))
>>> build_table_schema(df)
{'fields': [{'name': 'idx', 'type': 'integer'}, {'name': 'A', 'type': 'integer'}, {'name': 'B', 'type': 'string'}, {'name': 'C', 'type': 'datetime'}], 'primaryKey': ['idx'], 'pandas_version': '1.4.0'}


pandas.io.stata.StataReader.data_label   propertyStataReader.data_label

Return data label of Stata file.


pandas.io.stata.StataReader.value_labels   StataReader.value_labels()[source]

Return a dict, associating each variable name a dict, associating each value its corresponding label.  Returns
 dict


pandas.io.stata.StataReader.variable_labels   StataReader.variable_labels()[source]

Return variable labels as a dict, associating each variable name with corresponding label.  Returns
 dict


pandas.io.stata.StataWriter.write_file   StataWriter.write_file()[source]

Export DataFrame object to Stata dta format.


pandas.isna   pandas.isna(obj)[source]

Detect missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are missing (NaN in numeric arrays, None or NaN in object arrays, NaT in datetimelike).  Parameters

obj:scalar or array-like

Object to check for null or missing values.    Returns
 bool or array-like of bool

For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is missing.      See also  notna

Boolean inverse of pandas.isna.  Series.isna

Detect missing values in a Series.  DataFrame.isna

Detect missing values in a DataFrame.  Index.isna

Detect missing values in an Index.    Examples Scalar arguments (including strings) result in a scalar boolean.
>>> pd.isna('dog')
False

>>> pd.isna(pd.NA)
True

>>> pd.isna(np.nan)
True
  ndarrays result in an ndarray of booleans.
>>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]])
>>> array
array([[ 1., nan,  3.],
       [ 4.,  5., nan]])
>>> pd.isna(array)
array([[False,  True, False],
       [False, False,  True]])
  For indexes, an ndarray of booleans is returned.
>>> index = pd.DatetimeIndex(["2017-07-05", "2017-07-06", None,
...                           "2017-07-08"])
>>> index
DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'],
              dtype='datetime64[ns]', freq=None)
>>> pd.isna(index)
array([False, False,  True, False])
  For Series and DataFrame, the same type is returned, containing booleans.
>>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']])
>>> df
     0     1    2
0  ant   bee  cat
1  dog  None  fly
>>> pd.isna(df)
       0      1      2
0  False  False  False
1  False   True  False

>>> pd.isna(df[1])
0    False
1     True
Name: 1, dtype: bool


pandas.isnull   pandas.isnull(obj)[source]

Detect missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are missing (NaN in numeric arrays, None or NaN in object arrays, NaT in datetimelike).  Parameters

obj:scalar or array-like

Object to check for null or missing values.    Returns
 bool or array-like of bool

For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is missing.      See also  notna

Boolean inverse of pandas.isna.  Series.isna

Detect missing values in a Series.  DataFrame.isna

Detect missing values in a DataFrame.  Index.isna

Detect missing values in an Index.    Examples Scalar arguments (including strings) result in a scalar boolean.
>>> pd.isna('dog')
False

>>> pd.isna(pd.NA)
True

>>> pd.isna(np.nan)
True
  ndarrays result in an ndarray of booleans.
>>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]])
>>> array
array([[ 1., nan,  3.],
       [ 4.,  5., nan]])
>>> pd.isna(array)
array([[False,  True, False],
       [False, False,  True]])
  For indexes, an ndarray of booleans is returned.
>>> index = pd.DatetimeIndex(["2017-07-05", "2017-07-06", None,
...                           "2017-07-08"])
>>> index
DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'],
              dtype='datetime64[ns]', freq=None)
>>> pd.isna(index)
array([False, False,  True, False])
  For Series and DataFrame, the same type is returned, containing booleans.
>>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']])
>>> df
     0     1    2
0  ant   bee  cat
1  dog  None  fly
>>> pd.isna(df)
       0      1      2
0  False  False  False
1  False   True  False

>>> pd.isna(df[1])
0    False
1     True
Name: 1, dtype: bool


pandas.json_normalize   pandas.json_normalize(data, record_path=None, meta=None, meta_prefix=None, record_prefix=None, errors='raise', sep='.', max_level=None)[source]

Normalize semi-structured JSON data into a flat table.  Parameters

data:dict or list of dicts

Unserialized JSON objects.
record_path:str or list of str, default None

Path in each object to list of records. If not passed, data will be assumed to be an array of records.
meta:list of paths (str or list of str), default None

Fields to use as metadata for each record in resulting table.
meta_prefix:str, default None

If True, prefix records with dotted (?) path, e.g. foo.bar.field if meta is [‘foo’, ‘bar’].
record_prefix:str, default None

If True, prefix records with dotted (?) path, e.g. foo.bar.field if path to records is [‘foo’, ‘bar’].
errors:{‘raise’, ‘ignore’}, default ‘raise’

Configures error handling.  ‘ignore’ : will ignore KeyError if keys listed in meta are not always present. ‘raise’ : will raise KeyError if keys listed in meta are not always present.
sep:str, default ‘.’

Nested records will generate names separated by sep. e.g., for sep=’.’, {‘foo’: {‘bar’: 0}} -> foo.bar.
max_level:int, default None

Max number of levels(depth of dict) to normalize. if None, normalizes all levels.  New in version 0.25.0.     Returns

frame:DataFrame

Normalize semi-structured JSON data into a flat table.
   Examples
>>> data = [
...     {"id": 1, "name": {"first": "Coleen", "last": "Volk"}},
...     {"name": {"given": "Mark", "family": "Regner"}},
...     {"id": 2, "name": "Faye Raker"},
... ]
>>> pd.json_normalize(data)
    id name.first name.last name.given name.family        name
0  1.0     Coleen      Volk        NaN         NaN         NaN
1  NaN        NaN       NaN       Mark      Regner         NaN
2  2.0        NaN       NaN        NaN         NaN  Faye Raker

>>> data = [
...     {
...         "id": 1,
...         "name": "Cole Volk",
...         "fitness": {"height": 130, "weight": 60},
...     },
...     {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}},
...     {
...         "id": 2,
...         "name": "Faye Raker",
...         "fitness": {"height": 130, "weight": 60},
...     },
... ]
>>> pd.json_normalize(data, max_level=0)
    id        name                        fitness
0  1.0   Cole Volk  {'height': 130, 'weight': 60}
1  NaN    Mark Reg  {'height': 130, 'weight': 60}
2  2.0  Faye Raker  {'height': 130, 'weight': 60}
  Normalizes nested data up to level 1.
>>> data = [
...     {
...         "id": 1,
...         "name": "Cole Volk",
...         "fitness": {"height": 130, "weight": 60},
...     },
...     {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}},
...     {
...         "id": 2,
...         "name": "Faye Raker",
...         "fitness": {"height": 130, "weight": 60},
...     },
... ]
>>> pd.json_normalize(data, max_level=1)
    id        name  fitness.height  fitness.weight
0  1.0   Cole Volk             130              60
1  NaN    Mark Reg             130              60
2  2.0  Faye Raker             130              60

>>> data = [
...     {
...         "state": "Florida",
...         "shortname": "FL",
...         "info": {"governor": "Rick Scott"},
...         "counties": [
...             {"name": "Dade", "population": 12345},
...             {"name": "Broward", "population": 40000},
...             {"name": "Palm Beach", "population": 60000},
...         ],
...     },
...     {
...         "state": "Ohio",
...         "shortname": "OH",
...         "info": {"governor": "John Kasich"},
...         "counties": [
...             {"name": "Summit", "population": 1234},
...             {"name": "Cuyahoga", "population": 1337},
...         ],
...     },
... ]
>>> result = pd.json_normalize(
...     data, "counties", ["state", "shortname", ["info", "governor"]]
... )
>>> result
         name  population    state shortname info.governor
0        Dade       12345   Florida    FL    Rick Scott
1     Broward       40000   Florida    FL    Rick Scott
2  Palm Beach       60000   Florida    FL    Rick Scott
3      Summit        1234   Ohio       OH    John Kasich
4    Cuyahoga        1337   Ohio       OH    John Kasich

>>> data = {"A": [1, 2]}
>>> pd.json_normalize(data, "A", record_prefix="Prefix.")
    Prefix.0
0          1
1          2
  Returns normalized data with columns prefixed with the given string.


pandas.melt   pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None, ignore_index=True)[source]

Unpivot a DataFrame from wide to long format, optionally leaving identifiers set. This function is useful to massage a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are “unpivoted” to the row axis, leaving just two non-identifier columns, ‘variable’ and ‘value’.  Parameters

id_vars:tuple, list, or ndarray, optional

Column(s) to use as identifier variables.
value_vars:tuple, list, or ndarray, optional

Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars.
var_name:scalar

Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’.
value_name:scalar, default ‘value’

Name to use for the ‘value’ column.
col_level:int or str, optional

If columns are a MultiIndex then use this level to melt.
ignore_index:bool, default True

If True, original index is ignored. If False, the original index is retained. Index labels will be repeated as necessary.  New in version 1.1.0.     Returns
 DataFrame

Unpivoted DataFrame.      See also  DataFrame.melt

Identical method.  pivot_table

Create a spreadsheet-style pivot table as a DataFrame.  DataFrame.pivot

Return reshaped DataFrame organized by given index / column values.  DataFrame.explode

Explode a DataFrame from list-like columns to long format.    Examples
>>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},
...                    'B': {0: 1, 1: 3, 2: 5},
...                    'C': {0: 2, 1: 4, 2: 6}})
>>> df
   A  B  C
0  a  1  2
1  b  3  4
2  c  5  6

>>> pd.melt(df, id_vars=['A'], value_vars=['B'])
   A variable  value
0  a        B      1
1  b        B      3
2  c        B      5

>>> pd.melt(df, id_vars=['A'], value_vars=['B', 'C'])
   A variable  value
0  a        B      1
1  b        B      3
2  c        B      5
3  a        C      2
4  b        C      4
5  c        C      6
  The names of ‘variable’ and ‘value’ columns can be customized:
>>> pd.melt(df, id_vars=['A'], value_vars=['B'],
...         var_name='myVarname', value_name='myValname')
   A myVarname  myValname
0  a         B          1
1  b         B          3
2  c         B          5
  Original index values can be kept around:
>>> pd.melt(df, id_vars=['A'], value_vars=['B', 'C'], ignore_index=False)
   A variable  value
0  a        B      1
1  b        B      3
2  c        B      5
0  a        C      2
1  b        C      4
2  c        C      6
  If you have multi-index columns:
>>> df.columns = [list('ABC'), list('DEF')]
>>> df
   A  B  C
   D  E  F
0  a  1  2
1  b  3  4
2  c  5  6

>>> pd.melt(df, col_level=0, id_vars=['A'], value_vars=['B'])
   A variable  value
0  a        B      1
1  b        B      3
2  c        B      5

>>> pd.melt(df, id_vars=[('A', 'D')], value_vars=[('B', 'E')])
  (A, D) variable_0 variable_1  value
0      a          B          E      1
1      b          B          E      3
2      c          B          E      5


pandas.merge   pandas.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)[source]

Merge DataFrame or named Series objects with a database-style join. A named Series object is treated as a DataFrame with a single named column. The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on. When performing a cross merge, no column specifications to merge on are allowed.  Warning If both key columns contain rows where the key is a null value, those rows will be matched against each other. This is different from usual SQL join behaviour and can lead to unexpected results.   Parameters

left:DataFrame

right:DataFrame or named Series

Object to merge with.
how:{‘left’, ‘right’, ‘outer’, ‘inner’, ‘cross’}, default ‘inner’

Type of merge to be performed.  left: use only keys from left frame, similar to a SQL left outer join; preserve key order. right: use only keys from right frame, similar to a SQL right outer join; preserve key order. outer: use union of keys from both frames, similar to a SQL full outer join; sort keys lexicographically. inner: use intersection of keys from both frames, similar to a SQL inner join; preserve the order of the left keys.
cross: creates the cartesian product from both frames, preserves the order of the left keys.  New in version 1.2.0.
on:label or list

Column or index level names to join on. These must be found in both DataFrames. If on is None and not merging on indexes then this defaults to the intersection of the columns in both DataFrames.
left_on:label or list, or array-like

Column or index level names to join on in the left DataFrame. Can also be an array or list of arrays of the length of the left DataFrame. These arrays are treated as if they are columns.
right_on:label or list, or array-like

Column or index level names to join on in the right DataFrame. Can also be an array or list of arrays of the length of the right DataFrame. These arrays are treated as if they are columns.
left_index:bool, default False

Use the index from the left DataFrame as the join key(s). If it is a MultiIndex, the number of keys in the other DataFrame (either the index or a number of columns) must match the number of levels.
right_index:bool, default False

Use the index from the right DataFrame as the join key. Same caveats as left_index.
sort:bool, default False

Sort the join keys lexicographically in the result DataFrame. If False, the order of the join keys depends on the join type (how keyword).
suffixes:list-like, default is (“_x”, “_y”)

A length-2 sequence where each element is optionally a string indicating the suffix to add to overlapping column names in left and right respectively. Pass a value of None instead of a string to indicate that the column name from left or right should be left as-is, with no suffix. At least one of the values must not be None.
copy:bool, default True

If False, avoid copy if possible.
indicator:bool or str, default False

If True, adds a column to the output DataFrame called “_merge” with information on the source of each row. The column can be given a different name by providing a string argument. The column will have a Categorical type with the value of “left_only” for observations whose merge key only appears in the left DataFrame, “right_only” for observations whose merge key only appears in the right DataFrame, and “both” if the observation’s merge key is found in both DataFrames.
validate:str, optional

If specified, checks if merge is of specified type.  “one_to_one” or “1:1”: check if merge keys are unique in both left and right datasets. “one_to_many” or “1:m”: check if merge keys are unique in left dataset. “many_to_one” or “m:1”: check if merge keys are unique in right dataset. “many_to_many” or “m:m”: allowed, but does not result in checks.     Returns
 DataFrame

A DataFrame of the two merged objects.      See also  merge_ordered

Merge with optional filling/interpolation.  merge_asof

Merge on nearest keys.  DataFrame.join

Similar method using indices.    Notes Support for specifying index levels as the on, left_on, and right_on parameters was added in version 0.23.0 Support for merging named Series objects was added in version 0.24.0 Examples
>>> df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],
...                     'value': [1, 2, 3, 5]})
>>> df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],
...                     'value': [5, 6, 7, 8]})
>>> df1
    lkey value
0   foo      1
1   bar      2
2   baz      3
3   foo      5
>>> df2
    rkey value
0   foo      5
1   bar      6
2   baz      7
3   foo      8
  Merge df1 and df2 on the lkey and rkey columns. The value columns have the default suffixes, _x and _y, appended.
>>> df1.merge(df2, left_on='lkey', right_on='rkey')
  lkey  value_x rkey  value_y
0  foo        1  foo        5
1  foo        1  foo        8
2  foo        5  foo        5
3  foo        5  foo        8
4  bar        2  bar        6
5  baz        3  baz        7
  Merge DataFrames df1 and df2 with specified left and right suffixes appended to any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey',
...           suffixes=('_left', '_right'))
  lkey  value_left rkey  value_right
0  foo           1  foo            5
1  foo           1  foo            8
2  foo           5  foo            5
3  foo           5  foo            8
4  bar           2  bar            6
5  baz           3  baz            7
  Merge DataFrames df1 and df2, but raise an exception if the DataFrames have any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))
Traceback (most recent call last):
...
ValueError: columns overlap but no suffix specified:
    Index(['value'], dtype='object')

>>> df1 = pd.DataFrame({'a': ['foo', 'bar'], 'b': [1, 2]})
>>> df2 = pd.DataFrame({'a': ['foo', 'baz'], 'c': [3, 4]})
>>> df1
      a  b
0   foo  1
1   bar  2
>>> df2
      a  c
0   foo  3
1   baz  4

>>> df1.merge(df2, how='inner', on='a')
      a  b  c
0   foo  1  3

>>> df1.merge(df2, how='left', on='a')
      a  b  c
0   foo  1  3.0
1   bar  2  NaN

>>> df1 = pd.DataFrame({'left': ['foo', 'bar']})
>>> df2 = pd.DataFrame({'right': [7, 8]})
>>> df1
    left
0   foo
1   bar
>>> df2
    right
0   7
1   8

>>> df1.merge(df2, how='cross')
   left  right
0   foo      7
1   foo      8
2   bar      7
3   bar      8


pandas.merge_asof   pandas.merge_asof(left, right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, by=None, left_by=None, right_by=None, suffixes=('_x', '_y'), tolerance=None, allow_exact_matches=True, direction='backward')[source]

Perform a merge by key distance. This is similar to a left-join except that we match on nearest key rather than equal keys. Both DataFrames must be sorted by the key. For each row in the left DataFrame:
 A “backward” search selects the last row in the right DataFrame whose ‘on’ key is less than or equal to the left’s key. A “forward” search selects the first row in the right DataFrame whose ‘on’ key is greater than or equal to the left’s key. A “nearest” search selects the row in the right DataFrame whose ‘on’ key is closest in absolute distance to the left’s key.
 The default is “backward” and is compatible in versions below 0.20.0. The direction parameter was added in version 0.20.0 and introduces “forward” and “nearest”. Optionally match on equivalent keys with ‘by’ before searching with ‘on’.  Parameters

left:DataFrame or named Series

right:DataFrame or named Series

on:label

Field name to join on. Must be found in both DataFrames. The data MUST be ordered. Furthermore this must be a numeric column, such as datetimelike, integer, or float. On or left_on/right_on must be given.
left_on:label

Field name to join on in left DataFrame.
right_on:label

Field name to join on in right DataFrame.
left_index:bool

Use the index of the left DataFrame as the join key.
right_index:bool

Use the index of the right DataFrame as the join key.
by:column name or list of column names

Match on these columns before performing merge operation.
left_by:column name

Field names to match on in the left DataFrame.
right_by:column name

Field names to match on in the right DataFrame.
suffixes:2-length sequence (tuple, list, …)

Suffix to apply to overlapping column names in the left and right side, respectively.
tolerance:int or Timedelta, optional, default None

Select asof tolerance within this range; must be compatible with the merge index.
allow_exact_matches:bool, default True

 If True, allow matching with the same ‘on’ value (i.e. less-than-or-equal-to / greater-than-or-equal-to) If False, don’t match the same ‘on’ value (i.e., strictly less-than / strictly greater-than).
direction:‘backward’ (default), ‘forward’, or ‘nearest’

Whether to search for prior, subsequent, or closest matches.    Returns

merged:DataFrame

    See also  merge

Merge with a database-style join.  merge_ordered

Merge with optional filling/interpolation.    Examples
>>> left = pd.DataFrame({"a": [1, 5, 10], "left_val": ["a", "b", "c"]})
>>> left
    a left_val
0   1        a
1   5        b
2  10        c

>>> right = pd.DataFrame({"a": [1, 2, 3, 6, 7], "right_val": [1, 2, 3, 6, 7]})
>>> right
   a  right_val
0  1          1
1  2          2
2  3          3
3  6          6
4  7          7

>>> pd.merge_asof(left, right, on="a")
    a left_val  right_val
0   1        a          1
1   5        b          3
2  10        c          7

>>> pd.merge_asof(left, right, on="a", allow_exact_matches=False)
    a left_val  right_val
0   1        a        NaN
1   5        b        3.0
2  10        c        7.0

>>> pd.merge_asof(left, right, on="a", direction="forward")
    a left_val  right_val
0   1        a        1.0
1   5        b        6.0
2  10        c        NaN

>>> pd.merge_asof(left, right, on="a", direction="nearest")
    a left_val  right_val
0   1        a          1
1   5        b          6
2  10        c          7
  We can use indexed DataFrames as well.
>>> left = pd.DataFrame({"left_val": ["a", "b", "c"]}, index=[1, 5, 10])
>>> left
   left_val
1         a
5         b
10        c

>>> right = pd.DataFrame({"right_val": [1, 2, 3, 6, 7]}, index=[1, 2, 3, 6, 7])
>>> right
   right_val
1          1
2          2
3          3
6          6
7          7

>>> pd.merge_asof(left, right, left_index=True, right_index=True)
   left_val  right_val
1         a          1
5         b          3
10        c          7
  Here is a real-world times-series example
>>> quotes = pd.DataFrame(
...     {
...         "time": [
...             pd.Timestamp("2016-05-25 13:30:00.023"),
...             pd.Timestamp("2016-05-25 13:30:00.023"),
...             pd.Timestamp("2016-05-25 13:30:00.030"),
...             pd.Timestamp("2016-05-25 13:30:00.041"),
...             pd.Timestamp("2016-05-25 13:30:00.048"),
...             pd.Timestamp("2016-05-25 13:30:00.049"),
...             pd.Timestamp("2016-05-25 13:30:00.072"),
...             pd.Timestamp("2016-05-25 13:30:00.075")
...         ],
...         "ticker": [
...                "GOOG",
...                "MSFT",
...                "MSFT",
...                "MSFT",
...                "GOOG",
...                "AAPL",
...                "GOOG",
...                "MSFT"
...            ],
...            "bid": [720.50, 51.95, 51.97, 51.99, 720.50, 97.99, 720.50, 52.01],
...            "ask": [720.93, 51.96, 51.98, 52.00, 720.93, 98.01, 720.88, 52.03]
...     }
... )
>>> quotes
                     time ticker     bid     ask
0 2016-05-25 13:30:00.023   GOOG  720.50  720.93
1 2016-05-25 13:30:00.023   MSFT   51.95   51.96
2 2016-05-25 13:30:00.030   MSFT   51.97   51.98
3 2016-05-25 13:30:00.041   MSFT   51.99   52.00
4 2016-05-25 13:30:00.048   GOOG  720.50  720.93
5 2016-05-25 13:30:00.049   AAPL   97.99   98.01
6 2016-05-25 13:30:00.072   GOOG  720.50  720.88
7 2016-05-25 13:30:00.075   MSFT   52.01   52.03

>>> trades = pd.DataFrame(
...        {
...            "time": [
...                pd.Timestamp("2016-05-25 13:30:00.023"),
...                pd.Timestamp("2016-05-25 13:30:00.038"),
...                pd.Timestamp("2016-05-25 13:30:00.048"),
...                pd.Timestamp("2016-05-25 13:30:00.048"),
...                pd.Timestamp("2016-05-25 13:30:00.048")
...            ],
...            "ticker": ["MSFT", "MSFT", "GOOG", "GOOG", "AAPL"],
...            "price": [51.95, 51.95, 720.77, 720.92, 98.0],
...            "quantity": [75, 155, 100, 100, 100]
...        }
...    )
>>> trades
                     time ticker   price  quantity
0 2016-05-25 13:30:00.023   MSFT   51.95        75
1 2016-05-25 13:30:00.038   MSFT   51.95       155
2 2016-05-25 13:30:00.048   GOOG  720.77       100
3 2016-05-25 13:30:00.048   GOOG  720.92       100
4 2016-05-25 13:30:00.048   AAPL   98.00       100
  By default we are taking the asof of the quotes
>>> pd.merge_asof(trades, quotes, on="time", by="ticker")
                     time ticker   price  quantity     bid     ask
0 2016-05-25 13:30:00.023   MSFT   51.95        75   51.95   51.96
1 2016-05-25 13:30:00.038   MSFT   51.95       155   51.97   51.98
2 2016-05-25 13:30:00.048   GOOG  720.77       100  720.50  720.93
3 2016-05-25 13:30:00.048   GOOG  720.92       100  720.50  720.93
4 2016-05-25 13:30:00.048   AAPL   98.00       100     NaN     NaN
  We only asof within 2ms between the quote time and the trade time
>>> pd.merge_asof(
...     trades, quotes, on="time", by="ticker", tolerance=pd.Timedelta("2ms")
... )
                     time ticker   price  quantity     bid     ask
0 2016-05-25 13:30:00.023   MSFT   51.95        75   51.95   51.96
1 2016-05-25 13:30:00.038   MSFT   51.95       155     NaN     NaN
2 2016-05-25 13:30:00.048   GOOG  720.77       100  720.50  720.93
3 2016-05-25 13:30:00.048   GOOG  720.92       100  720.50  720.93
4 2016-05-25 13:30:00.048   AAPL   98.00       100     NaN     NaN
  We only asof within 10ms between the quote time and the trade time and we exclude exact matches on time. However prior data will propagate forward
>>> pd.merge_asof(
...     trades,
...     quotes,
...     on="time",
...     by="ticker",
...     tolerance=pd.Timedelta("10ms"),
...     allow_exact_matches=False
... )
                     time ticker   price  quantity     bid     ask
0 2016-05-25 13:30:00.023   MSFT   51.95        75     NaN     NaN
1 2016-05-25 13:30:00.038   MSFT   51.95       155   51.97   51.98
2 2016-05-25 13:30:00.048   GOOG  720.77       100     NaN     NaN
3 2016-05-25 13:30:00.048   GOOG  720.92       100     NaN     NaN
4 2016-05-25 13:30:00.048   AAPL   98.00       100     NaN     NaN


pandas.merge_ordered   pandas.merge_ordered(left, right, on=None, left_on=None, right_on=None, left_by=None, right_by=None, fill_method=None, suffixes=('_x', '_y'), how='outer')[source]

Perform a merge for ordered data with optional filling/interpolation. Designed for ordered data like time series data. Optionally perform group-wise merge (see examples).  Parameters

left:DataFrame

right:DataFrame

on:label or list

Field names to join on. Must be found in both DataFrames.
left_on:label or list, or array-like

Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns.
right_on:label or list, or array-like

Field names to join on in right DataFrame or vector/list of vectors per left_on docs.
left_by:column name or list of column names

Group left DataFrame by group columns and merge piece by piece with right DataFrame.
right_by:column name or list of column names

Group right DataFrame by group columns and merge piece by piece with left DataFrame.
fill_method:{‘ffill’, None}, default None

Interpolation method for data.
suffixes:list-like, default is (“_x”, “_y”)

A length-2 sequence where each element is optionally a string indicating the suffix to add to overlapping column names in left and right respectively. Pass a value of None instead of a string to indicate that the column name from left or right should be left as-is, with no suffix. At least one of the values must not be None.  Changed in version 0.25.0.
how:{‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘outer’

 left: use only keys from left frame (SQL: left outer join) right: use only keys from right frame (SQL: right outer join) outer: use union of keys from both frames (SQL: full outer join) inner: use intersection of keys from both frames (SQL: inner join).     Returns
 DataFrame

The merged DataFrame output type will the be same as ‘left’, if it is a subclass of DataFrame.      See also  merge

Merge with a database-style join.  merge_asof

Merge on nearest keys.    Examples
>>> df1 = pd.DataFrame(
...     {
...         "key": ["a", "c", "e", "a", "c", "e"],
...         "lvalue": [1, 2, 3, 1, 2, 3],
...         "group": ["a", "a", "a", "b", "b", "b"]
...     }
... )
>>> df1
      key  lvalue group
0   a       1     a
1   c       2     a
2   e       3     a
3   a       1     b
4   c       2     b
5   e       3     b

>>> df2 = pd.DataFrame({"key": ["b", "c", "d"], "rvalue": [1, 2, 3]})
>>> df2
      key  rvalue
0   b       1
1   c       2
2   d       3

>>> merge_ordered(df1, df2, fill_method="ffill", left_by="group")
  key  lvalue group  rvalue
0   a       1     a     NaN
1   b       1     a     1.0
2   c       2     a     2.0
3   d       2     a     3.0
4   e       3     a     3.0
5   a       1     b     NaN
6   b       1     b     1.0
7   c       2     b     2.0
8   d       2     b     3.0
9   e       3     b     3.0


pandas.MultiIndex   classpandas.MultiIndex(levels=None, codes=None, sortorder=None, names=None, dtype=None, copy=False, name=None, verify_integrity=True)[source]

A multi-level, or hierarchical, index object for pandas objects.  Parameters

levels:sequence of arrays

The unique labels for each level.
codes:sequence of arrays

Integers for each level designating which label at each location.
sortorder:optional int

Level of sortedness (must be lexicographically sorted by that level).
names:optional sequence of objects

Names for each of the index levels. (name is accepted for compat).
copy:bool, default False

Copy the meta-data.
verify_integrity:bool, default True

Check that the levels/codes are consistent and valid.      See also  MultiIndex.from_arrays

Convert list of arrays to MultiIndex.  MultiIndex.from_product

Create a MultiIndex from the cartesian product of iterables.  MultiIndex.from_tuples

Convert list of tuples to a MultiIndex.  MultiIndex.from_frame

Make a MultiIndex from a DataFrame.  Index

The base pandas Index type.    Notes See the user guide for more. Examples A new MultiIndex is typically constructed using one of the helper methods MultiIndex.from_arrays(), MultiIndex.from_product() and MultiIndex.from_tuples(). For example (using .from_arrays):
>>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
>>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))
MultiIndex([(1,  'red'),
            (1, 'blue'),
            (2,  'red'),
            (2, 'blue')],
           names=['number', 'color'])
  See further examples for how to construct a MultiIndex in the doc strings of the mentioned helper methods. Attributes
names Names of levels in MultiIndex.
nlevels Integer number of levels in this MultiIndex.
levshape A tuple with the length of each level.
levels
codes     Methods
from_arrays(arrays[, sortorder, names]) Convert arrays to MultiIndex.
from_tuples(tuples[, sortorder, names]) Convert list of tuples to MultiIndex.
from_product(iterables[, sortorder, names]) Make a MultiIndex from the cartesian product of multiple iterables.
from_frame(df[, sortorder, names]) Make a MultiIndex from a DataFrame.
set_levels(levels[, level, inplace, ...]) Set new levels on MultiIndex.
set_codes(codes[, level, inplace, ...]) Set new codes on MultiIndex.
to_frame([index, name]) Create a DataFrame with the levels of the MultiIndex as columns.
to_flat_index() Convert a MultiIndex to an Index of Tuples containing the level values.
sortlevel([level, ascending, sort_remaining]) Sort MultiIndex at the requested level.
droplevel([level]) Return index with requested level(s) removed.
swaplevel([i, j]) Swap level i with level j.
reorder_levels(order) Rearrange levels using input order.
remove_unused_levels() Create new MultiIndex from current that removes unused levels.
get_locs(seq) Get location for a sequence of labels.


pandas.MultiIndex.codes   propertyMultiIndex.codes


pandas.MultiIndex.droplevel   MultiIndex.droplevel(level=0)[source]

Return index with requested level(s) removed. If resulting index has only 1 level left, the result will be of Index type, not MultiIndex.  Parameters

level:int, str, or list-like, default 0

If a string is given, must be the name of a level If list-like, elements must be names or indexes of levels.    Returns
 Index or MultiIndex
   Examples
>>> mi = pd.MultiIndex.from_arrays(
... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z'])
>>> mi
MultiIndex([(1, 3, 5),
            (2, 4, 6)],
           names=['x', 'y', 'z'])

>>> mi.droplevel()
MultiIndex([(3, 5),
            (4, 6)],
           names=['y', 'z'])

>>> mi.droplevel(2)
MultiIndex([(1, 3),
            (2, 4)],
           names=['x', 'y'])

>>> mi.droplevel('z')
MultiIndex([(1, 3),
            (2, 4)],
           names=['x', 'y'])

>>> mi.droplevel(['x', 'y'])
Int64Index([5, 6], dtype='int64', name='z')


pandas.MultiIndex.dtypes   MultiIndex.dtypes

Return the dtypes as a Series for the underlying MultiIndex.


pandas.MultiIndex.from_arrays   classmethodMultiIndex.from_arrays(arrays, sortorder=None, names=NoDefault.no_default)[source]

Convert arrays to MultiIndex.  Parameters

arrays:list / sequence of array-likes

Each array-like gives one level’s value for each data point. len(arrays) is the number of levels.
sortorder:int or None

Level of sortedness (must be lexicographically sorted by that level).
names:list / sequence of str, optional

Names for the levels in the index.    Returns
 MultiIndex
    See also  MultiIndex.from_tuples

Convert list of tuples to MultiIndex.  MultiIndex.from_product

Make a MultiIndex from cartesian product of iterables.  MultiIndex.from_frame

Make a MultiIndex from a DataFrame.    Examples
>>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
>>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))
MultiIndex([(1,  'red'),
            (1, 'blue'),
            (2,  'red'),
            (2, 'blue')],
           names=['number', 'color'])


pandas.MultiIndex.from_frame   classmethodMultiIndex.from_frame(df, sortorder=None, names=None)[source]

Make a MultiIndex from a DataFrame.  Parameters

df:DataFrame

DataFrame to be converted to MultiIndex.
sortorder:int, optional

Level of sortedness (must be lexicographically sorted by that level).
names:list-like, optional

If no names are provided, use the column names, or tuple of column names if the columns is a MultiIndex. If a sequence, overwrite names with the given sequence.    Returns
 MultiIndex

The MultiIndex representation of the given DataFrame.      See also  MultiIndex.from_arrays

Convert list of arrays to MultiIndex.  MultiIndex.from_tuples

Convert list of tuples to MultiIndex.  MultiIndex.from_product

Make a MultiIndex from cartesian product of iterables.    Examples
>>> df = pd.DataFrame([['HI', 'Temp'], ['HI', 'Precip'],
...                    ['NJ', 'Temp'], ['NJ', 'Precip']],
...                   columns=['a', 'b'])
>>> df
      a       b
0    HI    Temp
1    HI  Precip
2    NJ    Temp
3    NJ  Precip

>>> pd.MultiIndex.from_frame(df)
MultiIndex([('HI',   'Temp'),
            ('HI', 'Precip'),
            ('NJ',   'Temp'),
            ('NJ', 'Precip')],
           names=['a', 'b'])
  Using explicit names, instead of the column names
>>> pd.MultiIndex.from_frame(df, names=['state', 'observation'])
MultiIndex([('HI',   'Temp'),
            ('HI', 'Precip'),
            ('NJ',   'Temp'),
            ('NJ', 'Precip')],
           names=['state', 'observation'])


pandas.MultiIndex.from_product   classmethodMultiIndex.from_product(iterables, sortorder=None, names=NoDefault.no_default)[source]

Make a MultiIndex from the cartesian product of multiple iterables.  Parameters

iterables:list / sequence of iterables

Each iterable has unique labels for each level of the index.
sortorder:int or None

Level of sortedness (must be lexicographically sorted by that level).
names:list / sequence of str, optional

Names for the levels in the index.  Changed in version 1.0.0: If not explicitly provided, names will be inferred from the elements of iterables if an element has a name attribute     Returns
 MultiIndex
    See also  MultiIndex.from_arrays

Convert list of arrays to MultiIndex.  MultiIndex.from_tuples

Convert list of tuples to MultiIndex.  MultiIndex.from_frame

Make a MultiIndex from a DataFrame.    Examples
>>> numbers = [0, 1, 2]
>>> colors = ['green', 'purple']
>>> pd.MultiIndex.from_product([numbers, colors],
...                            names=['number', 'color'])
MultiIndex([(0,  'green'),
            (0, 'purple'),
            (1,  'green'),
            (1, 'purple'),
            (2,  'green'),
            (2, 'purple')],
           names=['number', 'color'])


pandas.MultiIndex.from_tuples   classmethodMultiIndex.from_tuples(tuples, sortorder=None, names=None)[source]

Convert list of tuples to MultiIndex.  Parameters

tuples:list / sequence of tuple-likes

Each tuple is the index of one row/column.
sortorder:int or None

Level of sortedness (must be lexicographically sorted by that level).
names:list / sequence of str, optional

Names for the levels in the index.    Returns
 MultiIndex
    See also  MultiIndex.from_arrays

Convert list of arrays to MultiIndex.  MultiIndex.from_product

Make a MultiIndex from cartesian product of iterables.  MultiIndex.from_frame

Make a MultiIndex from a DataFrame.    Examples
>>> tuples = [(1, 'red'), (1, 'blue'),
...           (2, 'red'), (2, 'blue')]
>>> pd.MultiIndex.from_tuples(tuples, names=('number', 'color'))
MultiIndex([(1,  'red'),
            (1, 'blue'),
            (2,  'red'),
            (2, 'blue')],
           names=['number', 'color'])


pandas.MultiIndex.get_indexer   MultiIndex.get_indexer(target, method=None, limit=None, tolerance=None)[source]

Compute indexer and mask for new index given the current index. The indexer should be then used as an input to ndarray.take to align the current data to the new index.  Parameters

target:Index

method:{None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’}, optional

 default: exact matches only. pad / ffill: find the PREVIOUS index value if no exact match. backfill / bfill: use NEXT index value if no exact match nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value.
limit:int, optional

Maximum number of consecutive labels in target to match for inexact matches.
tolerance:optional

Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations must satisfy the equation abs(index[indexer] - target) <= tolerance. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index’s type.    Returns

indexer:np.ndarray[np.intp]

Integers from 0 to n - 1 indicating that the index at these positions matches the corresponding target values. Missing values in the target are marked by -1.     Notes Returns -1 for unmatched values, for further explanation see the example below. Examples
>>> index = pd.Index(['c', 'a', 'b'])
>>> index.get_indexer(['a', 'b', 'x'])
array([ 1,  2, -1])
  Notice that the return value is an array of locations in index and x is marked by -1, as it is not in index.


pandas.MultiIndex.get_level_values   MultiIndex.get_level_values(level)[source]

Return vector of label values for requested level. Length of returned vector is equal to the length of the index.  Parameters

level:int or str

level is either the integer position of the level in the MultiIndex, or the name of the level.    Returns

values:Index

Values is a level of this MultiIndex converted to a single Index (or subclass thereof).     Notes If the level contains missing values, the result may be casted to float with missing values specified as NaN. This is because the level is converted to a regular Index. Examples Create a MultiIndex:
>>> mi = pd.MultiIndex.from_arrays((list('abc'), list('def')))
>>> mi.names = ['level_1', 'level_2']
  Get level values by supplying level as either integer or name:
>>> mi.get_level_values(0)
Index(['a', 'b', 'c'], dtype='object', name='level_1')
>>> mi.get_level_values('level_2')
Index(['d', 'e', 'f'], dtype='object', name='level_2')
  If a level contains missing values, the return type of the level maybe casted to float.
>>> pd.MultiIndex.from_arrays([[1, None, 2], [3, 4, 5]]).dtypes
level_0    int64
level_1    int64
dtype: object
>>> pd.MultiIndex.from_arrays([[1, None, 2], [3, 4, 5]]).get_level_values(0)
Float64Index([1.0, nan, 2.0], dtype='float64')


pandas.MultiIndex.get_loc   MultiIndex.get_loc(key, method=None)[source]

Get location for a label or a tuple of labels. The location is returned as an integer/slice or boolean mask.  Parameters

key:label or tuple of labels (one for each level)

method:None

  Returns

loc:int, slice object or boolean mask

If the key is past the lexsort depth, the return may be a boolean mask array, otherwise it is always a slice or int.      See also  Index.get_loc

The get_loc method for (single-level) index.  MultiIndex.slice_locs

Get slice location given start label(s) and end label(s).  MultiIndex.get_locs

Get location for a label/slice/list/mask or a sequence of such.    Notes The key cannot be a slice, list of same-level labels, a boolean mask, or a sequence of such. If you want to use those, use MultiIndex.get_locs() instead. Examples
>>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')])

>>> mi.get_loc('b')
slice(1, 3, None)

>>> mi.get_loc(('b', 'e'))
1