Find indices where elements should be inserted to maintain order.
Find the indices into a sorted Index self such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved.
Note
The Index must be monotonically sorted, otherwise wrong locations will likely be returned. Pandas does not check this for you.
Values to insert into self.
If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of self).
Optional array of integer indices that sort self into ascending order. They are typically the result of np.argsort.
A scalar or array of insertion points with the same shape as value.
See also
Sort by the values along either axis.
Similar method from NumPy.
Notes
Binary search is used to find the required insertion points.
Examples
If the values are not monotonically sorted, wrong locations may be returned:


Set Index or MultiIndex name.
Able to set new names partially and by level.
Name(s) to set.
Changed in version 1.3.0.
If the index is a MultiIndex and names is not dict-like, level(s) to set (None for all levels). Otherwise level must be None.
Changed in version 1.3.0.
Modifies the object directly, instead of creating a new Index or MultiIndex.
The same type as the caller or None if inplace=True.
See also
Able to set new names without level.
Examples
When renaming levels with a dict, levels can not be passed.


Fast lookup of value from 1-dimensional ndarray.
Deprecated since version 1.0.
Notes
Only use this if you know what you’re doing.


Return a tuple of the shape of the underlying data.


Shift index by desired number of time frequency increments.
This method is for shifting the values of datetime-like indexes by a specified time increment a given number of times.
Number of periods (or increments) to shift by, can be positive or negative.
Frequency increment to shift by. If None, the index is shifted by its own freq attribute. Offset aliases are valid strings, e.g., ‘D’, ‘W’, ‘M’ etc.
Shifted index.
See also
Shift values of Series.
Notes
This method is only implemented for datetime-like index classes, i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex.
Examples
Put the first 5 month starts of 2011 into an index.
Shift the index by 10 days.
The default value of freq is the freq attribute of the index, which is ‘MS’ (month start) in this example.


Return the number of elements in the underlying data.


Compute the slice indexer for input labels and step.
Index needs to be ordered and unique.
If None, defaults to the beginning.
If None, defaults to the end.
Deprecated since version 1.4.0.
not ordered.
Notes
This function assumes that the data is sorted, so use at your own peril
Examples
This is a method on all index types. For example you can do:


Compute slice locations for input labels.
If None, defaults to the beginning.
If None, defaults to the end.
If None, defaults to 1.
Deprecated since version 1.4.0.
See also
Get location for a single label.
Notes
This method only works if the index is monotonic or unique.
Examples


Return a sorted copy of the index.
Return a sorted copy of the index, and optionally return the indices that sorted the index itself.
Should the indices that would sort the index be returned.
Should the index values be sorted in an ascending order.
Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.
New in version 1.2.0.
If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape.
New in version 1.1.0.
Sorted copy of the index.
The indices that the index itself was sorted by.
See also
Sort values of a Series.
Sort values in a DataFrame.
Examples
Sort values in ascending order (default behavior).
Sort values in descending order, and also get the indices idx was sorted by.


For internal compatibility with the Index API.
Sort the Index. This is for compat with MultiIndex
False to sort in descending order


Vectorized string functions for Series and Index.
NAs stay NA unless handled otherwise by a particular method. Patterned after Python’s string methods, with some inspiration from R’s stringr package.
Examples


Compute the symmetric difference of two Index objects.
Whether to sort the resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas.
None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements.
False : Do not sort the result.
Notes
symmetric_difference contains elements that appear in either idx1 or idx2 but not both. Equivalent to the Index created by idx1.difference(idx2) | idx2.difference(idx1) with duplicates dropped.
Examples


Return the transpose, which is by definition self.


Return a new Index of the values selected by the indices.
For internal compatibility with numpy arrays.
Indices to be taken.
The axis over which to select values, always 0.
If allow_fill=True and fill_value is not None, indices specified by -1 are regarded as NA. If Index doesn’t hold NA, raise ValueError.
An index formed of elements at the given indices. Will be the same type as self, except for RangeIndex.
See also
Return an array formed from the elements of a at the given indices.


Identity method.
This is implemented for compatibility with subclass implementations when chaining.
Caller.
See also
Subclass implementation.


Create a DataFrame with a column containing the Index.
Set the index of the returned DataFrame as the original Index.
The passed name should substitute for the index name (if it has one).
DataFrame containing the original Index data.
See also
Convert an Index to a Series.
Convert Series to DataFrame.
Examples
By default, the original Index is reused. To enforce a new Index:
To override the name of the resulting column, specify name:


Return a list of the values.
These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period)
See also
Return the array as an a.ndim-levels deep nested list of Python scalars.


Format specified values of self and return them.
Deprecated since version 1.2.0.
An indexer into self that specifies which values are used in the formatting process.
Options for specifying how the values should be formatted. These options include the following:
The value that serves as a placeholder for NULL values
Whether or not there are quoted values in self
The format used to represent date-like values.
Formatted values.


A NumPy ndarray representing the values in this Series or Index.
The dtype to pass to numpy.asarray().
Whether to ensure that the returned value is not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not strictly necessary.
The value to use for missing values. The default value depends on dtype and the type of the array.
New in version 1.0.0.
Additional keywords passed through to the to_numpy method of the underlying array (for extension arrays).
New in version 1.0.0.
See also
Get the actual data stored within.
Get the actual data stored within.
Similar method for DataFrame.
Notes
The returned array will be the same up to equality (values equal in self will be equal in the returned array; likewise for values that are not equal). When self contains an ExtensionArray, the dtype may be different. For example, for a category-dtype Series, to_numpy() will return a NumPy array and the categorical dtype will be lost.
For NumPy dtypes, this will be a reference to the actual data stored in this Series or Index (assuming copy=False). Modifying the result in place will modify the data stored in the Series or Index (not that we recommend doing that).
For extension types, to_numpy() may require copying data and coercing the result to a NumPy type (possibly object), which may be expensive. When you need a no-copy reference to the underlying data, Series.array should be used instead.
This table lays out the different dtypes and default return types of to_numpy() for various dtypes within pandas.
dtype
array type
category[T]
ndarray[T] (same dtype as input)
period
ndarray[object] (Periods)
interval
ndarray[object] (Intervals)
IntegerNA
ndarray[object]
datetime64[ns]
datetime64[ns]
datetime64[ns, tz]
ndarray[object] (Timestamps)
Examples
Specify the dtype to control how datetime-aware data is represented. Use dtype=object to return an ndarray of pandas Timestamp objects, each with the correct tz.
Or dtype='datetime64[ns]' to return an ndarray of native datetime64 values. The values are converted to UTC and the timezone info is dropped.


Create a Series with both index and values equal to the index keys.
Useful with map for returning an indexer based on an index.
Index of resulting Series. If None, defaults to original index.
Name of resulting Series. If None, defaults to name of original index.
The dtype will be based on the type of the Index values.
See also
Convert an Index to a DataFrame.
Convert Series to DataFrame.
Examples
By default, the original Index and original name is reused.
To enforce a new Index, specify new labels to index:
To override the name of the resulting column, specify name:


Form the union of two Index objects.
If the Index objects are incompatible, both Index objects will be cast to dtype(‘object’) first.
Changed in version 0.25.0.
Whether to sort the resulting Index.
None : Sort the result, except when
self and other are equal.
self or other has length 0.
Some values in self or other cannot be compared. A RuntimeWarning is issued in this case.
False : do not sort the result.
Examples
Union matching dtypes
Union mismatched dtypes
MultiIndex case


Return unique values in the index.
Unique values are returned in order of appearance, this does NOT sort.
Only return values from specified level (for MultiIndex). If int, gets the level by integer position, else by level name.
See also
Numpy array of unique values in that column.
Return unique values of Series object.


Return a Series containing counts of unique values.
The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.
If True then the object returned will contain the relative frequencies of the unique values.
Sort by frequencies.
Sort in ascending order.
Rather than count values, group them into half-open bins, a convenience for pd.cut, only works with numeric data.
Don’t include counts of NaN.
See also
Number of non-NA elements in a Series.
Number of non-NA elements in a DataFrame.
Equivalent method on DataFrames.
Examples
With normalize set to True, returns the relative frequency by dividing all values by the sum of values.
bins
Bins can be useful for going from a continuous variable to a categorical variable; instead of counting unique apparitions of values, divide the index in the specified number of half-open bins.
dropna
With dropna set to False we can also see NaN index values.


Return an array representing the data in the Index.
Warning
We recommend using Index.array or Index.to_numpy(), depending on whether you need a reference to the underlying data or a NumPy array.
See also
Reference to the underlying data.
A NumPy array representing the underlying data.


Replace values where the condition is False.
The replacement is taken from other.
Condition to select the values on.
Replacement if the condition is False.
A copy of self with values replaced from other where the condition is False.
See also
Same method for Series.
Same method for DataFrame.
Examples


Create an object to more easily perform multi-index slicing.
See also
New MultiIndex with no unused levels.
Notes
See Defined Levels for further info on slicing a MultiIndex.
Examples
Using the default slice command:
Using the IndexSlice class for a more intuitive command:


Infer the most likely frequency given the input index. If the frequency is uncertain, a warning will be printed.
If passed a Series will use the values of the series (NOT THE INDEX).
None if no discernible frequency.
If the index is not datetime-like.
If there are fewer than three values.
Examples


An ExtensionDtype for int16 integer data.
Changed in version 1.0.0: Now uses pandas.NA as its missing value, rather than numpy.nan.
Attributes
None
Methods
None


An ExtensionDtype for int32 integer data.
Changed in version 1.0.0: Now uses pandas.NA as its missing value, rather than numpy.nan.
Attributes
None
Methods
None


An ExtensionDtype for int64 integer data.
Changed in version 1.0.0: Now uses pandas.NA as its missing value, rather than numpy.nan.
Attributes
None
Methods
None


Immutable sequence used for indexing and alignment. The basic object storing axis labels for all pandas objects. Int64Index is a special case of Index with purely integer labels. .
Deprecated since version 1.4.0: In pandas v2.0 Int64Index will be removed and NumericIndex used instead. Int64Index will remain fully functional for the duration of pandas 1.x.
Make a copy of input ndarray.
Name to be stored in the index.
See also
The base pandas Index type.
Index of numpy int/uint/float data.
Notes
An Index instance can only contain hashable objects.
Attributes
None
Methods
None


An ExtensionDtype for int8 integer data.
Changed in version 1.0.0: Now uses pandas.NA as its missing value, rather than numpy.nan.
Attributes
None
Methods
None


Immutable object implementing an Interval, a bounded slice-like interval.
Left bound for the interval.
Right bound for the interval.
Whether the interval is closed on the left-side, right-side, both or neither. See the Notes for more detailed explanation.
See also
An Index of Interval objects that are all closed on the same side.
Convert continuous data into discrete bins (Categorical of Interval objects).
Convert continuous data into bins (Categorical of Interval objects) based on quantiles.
Represents a period of time.
Notes
The parameters left and right must be from the same type, you must be able to compare them and they must satisfy left <= right.
A closed interval (in mathematics denoted by square brackets) contains its endpoints, i.e. the closed interval [0, 5] is characterized by the conditions 0 <= x <= 5. This is what closed='both' stands for. An open interval (in mathematics denoted by parentheses) does not contain its endpoints, i.e. the open interval (0, 5) is characterized by the conditions 0 < x < 5. This is what closed='neither' stands for. Intervals can also be half-open or half-closed, i.e. [0, 5) is described by 0 <= x < 5 (closed='left') and (0, 5] is described by 0 < x <= 5 (closed='right').
Examples
It is possible to build Intervals of different types, like numeric ones:
You can check if an element belongs to it
You can test the bounds (closed='right', so 0 < x <= 5):
Calculate its length
You can operate with + and * over an Interval and the operation is applied to each of its bounds, so the result depends on the type of the bound elements
To create a time interval you can use Timestamps as the bounds
Attributes
closed
Whether the interval is closed on the left-side, right-side, both or neither.
closed_left
Check if the interval is closed on the left side.
closed_right
Check if the interval is closed on the right side.
is_empty
Indicates if an interval is empty, meaning it contains no points.
left
Left bound for the interval.
length
Return the length of the Interval.
mid
Return the midpoint of the Interval.
open_left
Check if the interval is open on the left side.
open_right
Check if the interval is open on the right side.
right
Right bound for the interval.
Methods
overlaps
Check whether two Interval objects overlap.


Whether the interval is closed on the left-side, right-side, both or neither.


Check if the interval is closed on the left side.
For the meaning of closed and open see Interval.
True if the Interval is closed on the left-side.


Check if the interval is closed on the right side.
For the meaning of closed and open see Interval.
True if the Interval is closed on the left-side.


Indicates if an interval is empty, meaning it contains no points.
New in version 0.25.0.
A boolean indicating if a scalar Interval is empty, or a boolean ndarray positionally indicating if an Interval in an IntervalArray or IntervalIndex is empty.
Examples
An Interval that contains points is not empty:
An Interval that does not contain any points is empty:
An Interval that contains a single point is not empty:
An IntervalArray or IntervalIndex returns a boolean ndarray positionally indicating if an Interval is empty:
Missing values are not considered empty:


Check if the interval is open on the left side.
For the meaning of closed and open see Interval.
True if the Interval is closed on the left-side.


Check if the interval is open on the right side.
For the meaning of closed and open see Interval.
True if the Interval is closed on the left-side.


Check whether two Interval objects overlap.
Two intervals overlap if they share a common point, including closed endpoints. Intervals that only have an open endpoint in common do not overlap.
Interval to check against for an overlap.
True if the two intervals overlap.
See also
The corresponding method for IntervalArray.
The corresponding method for IntervalIndex.
Examples
Intervals that share closed endpoints overlap:
Intervals that only have an open endpoint in common do not overlap:


Return a fixed frequency IntervalIndex.
Left bound for generating intervals.
Right bound for generating intervals.
Number of periods to generate.
The length of each interval. Must be consistent with the type of start and end, e.g. 2 for numeric, or ‘5H’ for datetime-like. Default is 1 for numeric and ‘D’ for datetime-like.
Name of the resulting IntervalIndex.
Whether the intervals are closed on the left-side, right-side, both or neither.
See also
An Index of intervals that are all closed on the same side.
Notes
Of the four parameters start, end, periods, and freq, exactly three must be specified. If freq is omitted, the resulting IntervalIndex will have periods linearly spaced elements between start and end, inclusively.
To learn more about datetime-like frequency strings, please see this link.
Examples
Numeric start and end is supported.
Additionally, datetime-like input is also supported.
The freq parameter specifies the frequency between the left and right. endpoints of the individual intervals within the IntervalIndex. For numeric start and end, the frequency must also be numeric.
Similarly, for datetime-like start and end, the frequency must be convertible to a DateOffset.
Specify start, end, and periods; the frequency is generated automatically (linearly spaced).
The closed parameter specifies which endpoints of the individual intervals within the IntervalIndex are closed.


An ExtensionDtype for Interval data.
This is not an actual numpy dtype, but a duck type.
The dtype of the Interval bounds.
Examples
Attributes
subtype
The dtype of the Interval bounds.
Methods
None


Immutable index of intervals that are closed on the same side.
New in version 0.20.0.
Array-like containing Interval objects from which to build the IntervalIndex.
Whether the intervals are closed on the left-side, right-side, both or neither.
If None, dtype will be inferred.
Copy the input data.
Name to be stored in the index.
Verify that the IntervalIndex is valid.
See also
The base pandas Index type.
A bounded slice-like interval; the elements of an IntervalIndex.
Function to create a fixed frequency IntervalIndex.
Bin values into discrete Intervals.
Bin values into equal-sized Intervals based on rank or sample quantiles.
Notes
See the user guide for more.
Examples
A new IntervalIndex is typically constructed using interval_range():
It may also be constructed using one of the constructor methods: IntervalIndex.from_arrays(), IntervalIndex.from_breaks(), and IntervalIndex.from_tuples().
See further examples in the doc strings of interval_range and the mentioned constructor methods.
Attributes
closed
Whether the intervals are closed on the left-side, right-side, both or neither.
is_empty
Indicates if an interval is empty, meaning it contains no points.
is_non_overlapping_monotonic
Return True if the IntervalArray is non-overlapping (no Intervals share points) and is either monotonic increasing or monotonic decreasing, else False.
is_overlapping
Return True if the IntervalIndex has overlapping intervals, else False.
values
Return an array representing the data in the Index.
left
right
mid
length
Methods
from_arrays(left, right[, closed, name, ...])
Construct from two arrays defining the left and right bounds.
from_tuples(data[, closed, name, copy, dtype])
Construct an IntervalIndex from an array-like of tuples.
from_breaks(breaks[, closed, name, copy, dtype])
Construct an IntervalIndex from an array of splits.
contains(*args, **kwargs)
Check elementwise if the Intervals contain the value.
overlaps(*args, **kwargs)
Check elementwise if an Interval overlaps the values in the IntervalArray.
set_closed(*args, **kwargs)
Return an IntervalArray identical to the current one, but closed on the specified side.
to_tuples(*args, **kwargs)
Return an ndarray of tuples of the form (left, right).


Whether the intervals are closed on the left-side, right-side, both or neither.


Check elementwise if the Intervals contain the value.
Return a boolean mask whether the value is contained in the Intervals of the IntervalArray.
New in version 0.25.0.
The value to check whether it is contained in the Intervals.
See also
Check whether Interval object contains value.
Check if an Interval overlaps the values in the IntervalArray.
Examples


Construct from two arrays defining the left and right bounds.
Left bounds for each interval.
Right bounds for each interval.
Whether the intervals are closed on the left-side, right-side, both or neither.
Copy the data.
If None, dtype will be inferred.
When a value is missing in only one of left or right. When a value in left is greater than the corresponding value in right.
See also
Function to create a fixed frequency IntervalIndex.
Construct an IntervalIndex from an array of splits.
Construct an IntervalIndex from an array-like of tuples.
Notes
Each element of left must be less than or equal to the right element at the same position. If an element is missing, it must be missing in both left and right. A TypeError is raised when using an unsupported type for left or right. At the moment, ‘category’, ‘object’, and ‘string’ subtypes are not supported.
Examples


Construct an IntervalIndex from an array of splits.
Left and right bounds for each interval.
Whether the intervals are closed on the left-side, right-side, both or neither.
Copy the data.
If None, dtype will be inferred.
See also
Function to create a fixed frequency IntervalIndex.
Construct from a left and right array.
Construct from a sequence of tuples.
Examples


Construct an IntervalIndex from an array-like of tuples.
Array of tuples.
Whether the intervals are closed on the left-side, right-side, both or neither.
By-default copy the data, this is compat only and ignored.
If None, dtype will be inferred.
See also
Function to create a fixed frequency IntervalIndex.
Construct an IntervalIndex from a left and right array.
Construct an IntervalIndex from an array of splits.
Examples


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.
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.
Maximum number of consecutive labels in target to match for inexact matches.
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.
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
Notice that the return value is an array of locations in index and x is marked by -1, as it is not in index.


Get integer location, slice or boolean mask for requested label.
default: matches where the label is within an interval only.
Examples
You can also supply a point inside an interval.
If a label is in several intervals, you get the locations of all the relevant intervals.
Only exact matches will be returned if an interval is provided.


Return True if the IntervalArray is non-overlapping (no Intervals share points) and is either monotonic increasing or monotonic decreasing, else False.


Return True if the IntervalIndex has overlapping intervals, else False.
Two intervals overlap if they share a common point, including closed endpoints. Intervals that only have an open endpoint in common do not overlap.
Boolean indicating if the IntervalIndex has overlapping intervals.
See also
Check whether two Interval objects overlap.
Check an IntervalIndex elementwise for overlaps.
Examples
Intervals that share closed endpoints overlap:
Intervals that only have an open endpoint in common do not overlap:


Check elementwise if an Interval overlaps the values in the IntervalArray.
Two intervals overlap if they share a common point, including closed endpoints. Intervals that only have an open endpoint in common do not overlap.
Interval to check against for an overlap.
Boolean array positionally indicating where an overlap occurs.
See also
Check whether two Interval objects overlap.
Examples
Intervals that share closed endpoints overlap:
Intervals that only have an open endpoint in common do not overlap:


Return an IntervalArray identical to the current one, but closed on the specified side.
Whether the intervals are closed on the left-side, right-side, both or neither.
Examples


Return an ndarray of tuples of the form (left, right).
Returns NA as a tuple if True, (nan, nan), or just as the NA value itself if False, nan.


Return an array representing the data in the Index.
Warning
We recommend using Index.array or Index.to_numpy(), depending on whether you need a reference to the underlying data or a NumPy array.
See also
Reference to the underlying data.
A NumPy array representing the underlying data.


Helps style a DataFrame or Series according to the data with HTML and CSS.
Data to be styled - either a Series or DataFrame.
Precision to round floats to. If not given defaults to pandas.options.styler.format.precision.
Changed in version 1.4.0.
List of {selector: (attr, value)} dicts; see Notes.
A unique identifier to avoid CSS collisions; generated automatically.
String caption to attach to the table. Tuple only used for LaTeX dual captions.
Items that show up in the opening <table> tag in addition to automatic (by default) id.
If True, each cell will have an id attribute in their HTML tag. The id takes the form T_<uuid>_row<num_row>_col<num_col> where <uuid> is the unique identifier, <num_row> is the row number and <num_col> is the column number.
Representation for missing values. If na_rep is None, no special formatting is applied, and falls back to pandas.options.styler.format.na_rep.
New in version 1.0.0.
If uuid is not specified, the length of the uuid to randomly generate expressed in hex characters, in range [0, 32].
New in version 1.2.0.
Character used as decimal separator for floats, complex and integers. If not given uses pandas.options.styler.format.decimal.
New in version 1.3.0.
Character used as thousands separator for floats, complex and integers. If not given uses pandas.options.styler.format.thousands.
New in version 1.3.0.
Use ‘html’ to replace the characters &, <, >, ', and " in cell display string with HTML-safe sequences. Use ‘latex’ to replace the characters &, %, $, #, _, {, }, ~, ^, and \ in the cell display string with LaTeX-safe sequences. If not given uses pandas.options.styler.format.escape.
New in version 1.3.0.
Object to define how values are displayed. See Styler.format. If not given uses pandas.options.styler.format.formatter.
New in version 1.4.0.
See also
Return a Styler object containing methods for building a styled HTML representation for the DataFrame.
Notes
Most styling will be done by passing style functions into Styler.apply or Styler.applymap. Style functions should return values with strings containing CSS 'attr: value' that will be applied to the indicated cells.
If using in the Jupyter notebook, Styler has defined a _repr_html_ to automatically render itself. Otherwise call Styler.to_html to get the generated HTML.
CSS classes are attached to the generated HTML
Index and Column names include index_name and level<k> where k is its level in a MultiIndex
Index label cells include
row_heading
row<n> where n is the numeric position of the row
level<k> where k is the level in a MultiIndex
Column label cells include * col_heading * col<n> where n is the numeric position of the column * level<k> where k is the level in a MultiIndex
Blank cells include blank
Data cells include data
Trimmed cells include col_trim or row_trim.
Any, or all, or these classes can be renamed by using the css_class_names argument in Styler.set_table_classes, giving a value such as {“row”: “MY_ROW_CLASS”, “col_trim”: “”, “row_trim”: “”}.
Attributes
env
(Jinja2 jinja2.Environment)
template_html
(Jinja2 Template)
template_html_table
(Jinja2 Template)
template_html_style
(Jinja2 Template)
template_latex
(Jinja2 Template)
loader
(Jinja2 Loader)
Methods
apply(func[, axis, subset])
Apply a CSS-styling function column-wise, row-wise, or table-wise.
apply_index(func[, axis, level])
Apply a CSS-styling function to the index or column headers, level-wise.
applymap(func[, subset])
Apply a CSS-styling function elementwise.
applymap_index(func[, axis, level])
Apply a CSS-styling function to the index or column headers, elementwise.
background_gradient([cmap, low, high, axis, ...])
Color the background in a gradient style.
bar([subset, axis, color, cmap, width, ...])
Draw bar chart in the cell backgrounds.
clear()
Reset the Styler, removing any previously applied styles.
export()
Export the styles applied to the current Styler.
format([formatter, subset, na_rep, ...])
Format the text display value of cells.
format_index([formatter, axis, level, ...])
Format the text display value of index labels or column headers.
from_custom_template(searchpath[, ...])
Factory function for creating a subclass of Styler.
hide([subset, axis, level, names])
Hide the entire index / column headers, or specific rows / columns from display.
hide_columns([subset, level, names])
Hide the column headers or specific keys in the columns from rendering.
hide_index([subset, level, names])
(DEPRECATED) Hide the entire index, or specific keys in the index from rendering.
highlight_between([subset, color, axis, ...])
Highlight a defined range with a style.
highlight_max([subset, color, axis, props])
Highlight the maximum with a style.
highlight_min([subset, color, axis, props])
Highlight the minimum with a style.
highlight_null([null_color, subset, props])
Highlight missing values with a style.
highlight_quantile([subset, color, axis, ...])
Highlight values defined by a quantile with a style.
pipe(func, *args, **kwargs)
Apply func(self, *args, **kwargs), and return the result.
render([sparse_index, sparse_columns])
(DEPRECATED) Render the Styler including all applied styles to HTML.
set_caption(caption)
Set the text added to a <caption> HTML element.
set_na_rep(na_rep)
(DEPRECATED) Set the missing data representation on a Styler.
set_precision(precision)
(DEPRECATED) Set the precision used to display values.
set_properties([subset])
Set defined CSS-properties to each <td> HTML element within the given subset.
set_sticky([axis, pixel_size, levels])
Add CSS to permanently display the index or column headers in a scrolling frame.
set_table_attributes(attributes)
Set the table attributes added to the <table> HTML element.
set_table_styles([table_styles, axis, ...])
Set the table styles included within the <style> HTML element.
set_td_classes(classes)
Set the DataFrame of strings added to the class attribute of <td> HTML elements.
set_tooltips(ttips[, props, css_class])
Set the DataFrame of strings on Styler generating :hover tooltips.
set_uuid(uuid)
Set the uuid applied to id attributes of HTML elements.
text_gradient([cmap, low, high, axis, ...])
Color the text in a gradient style.
to_excel(excel_writer[, sheet_name, na_rep, ...])
Write Styler to an Excel sheet.
to_html([buf, table_uuid, table_attributes, ...])
Write Styler to a file, buffer or string in HTML-CSS format.
to_latex([buf, column_format, position, ...])
Write Styler to a file, buffer or string in LaTeX format.
use(styles)
Set the styles on the current Styler.
where(cond, value[, other, subset])
(DEPRECATED) Apply CSS-styles based on a conditional function elementwise.


Apply a CSS-styling function column-wise, row-wise, or table-wise.
Updates the HTML representation with the result.
func should take a Series if axis in [0,1] and return a list-like object of same length, or a Series, not necessarily of same length, with valid index labels considering subset. func should take a DataFrame if axis is None and return either an ndarray with the same shape or a DataFrame, not necessarily of the same shape, with valid index and columns labels considering subset.
Changed in version 1.3.0.
Changed in version 1.4.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.
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.
Pass along to func.
See also
Apply a CSS-styling function to headers elementwise.
Apply a CSS-styling function to headers level-wise.
Apply a CSS-styling function elementwise.
Notes
The elements of the output of func should be CSS styles as strings, in the format ‘attribute: value; attribute2: value2; …’ or, if nothing is to be applied to that element, an empty string or None.
This is similar to DataFrame.apply, except that axis=None applies the function to the entire DataFrame at once, rather than column-wise or row-wise.
Examples
Using subset to restrict application to a single column or multiple columns
Using a 2d input to subset to select rows in addition to columns
Using a function which returns a Series / DataFrame of unequal length but containing valid index labels
See Table Visualization user guide for more details.


Apply a CSS-styling function to the index or column headers, level-wise.
Updates the HTML representation with the result.
New in version 1.4.0.
func should take a Series and return a string array of the same length.
The headers over which to apply the function.
If index is MultiIndex the level(s) over which to apply the function.
Pass along to func.
See also
Apply a CSS-styling function to headers elementwise.
Apply a CSS-styling function column-wise, row-wise, or table-wise.
Apply a CSS-styling function elementwise.
Notes
Each input to func will be the index as a Series, if an Index, or a level of a MultiIndex. The output of func should be an identically sized array of CSS styles as strings, in the format ‘attribute: value; attribute2: value2; …’ or, if nothing is to be applied to that element, an empty string or None.
Examples
Basic usage to conditionally highlight values in the index.
Selectively applying to specific levels of MultiIndex columns.


Apply a CSS-styling function elementwise.
Updates the HTML representation with the result.
func should take a scalar and return a string.
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.
Pass along to func.
See also
Apply a CSS-styling function to headers elementwise.
Apply a CSS-styling function to headers level-wise.
Apply a CSS-styling function column-wise, row-wise, or table-wise.
Notes
The elements of the output of func should be CSS styles as strings, in the format ‘attribute: value; attribute2: value2; …’ or, if nothing is to be applied to that element, an empty string or None.
Examples
Using subset to restrict application to a single column or multiple columns
Using a 2d input to subset to select rows in addition to columns
See Table Visualization user guide for more details.


Apply a CSS-styling function to the index or column headers, elementwise.
Updates the HTML representation with the result.
New in version 1.4.0.
func should take a scalar and return a string.
The headers over which to apply the function.
If index is MultiIndex the level(s) over which to apply the function.
Pass along to func.
See also
Apply a CSS-styling function to headers level-wise.
Apply a CSS-styling function column-wise, row-wise, or table-wise.
Apply a CSS-styling function elementwise.
Notes
Each input to func will be an index value, if an Index, or a level value of a MultiIndex. The output of func should be CSS styles as a string, in the format ‘attribute: value; attribute2: value2; …’ or, if nothing is to be applied to that element, an empty string or None.
Examples
Basic usage to conditionally highlight values in the index.
Selectively applying to specific levels of MultiIndex columns.


Color the background in a gradient style.
The background color is determined according to the data in each column, row or frame, or by a given gradient map. Requires matplotlib.
Matplotlib colormap.
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.
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.
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.
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.
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.
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.
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.
Gradient map for determining the background 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.
See also
Color the text 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
Shading the values column-wise, with axis=0, preselecting numeric columns
Shading all values collectively using axis=None
Compress the color map from the both low and high ends
Manually setting vmin and vmax gradient thresholds
Setting a gmap and applying to all columns with another cmap
Setting the gradient map for a dataframe (i.e. axis=None), we need to explicitly state subset to match the gmap shape


Draw bar chart in the cell backgrounds.
Changed in version 1.4.0.
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.
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.
If a str is passed, the color is the same for both negative and positive numbers. If 2-tuple/list is used, the first element is the color_negative and the second is the color_positive (eg: [‘#d65f5f’, ‘#5fba7d’]).
A string name of a matplotlib Colormap, or a Colormap object. Cannot be used together with color.
New in version 1.4.0.
The percentage of the cell, measured from the left, in which to draw the bars, in [0, 100].
The percentage height of the bar in the cell, centrally aligned, in [0,100].
New in version 1.4.0.
How to align the bars within the cells relative to a width adjusted center. If string must be one of:
‘left’ : bars are drawn rightwards from the minimum data value.
‘right’ : bars are drawn leftwards from the maximum data value.
‘zero’ : a value of zero is located at the center of the cell.
‘mid’ : a value of (max-min)/2 is located at the center of the cell, or if all values are negative (positive) the zero is aligned at the right (left) of the cell.
‘mean’ : the mean value of the data is located at the center of the cell.
If a float or integer is given this will indicate the center of the cell.
If a callable should take a 1d or 2d array and return a scalar.
Changed in version 1.4.0.
Minimum bar value, defining the left hand limit of the bar drawing range, lower values are clipped to vmin. When None (default): the minimum value of the data will be used.
Maximum bar value, defining the right hand limit of the bar drawing range, higher values are clipped to vmax. When None (default): the maximum value of the data will be used.
The base CSS of the cell that is extended to add the bar chart. Defaults to “width: 10em;”.
New in version 1.4.0.
Notes
This section of the user guide: Table Visualization gives a number of examples for different settings and color coordination.


Reset the Styler, removing any previously applied styles.
Returns None.


Export the styles applied to the current Styler.
Can be applied to a second Styler with Styler.use.
See also
Set the styles on the current Styler.
Create a copy of the current Styler.
Notes
This method is designed to copy non-data dependent attributes of one Styler to another. It differs from Styler.copy where data and data dependent attributes are also copied.
The following items are exported since they are not generally data dependent:
Styling functions added by the apply and applymap
Whether axes and names are hidden from the display, if unambiguous.
Table attributes
Table styles
The following attributes are considered data dependent and therefore not exported:
Caption
UUID
Tooltips
Any hidden rows or columns identified by Index labels
Any formatting applied using Styler.format
Any CSS classes added using Styler.set_td_classes
Examples


Format the text display value of cells.
Object to define how values are displayed. See notes.
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.
Representation for missing values. If na_rep is None, no special formatting is applied.
New in version 1.0.0.
Floating point precision to use for display purposes, if not determined by the specified formatter.
New in version 1.3.0.
Character used as decimal separator for floats, complex and integers.
New in version 1.3.0.
Character used as thousands separator for floats, complex and integers.
New in version 1.3.0.
Use ‘html’ to replace the characters &, <, >, ', and " in cell display string with HTML-safe sequences. Use ‘latex’ to replace the characters &, %, $, #, _, {, }, ~, ^, and \ in the cell display string with LaTeX-safe sequences. Escaping is done before formatter.
New in version 1.3.0.
Convert string patterns containing https://, http://, ftp:// or www. to HTML <a> tags as clickable URL hyperlinks if “html”, or LaTeX href commands if “latex”.
New in version 1.4.0.
Notes
This method assigns a formatting function, formatter, to each cell in the DataFrame. If formatter is None, then the default formatter is used. If a callable then that function should take a data value as input and return a displayable representation, such as a string. If formatter is given as a string this is assumed to be a valid Python format specification and is wrapped to a callable as string.format(x). If a dict is given, keys should correspond to column names, and values should be string or callable, as above.
The default formatter currently expresses floats and complex numbers with the pandas display precision unless using the precision argument here. The default formatter does not adjust the representation of missing values unless the na_rep argument is used.
The subset argument defines which region to apply the formatting function to. If the formatter argument is given in dict form but does not include all columns within the subset then these columns will have the default formatter applied. Any columns in the formatter dict excluded from the subset will be ignored.
When using a formatter string the dtypes must be compatible, otherwise a ValueError will be raised.
When instantiating a Styler, default formatting can be applied be setting the pandas.options:
styler.format.formatter: default None.
styler.format.na_rep: default None.
styler.format.precision: default 6.
styler.format.decimal: default “.”.
styler.format.thousands: default None.
styler.format.escape: default None.
Examples
Using na_rep and precision with the default formatter
Using a formatter specification on consistent column dtypes
Using the default formatter for unspecified columns
Multiple na_rep or precision specifications under the default formatter.
Using a callable formatter function.
Using a formatter with HTML escape and na_rep.
Using a formatter with LaTeX escape.


Format the text display value of index labels or column headers.
New in version 1.4.0.
Object to define how values are displayed. See notes.
Whether to apply the formatter to the index or column headers.
The level(s) over which to apply the generic formatter.
Representation for missing values. If na_rep is None, no special formatting is applied.
Floating point precision to use for display purposes, if not determined by the specified formatter.
Character used as decimal separator for floats, complex and integers.
Character used as thousands separator for floats, complex and integers.
Use ‘html’ to replace the characters &, <, >, ', and " in cell display string with HTML-safe sequences. Use ‘latex’ to replace the characters &, %, $, #, _, {, }, ~, ^, and \ in the cell display string with LaTeX-safe sequences. Escaping is done before formatter.
Convert string patterns containing https://, http://, ftp:// or www. to HTML <a> tags as clickable URL hyperlinks if “html”, or LaTeX href commands if “latex”.
Notes
This method assigns a formatting function, formatter, to each level label in the DataFrame’s index or column headers. If formatter is None, then the default formatter is used. If a callable then that function should take a label value as input and return a displayable representation, such as a string. If formatter is given as a string this is assumed to be a valid Python format specification and is wrapped to a callable as string.format(x). If a dict is given, keys should correspond to MultiIndex level numbers or names, and values should be string or callable, as above.
The default formatter currently expresses floats and complex numbers with the pandas display precision unless using the precision argument here. The default formatter does not adjust the representation of missing values unless the na_rep argument is used.
The level argument defines which levels of a MultiIndex to apply the method to. If the formatter argument is given in dict form but does not include all levels within the level argument then these unspecified levels will have the default formatter applied. Any levels in the formatter dict specifically excluded from the level argument will be ignored.
When using a formatter string the dtypes must be compatible, otherwise a ValueError will be raised.
Examples
Using na_rep and precision with the default formatter
Using a formatter specification on consistent dtypes in a level
Using the default formatter for unspecified levels
Using a callable formatter function.
Using a formatter with HTML escape and na_rep.
Using a formatter with LaTeX escape.


Factory function for creating a subclass of Styler.
Uses custom templates and Jinja environment.
Changed in version 1.3.0.
Path or paths of directories containing the templates.
Name of your custom template to replace the html_table template.
New in version 1.3.0.
Name of your custom template to replace the html_style template.
New in version 1.3.0.
Has the correct env,``template_html``, template_html_table and template_html_style class attributes set.


Hide the entire index / column headers, or specific rows / columns from display.
New in version 1.4.0.
A valid 1d input or single key along the axis within DataFrame.loc[<subset>, :] or DataFrame.loc[:, <subset>] depending upon axis, to limit data to select hidden rows / columns.
Apply to the index or columns.
The level(s) to hide in a MultiIndex if hiding the entire index / column headers. Cannot be used simultaneously with subset.
Whether to hide the level name(s) of the index / columns headers in the case it (or at least one the levels) remains visible.
Notes
This method has multiple functionality depending upon the combination of the subset, level and names arguments (see examples). The axis argument is used only to control whether the method is applied to row or column headers:
subset
level
names
Effect
None
None
False
The axis-Index is hidden entirely.
None
None
True
Only the axis-Index names are hidden.
None
Int, Str, List
False
Specified axis-MultiIndex levels are hidden entirely.
None
Int, Str, List
True
Specified axis-MultiIndex levels are hidden entirely and the names of remaining axis-MultiIndex levels.
Subset
None
False
The specified data rows/columns are hidden, but the axis-Index itself, and names, remain unchanged.
Subset
None
True
The specified data rows/columns and axis-Index names are hidden, but the axis-Index itself remains unchanged.
Subset
Int, Str, List
Boolean
ValueError: cannot supply subset and level simultaneously.
Note this method only hides the identifed elements so can be chained to hide multiple elements in sequence.
Examples
Simple application hiding specific rows:
Hide the index and retain the data values:
Hide specific rows in a MultiIndex but retain the index:
Hide specific rows and the index through chaining:
Hide a specific level:
Hiding just the index level names:
Examples all produce equivalently transposed effects with axis="columns".


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.
This method should be replaced by hide(axis="columns", **kwargs)
A valid 1d input or single key along the columns axis within DataFrame.loc[:, <subset>], to limit data to before applying the function.
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.
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.
See also
Hide the entire index / columns, or specific rows / columns.


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)
A valid 1d input or single key along the index axis within DataFrame.loc[<subset>, :], to limit data to before applying the function.
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.
Whether to hide the index name(s), in the case the index or part of it remains visible.
New in version 1.4.0.
See also
Hide the entire index / columns, or specific rows / columns.


Highlight a defined range with a style.
New in version 1.3.0.
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.
Background color to use for highlighting.
If left or right given as sequence, axis along which to apply those boundaries. See examples.
Left bound for defining the range.
Right bound for defining the range.
Identify whether bounds are closed or open.
CSS properties to use for highlighting. If props is given, color is not used.
See also
Highlight missing values with a style.
Highlight the maximum with a style.
Highlight the minimum with a style.
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
Using a range input sequnce along an axis, in this case setting a left and right for each column individually
Using axis=None and providing the left argument as an array that matches the input DataFrame, with a constant right
Using props instead of default background coloring


Highlight the maximum with a style.
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.
Background color to use for highlighting.
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.
CSS properties to use for highlighting. If props is given, color is not used.
New in version 1.3.0.
See also
Highlight missing values with a style.
Highlight the minimum with a style.
Highlight a defined range with a style.
Highlight values defined by a quantile with a style.


Highlight the minimum with a style.
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.
Background color to use for highlighting.
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.
CSS properties to use for highlighting. If props is given, color is not used.
New in version 1.3.0.
See also
Highlight missing values with a style.
Highlight the maximum with a style.
Highlight a defined range with a style.
Highlight values defined by a quantile with a style.


Highlight missing values with a style.
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.
CSS properties to use for highlighting. If props is given, color is not used.
New in version 1.3.0.
See also
Highlight the maximum with a style.
Highlight the minimum with a style.
Highlight a defined range with a style.
Highlight values defined by a quantile with a style.


Highlight values defined by a quantile with a style.
New in version 1.3.0.
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.
Background color to use for highlighting.
Axis along which to determine and highlight quantiles. If None quantiles are measured over the entire DataFrame. See examples.
Left bound, in [0, q_right), for the target quantile range.
Right bound, in (q_left, 1], for the target quantile range.
Argument passed to Series.quantile or DataFrame.quantile for quantile estimation.
Identify whether quantile bounds are closed or open.
CSS properties to use for highlighting. If props is given, color is not used.
See also
Highlight missing values with a style.
Highlight the maximum with a style.
Highlight the minimum with a style.
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
Or highlight quantiles row-wise or column-wise, in this case by row-wise
Use props instead of default background coloring


Apply func(self, *args, **kwargs), and return the result.
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.
Arguments passed to func.
A dictionary of keyword arguments passed into func.
The value returned by func.
See also
Analogous method for DataFrame.
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:
users can write:
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
The user-defined format_conversion function above can be called within a sequence of other style modifications:


Render the Styler including all applied styles to HTML.
Deprecated since version 1.4.0.
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.
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.
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.
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


Set the text added to a <caption> HTML element.
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.


Set the missing data representation on a Styler.
New in version 1.0.0.
Deprecated since version 1.3.0.
Notes
This method is deprecated. See Styler.format()


Set the precision used to display values.
Deprecated since version 1.3.0.
Notes
This method is deprecated see Styler.format.


Set defined CSS-properties to each <td> HTML element within the given subset.
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.
A dictionary of property, value pairs to be set for each cell.
Notes
This is a convenience methods which wraps the Styler.applymap() calling a function returning the CSS-properties independently of the data.
Examples
See Table Visualization user guide for more details.


Add CSS to permanently display the index or column headers in a scrolling frame.
Whether to make the index or column headers sticky.
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.
If axis is a MultiIndex the specific levels to stick. If None will stick all levels.
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.


Set the table attributes added to the <table> HTML element.
These are items in addition to automatic (by default) id attribute.
See also
Set the table styles included within the <style> HTML element.
Set the DataFrame of strings added to the class attribute of <td> HTML elements.
Examples


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.
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.
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.
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.
A dict of strings used to replace the default CSS classes described below.
New in version 1.4.0.
See also
Set the DataFrame of strings added to the class attribute of <td> HTML elements.
Set the table attributes added to the <table> HTML element.
Notes
The default CSS classes dict, whose values can be replaced is as follows:
Examples
Or with CSS strings
Adding column styling by name
Adding row styling
See Table Visualization user guide for more details.


Set the DataFrame of strings added to the class attribute of <td> HTML elements.
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.
See also
Set the table styles included within the <style> HTML element.
Set the table attributes added to the <table> HTML element.
Notes
Can be used in combination with Styler.set_table_styles to define an internal CSS solution without reference to external CSS files.
Examples
Using MultiIndex columns and a classes DataFrame as a subset of the underlying,
Form of the output with new additional css classes,


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.
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.
List of (attr, value) tuples or a valid CSS string. If None adopts the internal default values described in notes.
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’.
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
Optionally controlling the tooltip visual display


Set the uuid applied to id attributes of HTML elements.
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.


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.
Matplotlib colormap.
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.
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.
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.
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.
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.
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.
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.
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.
See also
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
Shading the values column-wise, with axis=0, preselecting numeric columns
Shading all values collectively using axis=None
Compress the color map from the both low and high ends
Manually setting vmin and vmax gradient thresholds
Setting a gmap and applying to all columns with another cmap
Setting the gradient map for a dataframe (i.e. axis=None), we need to explicitly state subset to match the gmap shape


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.
File path or existing ExcelWriter.
Name of sheet which will contain DataFrame.
Missing data representation.
Format string for floating point numbers. For example float_format="%.2f" will format 0.1234 to 0.12.
Columns to write.
Write out the column names. If a list of string is given it is assumed to be aliases for the column names.
Write row names (index).
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.
Upper left cell row to dump data frame.
Upper left cell column to dump data frame.
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.
Write MultiIndex and Hierarchical Rows as merged cells.
Encoding of the resulting excel file. Only necessary for xlwt, other writers support unicode natively.
Representation for infinity (there is no native representation for infinity in Excel).
Display more information in the error logs.
Specifies the one-based bottommost row and rightmost column that is to be frozen.
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
Write DataFrame to a comma-separated values (csv) file.
Class for writing DataFrame objects into excel sheets.
Read an Excel file into a pandas DataFrame.
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:
To specify the sheet name:
If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object:
ExcelWriter can also be used to append to an existing Excel file:
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):


Write Styler to a file, buffer or string in HTML-CSS format.
New in version 1.3.0.
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.
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.
Attributes to assign within the <table> HTML element in the format:
<table .. <table_attributes> >
If not given defaults to Styler’s preexisting value.
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.
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.
Adds “font-weight: bold;” as a CSS property to table style header cells.
New in version 1.4.0.
Set, or overwrite, the caption on Styler before rendering.
New in version 1.4.0.
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.
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.
Character encoding setting for file output, and HTML meta tags. Defaults to pandas.options.styler.render.encoding value of “utf-8”.
Whether to output a fully structured HTML file including all HTML elements, or just the core <style> and <table> elements.
Whether to include the <style> element and all associated element class and id identifiers, or solely the <table> element without styling identifiers.
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.
If buf is None, returns the result as a string. Otherwise returns None.
See also
Write a DataFrame to a file, buffer or string in HTML format.


Write Styler to a file, buffer or string in LaTeX format.
New in version 1.3.0.
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.
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.
The LaTeX positional argument (e.g. ‘h!’) for tables, placed in location:
\\begin{table}[<position>].
The LaTeX float command placed in location:
\begin{table}[<position>]
\<position_float>
Cannot be used if environment is “longtable”.
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.
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.
The LaTeX label included as: \label{<label>}. This is used with \ref{<label>} in the main .tex file.
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]>}.
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.
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.
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.
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.
Set to True to structure LaTeX compatible with the {siunitx} package.
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.
Character encoding setting. Defaults to pandas.options.styler.render.encoding, which is “utf-8”.
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.
If buf is None, returns the result as a string. Otherwise returns None.
See also
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)
italic (with siunitx)
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:
The equivalent using LaTeX only commands is the following:
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:
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:
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:
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:
A more comprehensive example using these arguments is as follows:
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:
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
font-style
background-color
cellcolor
color
color
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.
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:
Second we will format the display and, since our table is quite wide, will hide the repeated level-0 of the index:
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:
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.
Finally we render our LaTeX adding in other options as required:


Set the styles on the current Styler.
Possibly uses styles from Styler.export.
“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.
See also
Export the non data dependent attributes to the current Styler.
Examples


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.
cond should take a scalar, and optional keyword arguments, and return a boolean.
Applied when cond returns true.
Applied when cond returns false.
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.
Pass along to cond.
See also
Apply a CSS-styling function elementwise.
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:
should be refactored to:


Create a Table schema from data.
Whether to include data.index in the schema.
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.
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.
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


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


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


Export DataFrame object to Stata dta format.


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).
Object to check for null or missing values.
For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is missing.
See also
Boolean inverse of pandas.isna.
Detect missing values in a Series.
Detect missing values in a DataFrame.
Detect missing values in an Index.
Examples
Scalar arguments (including strings) result in a scalar boolean.
ndarrays result in an ndarray of booleans.
For indexes, an ndarray of booleans is returned.
For Series and DataFrame, the same type is returned, containing booleans.


Normalize semi-structured JSON data into a flat table.
Unserialized JSON objects.
Path in each object to list of records. If not passed, data will be assumed to be an array of records.
Fields to use as metadata for each record in resulting table.
If True, prefix records with dotted (?) path, e.g. foo.bar.field if meta is [‘foo’, ‘bar’].
If True, prefix records with dotted (?) path, e.g. foo.bar.field if path to records is [‘foo’, ‘bar’].
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.
Nested records will generate names separated by sep. e.g., for sep=’.’, {‘foo’: {‘bar’: 0}} -> foo.bar.
Max number of levels(depth of dict) to normalize. if None, normalizes all levels.
New in version 0.25.0.
Examples
Normalizes nested data up to level 1.
Returns normalized data with columns prefixed with the given string.


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’.
Column(s) to use as identifier variables.
Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars.
Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’.
Name to use for the ‘value’ column.
If columns are a MultiIndex then use this level to melt.
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.
Unpivoted DataFrame.
See also
Identical method.
Create a spreadsheet-style pivot table as a DataFrame.
Return reshaped DataFrame organized by given index / column values.
Explode a DataFrame from list-like columns to long format.
Examples
The names of ‘variable’ and ‘value’ columns can be customized:
Original index values can be kept around:
If you have multi-index columns:


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.
Object to merge with.
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.
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.
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.
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.
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.
Use the index from the right DataFrame as the join key. Same caveats as left_index.
Sort the join keys lexicographically in the result DataFrame. If False, the order of the join keys depends on the join type (how keyword).
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.
If False, avoid copy if possible.
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.
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.
A DataFrame of the two merged objects.
See also
Merge with optional filling/interpolation.
Merge on nearest keys.
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
Merge df1 and df2 on the lkey and rkey columns. The value columns have the default suffixes, _x and _y, appended.
Merge DataFrames df1 and df2 with specified left and right suffixes appended to any overlapping columns.
Merge DataFrames df1 and df2, but raise an exception if the DataFrames have any overlapping columns.


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’.
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.
Field name to join on in left DataFrame.
Field name to join on in right DataFrame.
Use the index of the left DataFrame as the join key.
Use the index of the right DataFrame as the join key.
Match on these columns before performing merge operation.
Field names to match on in the left DataFrame.
Field names to match on in the right DataFrame.
Suffix to apply to overlapping column names in the left and right side, respectively.
Select asof tolerance within this range; must be compatible with the merge index.
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).
Whether to search for prior, subsequent, or closest matches.
See also
Merge with a database-style join.
Merge with optional filling/interpolation.
Examples
We can use indexed DataFrames as well.
Here is a real-world times-series example
By default we are taking the asof of the quotes
We only asof within 2ms between the quote time and the trade time
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


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).
Field names to join on. Must be found in both DataFrames.
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.
Field names to join on in right DataFrame or vector/list of vectors per left_on docs.
Group left DataFrame by group columns and merge piece by piece with right DataFrame.
Group right DataFrame by group columns and merge piece by piece with left DataFrame.
Interpolation method for data.
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.
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).
The merged DataFrame output type will the be same as ‘left’, if it is a subclass of DataFrame.
See also
Merge with a database-style join.
Merge on nearest keys.
Examples


A multi-level, or hierarchical, index object for pandas objects.
The unique labels for each level.
Integers for each level designating which label at each location.
Level of sortedness (must be lexicographically sorted by that level).
Names for each of the index levels. (name is accepted for compat).
Copy the meta-data.
Check that the levels/codes are consistent and valid.
See also
Convert list of arrays to MultiIndex.
Create a MultiIndex from the cartesian product of iterables.
Convert list of tuples to a MultiIndex.
Make a MultiIndex from a DataFrame.
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):
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.


Return index with requested level(s) removed.
If resulting index has only 1 level left, the result will be of Index type, not MultiIndex.
If a string is given, must be the name of a level If list-like, elements must be names or indexes of levels.
Examples


Return the dtypes as a Series for the underlying MultiIndex.