pandas.Index.max   Index.max(axis=None, skipna=True, *args, **kwargs)[source]

Return the maximum value of the Index.  Parameters

axis:int, optional

For compatibility with NumPy. Only 0 or None are allowed.
skipna:bool, default True

Exclude NA/null values when showing the result.  *args, **kwargs

Additional arguments and keywords for compatibility with NumPy.    Returns
 scalar

Maximum value.      See also  Index.min

Return the minimum value in an Index.  Series.max

Return the maximum value in a Series.  DataFrame.max

Return the maximum values in a DataFrame.    Examples
>>> idx = pd.Index([3, 2, 1])
>>> idx.max()
3

>>> idx = pd.Index(['c', 'b', 'a'])
>>> idx.max()
'c'
  For a MultiIndex, the maximum is determined lexicographically.
>>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])
>>> idx.max()
('b', 2)


pandas.Index.memory_usage   Index.memory_usage(deep=False)[source]

Memory usage of the values.  Parameters

deep:bool, default False

Introspect the data deeply, interrogate object dtypes for system-level memory consumption.    Returns
 bytes used
    See also  numpy.ndarray.nbytes

Total bytes consumed by the elements of the array.    Notes Memory usage does not include memory consumed by elements that are not components of the array if deep=False or if used on PyPy


pandas.Index.min   Index.min(axis=None, skipna=True, *args, **kwargs)[source]

Return the minimum value of the Index.  Parameters

axis:{None}

Dummy argument for consistency with Series.
skipna:bool, default True

Exclude NA/null values when showing the result.  *args, **kwargs

Additional arguments and keywords for compatibility with NumPy.    Returns
 scalar

Minimum value.      See also  Index.max

Return the maximum value of the object.  Series.min

Return the minimum value in a Series.  DataFrame.min

Return the minimum values in a DataFrame.    Examples
>>> idx = pd.Index([3, 2, 1])
>>> idx.min()
1

>>> idx = pd.Index(['c', 'b', 'a'])
>>> idx.min()
'a'
  For a MultiIndex, the minimum is determined lexicographically.
>>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])
>>> idx.min()
('a', 1)


pandas.Index.name   propertyIndex.name

Return Index or MultiIndex name.


pandas.Index.names   propertyIndex.names


pandas.Index.nbytes   propertyIndex.nbytes

Return the number of bytes in the underlying data.


pandas.Index.ndim   propertyIndex.ndim

Number of dimensions of the underlying data, by definition 1.


pandas.Index.nlevels   propertyIndex.nlevels

Number of levels.


pandas.Index.notna   finalIndex.notna()[source]

Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). NA values, such as None or numpy.NaN, get mapped to False values.  Returns
 numpy.ndarray[bool]

Boolean array to indicate which entries are not NA.      See also  Index.notnull

Alias of notna.  Index.isna

Inverse of notna.  notna

Top-level notna.    Examples Show which entries in an Index are not NA. The result is an array.
>>> idx = pd.Index([5.2, 6.0, np.NaN])
>>> idx
Float64Index([5.2, 6.0, nan], dtype='float64')
>>> idx.notna()
array([ True,  True, False])
  Empty strings are not considered NA values. None is considered a NA value.
>>> idx = pd.Index(['black', '', 'red', None])
>>> idx
Index(['black', '', 'red', None], dtype='object')
>>> idx.notna()
array([ True,  True,  True, False])


pandas.Index.notnull   Index.notnull()[source]

Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). NA values, such as None or numpy.NaN, get mapped to False values.  Returns
 numpy.ndarray[bool]

Boolean array to indicate which entries are not NA.      See also  Index.notnull

Alias of notna.  Index.isna

Inverse of notna.  notna

Top-level notna.    Examples Show which entries in an Index are not NA. The result is an array.
>>> idx = pd.Index([5.2, 6.0, np.NaN])
>>> idx
Float64Index([5.2, 6.0, nan], dtype='float64')
>>> idx.notna()
array([ True,  True, False])
  Empty strings are not considered NA values. None is considered a NA value.
>>> idx = pd.Index(['black', '', 'red', None])
>>> idx
Index(['black', '', 'red', None], dtype='object')
>>> idx.notna()
array([ True,  True,  True, False])


pandas.Index.nunique   Index.nunique(dropna=True)[source]

Return number of unique elements in the object. Excludes NA values by default.  Parameters

dropna:bool, default True

Don’t include NaN in the count.    Returns
 int
    See also  DataFrame.nunique

Method nunique for DataFrame.  Series.count

Count non-NA/null observations in the Series.    Examples
>>> s = pd.Series([1, 3, 5, 7, 7])
>>> s
0    1
1    3
2    5
3    7
4    7
dtype: int64

>>> s.nunique()
4


pandas.Index.putmask   finalIndex.putmask(mask, value)[source]

Return a new Index of the values set with the mask.  Returns
 Index
    See also  numpy.ndarray.putmask

Changes elements of an array based on conditional and input values.


pandas.Index.ravel   finalIndex.ravel(order='C')[source]

Return an ndarray of the flattened values of the underlying data.  Returns
 numpy.ndarray

Flattened array.      See also  numpy.ndarray.ravel

Return a flattened array.


pandas.Index.reindex   Index.reindex(target, method=None, level=None, limit=None, tolerance=None)[source]

Create index with target’s values.  Parameters

target:an iterable

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

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

Level of multiindex.
limit:int, optional

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

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

new_index:pd.Index

Resulting index.
indexer:np.ndarray[np.intp] or None

Indices of output values in original index.    Raises
 TypeError

If method passed along with level.  ValueError

If non-unique multi-index  ValueError

If non-unique index and method or limit passed.      See also  Series.reindex
DataFrame.reindex
  Examples
>>> idx = pd.Index(['car', 'bike', 'train', 'tractor'])
>>> idx
Index(['car', 'bike', 'train', 'tractor'], dtype='object')
>>> idx.reindex(['car', 'bike'])
(Index(['car', 'bike'], dtype='object'), array([0, 1]))


pandas.Index.rename   Index.rename(name, inplace=False)[source]

Alter Index or MultiIndex name. Able to set new names without level. Defaults to returning new index. Length of names must match number of levels in MultiIndex.  Parameters

name:label or list of labels

Name(s) to set.
inplace:bool, default False

Modifies the object directly, instead of creating a new Index or MultiIndex.    Returns
 Index or None

The same type as the caller or None if inplace=True.      See also  Index.set_names

Able to set new names partially and by level.    Examples
>>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score')
>>> idx.rename('grade')
Index(['A', 'C', 'A', 'B'], dtype='object', name='grade')

>>> idx = pd.MultiIndex.from_product([['python', 'cobra'],
...                                   [2018, 2019]],
...                                   names=['kind', 'year'])
>>> idx
MultiIndex([('python', 2018),
            ('python', 2019),
            ( 'cobra', 2018),
            ( 'cobra', 2019)],
           names=['kind', 'year'])
>>> idx.rename(['species', 'year'])
MultiIndex([('python', 2018),
            ('python', 2019),
            ( 'cobra', 2018),
            ( 'cobra', 2019)],
           names=['species', 'year'])
>>> idx.rename('species')
Traceback (most recent call last):
TypeError: Must pass list-like as `names`.


pandas.Index.repeat   Index.repeat(repeats, axis=None)[source]

Repeat elements of a Index. Returns a new Index where each element of the current Index is repeated consecutively a given number of times.  Parameters

repeats:int or array of ints

The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty Index.
axis:None

Must be None. Has no effect but is accepted for compatibility with numpy.    Returns

repeated_index:Index

Newly created Index with repeated elements.      See also  Series.repeat

Equivalent function for Series.  numpy.repeat

Similar method for numpy.ndarray.    Examples
>>> idx = pd.Index(['a', 'b', 'c'])
>>> idx
Index(['a', 'b', 'c'], dtype='object')
>>> idx.repeat(2)
Index(['a', 'a', 'b', 'b', 'c', 'c'], dtype='object')
>>> idx.repeat([1, 2, 3])
Index(['a', 'b', 'b', 'c', 'c', 'c'], dtype='object')


pandas.Index.searchsorted   Index.searchsorted(value, side='left', sorter=None)[source]

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.   Parameters

value:array-like or scalar

Values to insert into self.
side:{‘left’, ‘right’}, optional

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).
sorter:1-D array-like, optional

Optional array of integer indices that sort self into ascending order. They are typically the result of np.argsort.    Returns
 int or array of int

A scalar or array of insertion points with the same shape as value.      See also  sort_values

Sort by the values along either axis.  numpy.searchsorted

Similar method from NumPy.    Notes Binary search is used to find the required insertion points. Examples
>>> ser = pd.Series([1, 2, 3])
>>> ser
0    1
1    2
2    3
dtype: int64

>>> ser.searchsorted(4)
3

>>> ser.searchsorted([0, 4])
array([0, 3])

>>> ser.searchsorted([1, 3], side='left')
array([0, 2])

>>> ser.searchsorted([1, 3], side='right')
array([1, 3])

>>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000']))
>>> ser
0   2000-03-11
1   2000-03-12
2   2000-03-13
dtype: datetime64[ns]

>>> ser.searchsorted('3/14/2000')
3

>>> ser = pd.Categorical(
...     ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True
... )
>>> ser
['apple', 'bread', 'bread', 'cheese', 'milk']
Categories (4, object): ['apple' < 'bread' < 'cheese' < 'milk']

>>> ser.searchsorted('bread')
1

>>> ser.searchsorted(['bread'], side='right')
array([3])
  If the values are not monotonically sorted, wrong locations may be returned:
>>> ser = pd.Series([2, 1, 3])
>>> ser
0    2
1    1
2    3
dtype: int64

>>> ser.searchsorted(1)
0  # wrong result, correct would be 1


pandas.Index.set_names   Index.set_names(names, level=None, inplace=False)[source]

Set Index or MultiIndex name. Able to set new names partially and by level.  Parameters

names:label or list of label or dict-like for MultiIndex

Name(s) to set.  Changed in version 1.3.0.
level:int, label or list of int or label, optional

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.
inplace:bool, default False

Modifies the object directly, instead of creating a new Index or MultiIndex.    Returns
 Index or None

The same type as the caller or None if inplace=True.      See also  Index.rename

Able to set new names without level.    Examples
>>> idx = pd.Index([1, 2, 3, 4])
>>> idx
Int64Index([1, 2, 3, 4], dtype='int64')
>>> idx.set_names('quarter')
Int64Index([1, 2, 3, 4], dtype='int64', name='quarter')

>>> idx = pd.MultiIndex.from_product([['python', 'cobra'],
...                                   [2018, 2019]])
>>> idx
MultiIndex([('python', 2018),
            ('python', 2019),
            ( 'cobra', 2018),
            ( 'cobra', 2019)],
           )
>>> idx.set_names(['kind', 'year'], inplace=True)
>>> idx
MultiIndex([('python', 2018),
            ('python', 2019),
            ( 'cobra', 2018),
            ( 'cobra', 2019)],
           names=['kind', 'year'])
>>> idx.set_names('species', level=0)
MultiIndex([('python', 2018),
            ('python', 2019),
            ( 'cobra', 2018),
            ( 'cobra', 2019)],
           names=['species', 'year'])
  When renaming levels with a dict, levels can not be passed.
>>> idx.set_names({'kind': 'snake'})
MultiIndex([('python', 2018),
            ('python', 2019),
            ( 'cobra', 2018),
            ( 'cobra', 2019)],
           names=['snake', 'year'])


pandas.Index.set_value   finalIndex.set_value(arr, key, value)[source]

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


pandas.Index.shape   propertyIndex.shape

Return a tuple of the shape of the underlying data.


pandas.Index.shift   Index.shift(periods=1, freq=None)[source]

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.  Parameters

periods:int, default 1

Number of periods (or increments) to shift by, can be positive or negative.
freq:pandas.DateOffset, pandas.Timedelta or str, optional

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.    Returns
 pandas.Index

Shifted index.      See also  Series.shift

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.
>>> month_starts = pd.date_range('1/1/2011', periods=5, freq='MS')
>>> month_starts
DatetimeIndex(['2011-01-01', '2011-02-01', '2011-03-01', '2011-04-01',
               '2011-05-01'],
              dtype='datetime64[ns]', freq='MS')
  Shift the index by 10 days.
>>> month_starts.shift(10, freq='D')
DatetimeIndex(['2011-01-11', '2011-02-11', '2011-03-11', '2011-04-11',
               '2011-05-11'],
              dtype='datetime64[ns]', freq=None)
  The default value of freq is the freq attribute of the index, which is ‘MS’ (month start) in this example.
>>> month_starts.shift(10)
DatetimeIndex(['2011-11-01', '2011-12-01', '2012-01-01', '2012-02-01',
               '2012-03-01'],
              dtype='datetime64[ns]', freq='MS')


pandas.Index.size   propertyIndex.size

Return the number of elements in the underlying data.


pandas.Index.slice_indexer   Index.slice_indexer(start=None, end=None, step=None, kind=NoDefault.no_default)[source]

Compute the slice indexer for input labels and step. Index needs to be ordered and unique.  Parameters

start:label, default None

If None, defaults to the beginning.
end:label, default None

If None, defaults to the end.
step:int, default None

kind:str, default None

 Deprecated since version 1.4.0.     Returns

indexer:slice

  Raises

KeyError:If key does not exist, or key is not unique and index is

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:
>>> idx = pd.Index(list('abcd'))
>>> idx.slice_indexer(start='b', end='c')
slice(1, 3, None)

>>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')])
>>> idx.slice_indexer(start='b', end=('c', 'g'))
slice(1, 3, None)


pandas.Index.slice_locs   Index.slice_locs(start=None, end=None, step=None, kind=NoDefault.no_default)[source]

Compute slice locations for input labels.  Parameters

start:label, default None

If None, defaults to the beginning.
end:label, default None

If None, defaults to the end.
step:int, defaults None

If None, defaults to 1.
kind:{‘loc’, ‘getitem’} or None

 Deprecated since version 1.4.0.     Returns

start, end:int

    See also  Index.get_loc

Get location for a single label.    Notes This method only works if the index is monotonic or unique. Examples
>>> idx = pd.Index(list('abcd'))
>>> idx.slice_locs(start='b', end='c')
(1, 3)


pandas.Index.sort   finalIndex.sort(*args, **kwargs)[source]

Use sort_values instead.


pandas.Index.sort_values   Index.sort_values(return_indexer=False, ascending=True, na_position='last', key=None)[source]

Return a sorted copy of the index. Return a sorted copy of the index, and optionally return the indices that sorted the index itself.  Parameters

return_indexer:bool, default False

Should the indices that would sort the index be returned.
ascending:bool, default True

Should the index values be sorted in an ascending order.
na_position:{‘first’ or ‘last’}, default ‘last’

Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.  New in version 1.2.0.
key:callable, optional

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.     Returns

sorted_index:pandas.Index

Sorted copy of the index.
indexer:numpy.ndarray, optional

The indices that the index itself was sorted by.      See also  Series.sort_values

Sort values of a Series.  DataFrame.sort_values

Sort values in a DataFrame.    Examples
>>> idx = pd.Index([10, 100, 1, 1000])
>>> idx
Int64Index([10, 100, 1, 1000], dtype='int64')
  Sort values in ascending order (default behavior).
>>> idx.sort_values()
Int64Index([1, 10, 100, 1000], dtype='int64')
  Sort values in descending order, and also get the indices idx was sorted by.
>>> idx.sort_values(ascending=False, return_indexer=True)
(Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))


pandas.Index.sortlevel   Index.sortlevel(level=None, ascending=True, sort_remaining=None)[source]

For internal compatibility with the Index API. Sort the Index. This is for compat with MultiIndex  Parameters

ascending:bool, default True

False to sort in descending order  level, sort_remaining are compat parameters
  Returns
 Index


pandas.Index.str   Index.str()[source]

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
>>> s = pd.Series(["A_Str_Series"])
>>> s
0    A_Str_Series
dtype: object

>>> s.str.split("_")
0    [A, Str, Series]
dtype: object

>>> s.str.replace("_", "")
0    AStrSeries
dtype: object


pandas.Index.symmetric_difference   Index.symmetric_difference(other, result_name=None, sort=None)[source]

Compute the symmetric difference of two Index objects.  Parameters

other:Index or array-like

result_name:str

sort:False or None, default None

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.     Returns

symmetric_difference:Index

   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
>>> idx1 = pd.Index([1, 2, 3, 4])
>>> idx2 = pd.Index([2, 3, 4, 5])
>>> idx1.symmetric_difference(idx2)
Int64Index([1, 5], dtype='int64')


pandas.Index.T   propertyIndex.T

Return the transpose, which is by definition self.


pandas.Index.take   Index.take(indices, axis=0, allow_fill=True, fill_value=None, **kwargs)[source]

Return a new Index of the values selected by the indices. For internal compatibility with numpy arrays.  Parameters

indices:array-like

Indices to be taken.
axis:int, optional

The axis over which to select values, always 0.
allow_fill:bool, default True

fill_value:scalar, default None

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.    Returns
 Index

An index formed of elements at the given indices. Will be the same type as self, except for RangeIndex.      See also  numpy.ndarray.take

Return an array formed from the elements of a at the given indices.


pandas.Index.to_flat_index   Index.to_flat_index()[source]

Identity method. This is implemented for compatibility with subclass implementations when chaining.  Returns
 pd.Index

Caller.      See also  MultiIndex.to_flat_index

Subclass implementation.


pandas.Index.to_frame   Index.to_frame(index=True, name=NoDefault.no_default)[source]

Create a DataFrame with a column containing the Index.  Parameters

index:bool, default True

Set the index of the returned DataFrame as the original Index.
name:object, default None

The passed name should substitute for the index name (if it has one).    Returns
 DataFrame

DataFrame containing the original Index data.      See also  Index.to_series

Convert an Index to a Series.  Series.to_frame

Convert Series to DataFrame.    Examples
>>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')
>>> idx.to_frame()
       animal
animal
Ant       Ant
Bear     Bear
Cow       Cow
  By default, the original Index is reused. To enforce a new Index:
>>> idx.to_frame(index=False)
    animal
0   Ant
1  Bear
2   Cow
  To override the name of the resulting column, specify name:
>>> idx.to_frame(index=False, name='zoo')
    zoo
0   Ant
1  Bear
2   Cow


pandas.Index.to_list   Index.to_list()[source]

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)  Returns
 list
    See also  numpy.ndarray.tolist

Return the array as an a.ndim-levels deep nested list of Python scalars.


pandas.Index.to_native_types   finalIndex.to_native_types(slicer=None, **kwargs)[source]

Format specified values of self and return them.  Deprecated since version 1.2.0.   Parameters

slicer:int, array-like

An indexer into self that specifies which values are used in the formatting process.
kwargs:dict

Options for specifying how the values should be formatted. These options include the following:
 na_rep:str

The value that serves as a placeholder for NULL values
 quoting:bool or None

Whether or not there are quoted values in self
 date_format:str

The format used to represent date-like values.        Returns
 numpy.ndarray

Formatted values.


pandas.Index.to_numpy   Index.to_numpy(dtype=None, copy=False, na_value=NoDefault.no_default, **kwargs)[source]

A NumPy ndarray representing the values in this Series or Index.  Parameters

dtype:str or numpy.dtype, optional

The dtype to pass to numpy.asarray().
copy:bool, default False

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.
na_value:Any, optional

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.   **kwargs

Additional keywords passed through to the to_numpy method of the underlying array (for extension arrays).  New in version 1.0.0.     Returns
 numpy.ndarray
    See also  Series.array

Get the actual data stored within.  Index.array

Get the actual data stored within.  DataFrame.to_numpy

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
>>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))
>>> ser.to_numpy()
array(['a', 'b', 'a'], dtype=object)
  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.
>>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
>>> ser.to_numpy(dtype=object)
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
       Timestamp('2000-01-02 00:00:00+0100', tz='CET')],
      dtype=object)
  Or dtype='datetime64[ns]' to return an ndarray of native datetime64 values. The values are converted to UTC and the timezone info is dropped.
>>> ser.to_numpy(dtype="datetime64[ns]")
...
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'],
      dtype='datetime64[ns]')


pandas.Index.to_series   Index.to_series(index=None, name=None)[source]

Create a Series with both index and values equal to the index keys. Useful with map for returning an indexer based on an index.  Parameters

index:Index, optional

Index of resulting Series. If None, defaults to original index.
name:str, optional

Name of resulting Series. If None, defaults to name of original index.    Returns
 Series

The dtype will be based on the type of the Index values.      See also  Index.to_frame

Convert an Index to a DataFrame.  Series.to_frame

Convert Series to DataFrame.    Examples
>>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')
  By default, the original Index and original name is reused.
>>> idx.to_series()
animal
Ant      Ant
Bear    Bear
Cow      Cow
Name: animal, dtype: object
  To enforce a new Index, specify new labels to index:
>>> idx.to_series(index=[0, 1, 2])
0     Ant
1    Bear
2     Cow
Name: animal, dtype: object
  To override the name of the resulting column, specify name:
>>> idx.to_series(name='zoo')
animal
Ant      Ant
Bear    Bear
Cow      Cow
Name: zoo, dtype: object


pandas.Index.tolist   Index.tolist()[source]

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)  Returns
 list
    See also  numpy.ndarray.tolist

Return the array as an a.ndim-levels deep nested list of Python scalars.


pandas.Index.transpose   Index.transpose(*args, **kwargs)[source]

Return the transpose, which is by definition self.  Returns
 %(klass)s


pandas.Index.union   finalIndex.union(other, sort=None)[source]

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.
  Parameters

other:Index or array-like

sort:bool or None, default None

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.     Returns

union:Index

   Examples Union matching dtypes
>>> idx1 = pd.Index([1, 2, 3, 4])
>>> idx2 = pd.Index([3, 4, 5, 6])
>>> idx1.union(idx2)
Int64Index([1, 2, 3, 4, 5, 6], dtype='int64')
  Union mismatched dtypes
>>> idx1 = pd.Index(['a', 'b', 'c', 'd'])
>>> idx2 = pd.Index([1, 2, 3, 4])
>>> idx1.union(idx2)
Index(['a', 'b', 'c', 'd', 1, 2, 3, 4], dtype='object')
  MultiIndex case
>>> idx1 = pd.MultiIndex.from_arrays(
...     [[1, 1, 2, 2], ["Red", "Blue", "Red", "Blue"]]
... )
>>> idx1
MultiIndex([(1,  'Red'),
    (1, 'Blue'),
    (2,  'Red'),
    (2, 'Blue')],
   )
>>> idx2 = pd.MultiIndex.from_arrays(
...     [[3, 3, 2, 2], ["Red", "Green", "Red", "Green"]]
... )
>>> idx2
MultiIndex([(3,   'Red'),
    (3, 'Green'),
    (2,   'Red'),
    (2, 'Green')],
   )
>>> idx1.union(idx2)
MultiIndex([(1,  'Blue'),
    (1,   'Red'),
    (2,  'Blue'),
    (2, 'Green'),
    (2,   'Red'),
    (3, 'Green'),
    (3,   'Red')],
   )
>>> idx1.union(idx2, sort=False)
MultiIndex([(1,   'Red'),
    (1,  'Blue'),
    (2,   'Red'),
    (2,  'Blue'),
    (3,   'Red'),
    (3, 'Green'),
    (2, 'Green')],
   )


pandas.Index.unique   Index.unique(level=None)[source]

Return unique values in the index. Unique values are returned in order of appearance, this does NOT sort.  Parameters

level:int or hashable, optional

Only return values from specified level (for MultiIndex). If int, gets the level by integer position, else by level name.    Returns
 Index
    See also  unique

Numpy array of unique values in that column.  Series.unique

Return unique values of Series object.


pandas.Index.value_counts   Index.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)[source]

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.  Parameters

normalize:bool, default False

If True then the object returned will contain the relative frequencies of the unique values.
sort:bool, default True

Sort by frequencies.
ascending:bool, default False

Sort in ascending order.
bins:int, optional

Rather than count values, group them into half-open bins, a convenience for pd.cut, only works with numeric data.
dropna:bool, default True

Don’t include counts of NaN.    Returns
 Series
    See also  Series.count

Number of non-NA elements in a Series.  DataFrame.count

Number of non-NA elements in a DataFrame.  DataFrame.value_counts

Equivalent method on DataFrames.    Examples
>>> index = pd.Index([3, 1, 2, 3, 4, np.nan])
>>> index.value_counts()
3.0    2
1.0    1
2.0    1
4.0    1
dtype: int64
  With normalize set to True, returns the relative frequency by dividing all values by the sum of values.
>>> s = pd.Series([3, 1, 2, 3, 4, np.nan])
>>> s.value_counts(normalize=True)
3.0    0.4
1.0    0.2
2.0    0.2
4.0    0.2
dtype: float64
  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.
>>> s.value_counts(bins=3)
(0.996, 2.0]    2
(2.0, 3.0]      2
(3.0, 4.0]      1
dtype: int64
  dropna With dropna set to False we can also see NaN index values.
>>> s.value_counts(dropna=False)
3.0    2
1.0    1
2.0    1
4.0    1
NaN    1
dtype: int64


pandas.Index.values   propertyIndex.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.   Returns
 array: numpy.ndarray or ExtensionArray
    See also  Index.array

Reference to the underlying data.  Index.to_numpy

A NumPy array representing the underlying data.


pandas.Index.view   Index.view(cls=None)[source]


pandas.Index.where   finalIndex.where(cond, other=None)[source]

Replace values where the condition is False. The replacement is taken from other.  Parameters

cond:bool array-like with the same length as self

Condition to select the values on.
other:scalar, or array-like, default None

Replacement if the condition is False.    Returns
 pandas.Index

A copy of self with values replaced from other where the condition is False.      See also  Series.where

Same method for Series.  DataFrame.where

Same method for DataFrame.    Examples
>>> idx = pd.Index(['car', 'bike', 'train', 'tractor'])
>>> idx
Index(['car', 'bike', 'train', 'tractor'], dtype='object')
>>> idx.where(idx.isin(['car', 'train']), 'other')
Index(['car', 'other', 'train', 'other'], dtype='object')


pandas.IndexSlice   pandas.IndexSlice=<pandas.core.indexing._IndexSlice object>

Create an object to more easily perform multi-index slicing.  See also  MultiIndex.remove_unused_levels

New MultiIndex with no unused levels.    Notes See Defined Levels for further info on slicing a MultiIndex. Examples
>>> midx = pd.MultiIndex.from_product([['A0','A1'], ['B0','B1','B2','B3']])
>>> columns = ['foo', 'bar']
>>> dfmi = pd.DataFrame(np.arange(16).reshape((len(midx), len(columns))),
...                     index=midx, columns=columns)
  Using the default slice command:
>>> dfmi.loc[(slice(None), slice('B0', 'B1')), :]
           foo  bar
    A0 B0    0    1
       B1    2    3
    A1 B0    8    9
       B1   10   11
  Using the IndexSlice class for a more intuitive command:
>>> idx = pd.IndexSlice
>>> dfmi.loc[idx[:, 'B0':'B1'], :]
           foo  bar
    A0 B0    0    1
       B1    2    3
    A1 B0    8    9
       B1   10   11


pandas.infer_freq   pandas.infer_freq(index, warn=True)[source]

Infer the most likely frequency given the input index. If the frequency is uncertain, a warning will be printed.  Parameters

index:DatetimeIndex or TimedeltaIndex

If passed a Series will use the values of the series (NOT THE INDEX).
warn:bool, default True

  Returns
 str or None

None if no discernible frequency.    Raises
 TypeError

If the index is not datetime-like.  ValueError

If there are fewer than three values.     Examples
>>> idx = pd.date_range(start='2020/12/01', end='2020/12/30', periods=30)
>>> pd.infer_freq(idx)
'D'


pandas.Int16Dtype   classpandas.Int16Dtype[source]

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


pandas.Int32Dtype   classpandas.Int32Dtype[source]

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


pandas.Int64Dtype   classpandas.Int64Dtype[source]

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


pandas.Int64Index   classpandas.Int64Index(data=None, dtype=None, copy=False, name=None)[source]

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.   Parameters

data:array-like (1-dimensional)

dtype:NumPy dtype (default: int64)

copy:bool

Make a copy of input ndarray.
name:object

Name to be stored in the index.      See also  Index

The base pandas Index type.  NumericIndex

Index of numpy int/uint/float data.    Notes An Index instance can only contain hashable objects. Attributes
None     Methods
None


pandas.Int8Dtype   classpandas.Int8Dtype[source]

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


pandas.Interval   classpandas.Interval

Immutable object implementing an Interval, a bounded slice-like interval.  Parameters

left:orderable scalar

Left bound for the interval.
right:orderable scalar

Right bound for the interval.
closed:{‘right’, ‘left’, ‘both’, ‘neither’}, default ‘right’

Whether the interval is closed on the left-side, right-side, both or neither. See the Notes for more detailed explanation.      See also  IntervalIndex

An Index of Interval objects that are all closed on the same side.  cut

Convert continuous data into discrete bins (Categorical of Interval objects).  qcut

Convert continuous data into bins (Categorical of Interval objects) based on quantiles.  Period

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:
>>> iv = pd.Interval(left=0, right=5)
>>> iv
Interval(0, 5, closed='right')
  You can check if an element belongs to it
>>> 2.5 in iv
True
  You can test the bounds (closed='right', so 0 < x <= 5):
>>> 0 in iv
False
>>> 5 in iv
True
>>> 0.0001 in iv
True
  Calculate its length
>>> iv.length
5
  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
>>> shifted_iv = iv + 3
>>> shifted_iv
Interval(3, 8, closed='right')
>>> extended_iv = iv * 10.0
>>> extended_iv
Interval(0.0, 50.0, closed='right')
  To create a time interval you can use Timestamps as the bounds
>>> year_2017 = pd.Interval(pd.Timestamp('2017-01-01 00:00:00'),
...                         pd.Timestamp('2018-01-01 00:00:00'),
...                         closed='left')
>>> pd.Timestamp('2017-01-01 00:00') in year_2017
True
>>> year_2017.length
Timedelta('365 days 00:00:00')
  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.


pandas.Interval.closed   Interval.closed

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


pandas.Interval.closed_left   Interval.closed_left

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

True if the Interval is closed on the left-side.


pandas.Interval.closed_right   Interval.closed_right

Check if the interval is closed on the right side. For the meaning of closed and open see Interval.  Returns
 bool

True if the Interval is closed on the left-side.


pandas.Interval.is_empty   Interval.is_empty

Indicates if an interval is empty, meaning it contains no points.  New in version 0.25.0.   Returns
 bool or ndarray

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:
>>> pd.Interval(0, 1, closed='right').is_empty
False
  An Interval that does not contain any points is empty:
>>> pd.Interval(0, 0, closed='right').is_empty
True
>>> pd.Interval(0, 0, closed='left').is_empty
True
>>> pd.Interval(0, 0, closed='neither').is_empty
True
  An Interval that contains a single point is not empty:
>>> pd.Interval(0, 0, closed='both').is_empty
False
  An IntervalArray or IntervalIndex returns a boolean ndarray positionally indicating if an Interval is empty:
>>> ivs = [pd.Interval(0, 0, closed='neither'),
...        pd.Interval(1, 2, closed='neither')]
>>> pd.arrays.IntervalArray(ivs).is_empty
array([ True, False])
  Missing values are not considered empty:
>>> ivs = [pd.Interval(0, 0, closed='neither'), np.nan]
>>> pd.IntervalIndex(ivs).is_empty
array([ True, False])


pandas.Interval.left   Interval.left

Left bound for the interval.


pandas.Interval.length   Interval.length

Return the length of the Interval.


pandas.Interval.mid   Interval.mid

Return the midpoint of the Interval.


pandas.Interval.open_left   Interval.open_left

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

True if the Interval is closed on the left-side.


pandas.Interval.open_right   Interval.open_right

Check if the interval is open on the right side. For the meaning of closed and open see Interval.  Returns
 bool

True if the Interval is closed on the left-side.


pandas.Interval.overlaps   Interval.overlaps()

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.  Parameters

other:Interval

Interval to check against for an overlap.    Returns
 bool

True if the two intervals overlap.      See also  IntervalArray.overlaps

The corresponding method for IntervalArray.  IntervalIndex.overlaps

The corresponding method for IntervalIndex.    Examples
>>> i1 = pd.Interval(0, 2)
>>> i2 = pd.Interval(1, 3)
>>> i1.overlaps(i2)
True
>>> i3 = pd.Interval(4, 5)
>>> i1.overlaps(i3)
False
  Intervals that share closed endpoints overlap:
>>> i4 = pd.Interval(0, 1, closed='both')
>>> i5 = pd.Interval(1, 2, closed='both')
>>> i4.overlaps(i5)
True
  Intervals that only have an open endpoint in common do not overlap:
>>> i6 = pd.Interval(1, 2, closed='neither')
>>> i4.overlaps(i6)
False


pandas.Interval.right   Interval.right

Right bound for the interval.


pandas.interval_range   pandas.interval_range(start=None, end=None, periods=None, freq=None, name=None, closed='right')[source]

Return a fixed frequency IntervalIndex.  Parameters

start:numeric or datetime-like, default None

Left bound for generating intervals.
end:numeric or datetime-like, default None

Right bound for generating intervals.
periods:int, default None

Number of periods to generate.
freq:numeric, str, or DateOffset, default None

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:str, default None

Name of the resulting IntervalIndex.
closed:{‘left’, ‘right’, ‘both’, ‘neither’}, default ‘right’

Whether the intervals are closed on the left-side, right-side, both or neither.    Returns
 IntervalIndex
    See also  IntervalIndex

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.
>>> pd.interval_range(start=0, end=5)
IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],
              dtype='interval[int64, right]')
  Additionally, datetime-like input is also supported.
>>> pd.interval_range(start=pd.Timestamp('2017-01-01'),
...                   end=pd.Timestamp('2017-01-04'))
IntervalIndex([(2017-01-01, 2017-01-02], (2017-01-02, 2017-01-03],
               (2017-01-03, 2017-01-04]],
              dtype='interval[datetime64[ns], right]')
  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.
>>> pd.interval_range(start=0, periods=4, freq=1.5)
IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]],
              dtype='interval[float64, right]')
  Similarly, for datetime-like start and end, the frequency must be convertible to a DateOffset.
>>> pd.interval_range(start=pd.Timestamp('2017-01-01'),
...                   periods=3, freq='MS')
IntervalIndex([(2017-01-01, 2017-02-01], (2017-02-01, 2017-03-01],
               (2017-03-01, 2017-04-01]],
              dtype='interval[datetime64[ns], right]')
  Specify start, end, and periods; the frequency is generated automatically (linearly spaced).
>>> pd.interval_range(start=0, end=6, periods=4)
IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]],
          dtype='interval[float64, right]')
  The closed parameter specifies which endpoints of the individual intervals within the IntervalIndex are closed.
>>> pd.interval_range(end=5, periods=4, closed='both')
IntervalIndex([[1, 2], [2, 3], [3, 4], [4, 5]],
              dtype='interval[int64, both]')


pandas.IntervalDtype   classpandas.IntervalDtype(subtype=None, closed=None)[source]

An ExtensionDtype for Interval data. This is not an actual numpy dtype, but a duck type.  Parameters

subtype:str, np.dtype

The dtype of the Interval bounds.     Examples
>>> pd.IntervalDtype(subtype='int64', closed='both')
interval[int64, both]
  Attributes
subtype The dtype of the Interval bounds.    Methods
None


pandas.IntervalDtype.subtype   propertyIntervalDtype.subtype

The dtype of the Interval bounds.


pandas.IntervalIndex   classpandas.IntervalIndex(data, closed=None, dtype=None, copy=False, name=None, verify_integrity=True)[source]

Immutable index of intervals that are closed on the same side.  New in version 0.20.0.   Parameters

data:array-like (1-dimensional)

Array-like containing Interval objects from which to build the IntervalIndex.
closed:{‘left’, ‘right’, ‘both’, ‘neither’}, default ‘right’

Whether the intervals are closed on the left-side, right-side, both or neither.
dtype:dtype or None, default None

If None, dtype will be inferred.
copy:bool, default False

Copy the input data.
name:object, optional

Name to be stored in the index.
verify_integrity:bool, default True

Verify that the IntervalIndex is valid.      See also  Index

The base pandas Index type.  Interval

A bounded slice-like interval; the elements of an IntervalIndex.  interval_range

Function to create a fixed frequency IntervalIndex.  cut

Bin values into discrete Intervals.  qcut

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():
>>> pd.interval_range(start=0, end=5)
IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],
              dtype='interval[int64, right]')
  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).


pandas.IntervalIndex.closed   IntervalIndex.closed

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


pandas.IntervalIndex.contains   IntervalIndex.contains(*args, **kwargs)[source]

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.   Parameters

other:scalar

The value to check whether it is contained in the Intervals.    Returns
 boolean array
    See also  Interval.contains

Check whether Interval object contains value.  IntervalArray.overlaps

Check if an Interval overlaps the values in the IntervalArray.    Examples
>>> intervals = pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 3), (2, 4)])
>>> intervals
<IntervalArray>
[(0, 1], (1, 3], (2, 4]]
Length: 3, dtype: interval[int64, right]

>>> intervals.contains(0.5)
array([ True, False, False])


pandas.IntervalIndex.from_arrays   classmethodIntervalIndex.from_arrays(left, right, closed='right', name=None, copy=False, dtype=None)[source]

Construct from two arrays defining the left and right bounds.  Parameters

left:array-like (1-dimensional)

Left bounds for each interval.
right:array-like (1-dimensional)

Right bounds for each interval.
closed:{‘left’, ‘right’, ‘both’, ‘neither’}, default ‘right’

Whether the intervals are closed on the left-side, right-side, both or neither.
copy:bool, default False

Copy the data.
dtype:dtype, optional

If None, dtype will be inferred.    Returns
 IntervalIndex
  Raises
 ValueError

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  interval_range

Function to create a fixed frequency IntervalIndex.  IntervalIndex.from_breaks

Construct an IntervalIndex from an array of splits.  IntervalIndex.from_tuples

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
>>> pd.IntervalIndex.from_arrays([0, 1, 2], [1, 2, 3])
IntervalIndex([(0, 1], (1, 2], (2, 3]],
              dtype='interval[int64, right]')


pandas.IntervalIndex.from_breaks   classmethodIntervalIndex.from_breaks(breaks, closed='right', name=None, copy=False, dtype=None)[source]

Construct an IntervalIndex from an array of splits.  Parameters

breaks:array-like (1-dimensional)

Left and right bounds for each interval.
closed:{‘left’, ‘right’, ‘both’, ‘neither’}, default ‘right’

Whether the intervals are closed on the left-side, right-side, both or neither.
copy:bool, default False

Copy the data.
dtype:dtype or None, default None

If None, dtype will be inferred.    Returns
 IntervalIndex
    See also  interval_range

Function to create a fixed frequency IntervalIndex.  IntervalIndex.from_arrays

Construct from a left and right array.  IntervalIndex.from_tuples

Construct from a sequence of tuples.    Examples
>>> pd.IntervalIndex.from_breaks([0, 1, 2, 3])
IntervalIndex([(0, 1], (1, 2], (2, 3]],
              dtype='interval[int64, right]')


pandas.IntervalIndex.from_tuples   classmethodIntervalIndex.from_tuples(data, closed='right', name=None, copy=False, dtype=None)[source]

Construct an IntervalIndex from an array-like of tuples.  Parameters

data:array-like (1-dimensional)

Array of tuples.
closed:{‘left’, ‘right’, ‘both’, ‘neither’}, default ‘right’

Whether the intervals are closed on the left-side, right-side, both or neither.
copy:bool, default False

By-default copy the data, this is compat only and ignored.
dtype:dtype or None, default None

If None, dtype will be inferred.    Returns
 IntervalIndex
    See also  interval_range

Function to create a fixed frequency IntervalIndex.  IntervalIndex.from_arrays

Construct an IntervalIndex from a left and right array.  IntervalIndex.from_breaks

Construct an IntervalIndex from an array of splits.    Examples
>>> pd.IntervalIndex.from_tuples([(0, 1), (1, 2)])
IntervalIndex([(0, 1], (1, 2]],
               dtype='interval[int64, right]')


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

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

target:Index

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

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

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

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

indexer:np.ndarray[np.intp]

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


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

Get integer location, slice or boolean mask for requested label.  Parameters

key:label

method:{None}, optional

 default: matches where the label is within an interval only.     Returns
 int if unique index, slice if monotonic index, else mask
   Examples
>>> i1, i2 = pd.Interval(0, 1), pd.Interval(1, 2)
>>> index = pd.IntervalIndex([i1, i2])
>>> index.get_loc(1)
0
  You can also supply a point inside an interval.
>>> index.get_loc(1.5)
1
  If a label is in several intervals, you get the locations of all the relevant intervals.
>>> i3 = pd.Interval(0, 2)
>>> overlapping_index = pd.IntervalIndex([i1, i2, i3])
>>> overlapping_index.get_loc(0.5)
array([ True, False,  True])
  Only exact matches will be returned if an interval is provided.
>>> index.get_loc(pd.Interval(0, 1))
0


pandas.IntervalIndex.is_empty   propertyIntervalIndex.is_empty

Indicates if an interval is empty, meaning it contains no points.  New in version 0.25.0.   Returns
 bool or ndarray

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:
>>> pd.Interval(0, 1, closed='right').is_empty
False
  An Interval that does not contain any points is empty:
>>> pd.Interval(0, 0, closed='right').is_empty
True
>>> pd.Interval(0, 0, closed='left').is_empty
True
>>> pd.Interval(0, 0, closed='neither').is_empty
True
  An Interval that contains a single point is not empty:
>>> pd.Interval(0, 0, closed='both').is_empty
False
  An IntervalArray or IntervalIndex returns a boolean ndarray positionally indicating if an Interval is empty:
>>> ivs = [pd.Interval(0, 0, closed='neither'),
...        pd.Interval(1, 2, closed='neither')]
>>> pd.arrays.IntervalArray(ivs).is_empty
array([ True, False])
  Missing values are not considered empty:
>>> ivs = [pd.Interval(0, 0, closed='neither'), np.nan]
>>> pd.IntervalIndex(ivs).is_empty
array([ True, False])


pandas.IntervalIndex.is_non_overlapping_monotonic   IntervalIndex.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.


pandas.IntervalIndex.is_overlapping   propertyIntervalIndex.is_overlapping

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.  Returns
 bool

Boolean indicating if the IntervalIndex has overlapping intervals.      See also  Interval.overlaps

Check whether two Interval objects overlap.  IntervalIndex.overlaps

Check an IntervalIndex elementwise for overlaps.    Examples
>>> index = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (4, 5)])
>>> index
IntervalIndex([(0, 2], (1, 3], (4, 5]],
      dtype='interval[int64, right]')
>>> index.is_overlapping
True
  Intervals that share closed endpoints overlap:
>>> index = pd.interval_range(0, 3, closed='both')
>>> index
IntervalIndex([[0, 1], [1, 2], [2, 3]],
      dtype='interval[int64, both]')
>>> index.is_overlapping
True
  Intervals that only have an open endpoint in common do not overlap:
>>> index = pd.interval_range(0, 3, closed='left')
>>> index
IntervalIndex([[0, 1), [1, 2), [2, 3)],
      dtype='interval[int64, left]')
>>> index.is_overlapping
False


pandas.IntervalIndex.left   IntervalIndex.left


pandas.IntervalIndex.length   propertyIntervalIndex.length


pandas.IntervalIndex.mid   IntervalIndex.mid


pandas.IntervalIndex.overlaps   IntervalIndex.overlaps(*args, **kwargs)[source]

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.  Parameters

other:IntervalArray

Interval to check against for an overlap.    Returns
 ndarray

Boolean array positionally indicating where an overlap occurs.      See also  Interval.overlaps

Check whether two Interval objects overlap.    Examples
>>> data = [(0, 1), (1, 3), (2, 4)]
>>> intervals = pd.arrays.IntervalArray.from_tuples(data)
>>> intervals
<IntervalArray>
[(0, 1], (1, 3], (2, 4]]
Length: 3, dtype: interval[int64, right]

>>> intervals.overlaps(pd.Interval(0.5, 1.5))
array([ True,  True, False])
  Intervals that share closed endpoints overlap:
>>> intervals.overlaps(pd.Interval(1, 3, closed='left'))
array([ True,  True, True])
  Intervals that only have an open endpoint in common do not overlap:
>>> intervals.overlaps(pd.Interval(1, 2, closed='right'))
array([False,  True, False])


pandas.IntervalIndex.right   IntervalIndex.right


pandas.IntervalIndex.set_closed   IntervalIndex.set_closed(*args, **kwargs)[source]

Return an IntervalArray identical to the current one, but closed on the specified side.  Parameters

closed:{‘left’, ‘right’, ‘both’, ‘neither’}

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

new_index:IntervalArray

   Examples
>>> index = pd.arrays.IntervalArray.from_breaks(range(4))
>>> index
<IntervalArray>
[(0, 1], (1, 2], (2, 3]]
Length: 3, dtype: interval[int64, right]
>>> index.set_closed('both')
<IntervalArray>
[[0, 1], [1, 2], [2, 3]]
Length: 3, dtype: interval[int64, both]


pandas.IntervalIndex.to_tuples   IntervalIndex.to_tuples(*args, **kwargs)[source]

Return an ndarray of tuples of the form (left, right).  Parameters

na_tuple:bool, default True

Returns NA as a tuple if True, (nan, nan), or just as the NA value itself if False, nan.    Returns
 tuples: ndarray


pandas.IntervalIndex.values   propertyIntervalIndex.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.   Returns
 array: numpy.ndarray or ExtensionArray
    See also  Index.array

Reference to the underlying data.  Index.to_numpy

A NumPy array representing the underlying data.


pandas.io.formats.style.Styler   classpandas.io.formats.style.Styler(data, precision=None, table_styles=None, uuid=None, caption=None, table_attributes=None, cell_ids=True, na_rep=None, uuid_len=5, decimal=None, thousands=None, escape=None, formatter=None)[source]

Helps style a DataFrame or Series according to the data with HTML and CSS.  Parameters

data:Series or DataFrame

Data to be styled - either a Series or DataFrame.
precision:int, optional

Precision to round floats to. If not given defaults to pandas.options.styler.format.precision.  Changed in version 1.4.0.
table_styles:list-like, default None

List of {selector: (attr, value)} dicts; see Notes.
uuid:str, default None

A unique identifier to avoid CSS collisions; generated automatically.
caption:str, tuple, default None

String caption to attach to the table. Tuple only used for LaTeX dual captions.
table_attributes:str, default None

Items that show up in the opening <table> tag in addition to automatic (by default) id.
cell_ids:bool, default True

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.
na_rep:str, optional

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.
uuid_len:int, default 5

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.
decimal:str, optional

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.
thousands:str, optional, default None

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.
escape:str, optional

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.
formatter:str, callable, dict, optional

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  DataFrame.style

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.


pandas.io.formats.style.Styler.apply   Styler.apply(func, axis=0, subset=None, **kwargs)[source]

Apply a CSS-styling function column-wise, row-wise, or table-wise. Updates the HTML representation with the result.  Parameters

func:function

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.
axis:{0 or ‘index’, 1 or ‘columns’, None}, default 0

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

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

Pass along to func.    Returns

self:Styler

    See also  Styler.applymap_index

Apply a CSS-styling function to headers elementwise.  Styler.apply_index

Apply a CSS-styling function to headers level-wise.  Styler.applymap

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
>>> def highlight_max(x, color):
...     return np.where(x == np.nanmax(x.to_numpy()), f"color: {color};", None)
>>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
>>> df.style.apply(highlight_max, color='red')
>>> df.style.apply(highlight_max, color='blue', axis=1)
>>> df.style.apply(highlight_max, color='green', axis=None)
  Using subset to restrict application to a single column or multiple columns
>>> df.style.apply(highlight_max, color='red', subset="A")
...
>>> df.style.apply(highlight_max, color='red', subset=["A", "B"])
...
  Using a 2d input to subset to select rows in addition to columns
>>> df.style.apply(highlight_max, color='red', subset=([0,1,2], slice(None)))
...
>>> df.style.apply(highlight_max, color='red', subset=(slice(0,5,2), "A"))
...
  Using a function which returns a Series / DataFrame of unequal length but containing valid index labels
>>> df = pd.DataFrame([[1, 2], [3, 4], [4, 6]], index=["A1", "A2", "Total"])
>>> total_style = pd.Series("font-weight: bold;", index=["Total"])
>>> df.style.apply(lambda s: total_style)
  See Table Visualization user guide for more details.


pandas.io.formats.style.Styler.apply_index   Styler.apply_index(func, axis=0, level=None, **kwargs)[source]

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.   Parameters

func:function

func should take a Series and return a string array of the same length.
axis:{0, 1, “index”, “columns”}

The headers over which to apply the function.
level:int, str, list, optional

If index is MultiIndex the level(s) over which to apply the function.
**kwargs:dict

Pass along to func.    Returns

self:Styler

    See also  Styler.applymap_index

Apply a CSS-styling function to headers elementwise.  Styler.apply

Apply a CSS-styling function column-wise, row-wise, or table-wise.  Styler.applymap

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.
>>> df = pd.DataFrame([[1,2], [3,4]], index=["A", "B"])
>>> def color_b(s):
...     return np.where(s == "B", "background-color: yellow;", "")
>>> df.style.apply_index(color_b)
     Selectively applying to specific levels of MultiIndex columns.
>>> midx = pd.MultiIndex.from_product([['ix', 'jy'], [0, 1], ['x3', 'z4']])
>>> df = pd.DataFrame([np.arange(8)], columns=midx)
>>> def highlight_x(s):
...     return ["background-color: yellow;" if "x" in v else "" for v in s]
>>> df.style.apply_index(highlight_x, axis="columns", level=[0, 2])
...


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

Apply a CSS-styling function elementwise. Updates the HTML representation with the result.  Parameters

func:function

func should take a scalar and return a string.
subset:label, array-like, IndexSlice, optional

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

Pass along to func.    Returns

self:Styler

    See also  Styler.applymap_index

Apply a CSS-styling function to headers elementwise.  Styler.apply_index

Apply a CSS-styling function to headers level-wise.  Styler.apply

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
>>> def color_negative(v, color):
...     return f"color: {color};" if v < 0 else None
>>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
>>> df.style.applymap(color_negative, color='red')
  Using subset to restrict application to a single column or multiple columns
>>> df.style.applymap(color_negative, color='red', subset="A")
...
>>> df.style.applymap(color_negative, color='red', subset=["A", "B"])
...
  Using a 2d input to subset to select rows in addition to columns
>>> df.style.applymap(color_negative, color='red',
...  subset=([0,1,2], slice(None)))
>>> df.style.applymap(color_negative, color='red', subset=(slice(0,5,2), "A"))
...
  See Table Visualization user guide for more details.


pandas.io.formats.style.Styler.applymap_index   Styler.applymap_index(func, axis=0, level=None, **kwargs)[source]

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.   Parameters

func:function

func should take a scalar and return a string.
axis:{0, 1, “index”, “columns”}

The headers over which to apply the function.
level:int, str, list, optional

If index is MultiIndex the level(s) over which to apply the function.
**kwargs:dict

Pass along to func.    Returns

self:Styler

    See also  Styler.apply_index

Apply a CSS-styling function to headers level-wise.  Styler.apply

Apply a CSS-styling function column-wise, row-wise, or table-wise.  Styler.applymap

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.
>>> df = pd.DataFrame([[1,2], [3,4]], index=["A", "B"])
>>> def color_b(s):
...     return "background-color: yellow;" if v == "B" else None
>>> df.style.applymap_index(color_b)
     Selectively applying to specific levels of MultiIndex columns.
>>> midx = pd.MultiIndex.from_product([['ix', 'jy'], [0, 1], ['x3', 'z4']])
>>> df = pd.DataFrame([np.arange(8)], columns=midx)
>>> def highlight_x(v):
...     return "background-color: yellow;" if "x" in v else None
>>> df.style.applymap_index(highlight_x, axis="columns", level=[0, 2])
...


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

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.  Parameters

cmap:str or colormap

Matplotlib colormap.
low:float

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

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

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

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

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

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

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

Gradient map for determining the 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.     Returns

self:Styler

    See also  Styler.text_gradient

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
>>> df = pd.DataFrame(columns=["City", "Temp (c)", "Rain (mm)", "Wind (m/s)"],
...                   data=[["Stockholm", 21.6, 5.0, 3.2],
...                         ["Oslo", 22.4, 13.3, 3.1],
...                         ["Copenhagen", 24.5, 0.0, 6.7]])
  Shading the values column-wise, with axis=0, preselecting numeric columns
>>> df.style.background_gradient(axis=0)
     Shading all values collectively using axis=None
>>> df.style.background_gradient(axis=None)
     Compress the color map from the both low and high ends
>>> df.style.background_gradient(axis=None, low=0.75, high=1.0)
     Manually setting vmin and vmax gradient thresholds
>>> df.style.background_gradient(axis=None, vmin=6.7, vmax=21.6)
     Setting a gmap and applying to all columns with another cmap
>>> df.style.background_gradient(axis=0, gmap=df['Temp (c)'], cmap='YlOrRd')
...
     Setting the gradient map for a dataframe (i.e. axis=None), we need to explicitly state subset to match the gmap shape
>>> gmap = np.array([[1,2,3], [2,3,4], [3,4,5]])
>>> df.style.background_gradient(axis=None, gmap=gmap,
...     cmap='YlOrRd', subset=['Temp (c)', 'Rain (mm)', 'Wind (m/s)']
... )


pandas.io.formats.style.Styler.bar   Styler.bar(subset=None, axis=0, *, color=None, cmap=None, width=100, height=100, align='mid', vmin=None, vmax=None, props='width: 10em;')[source]

Draw bar chart in the cell backgrounds.  Changed in version 1.4.0.   Parameters

subset:label, array-like, IndexSlice, optional

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

Apply to each column (axis=0 or 'index'), to each row (axis=1 or 'columns'), or to the entire DataFrame at once with axis=None.
color:str or 2-tuple/list

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’]).
cmap:str, matplotlib.cm.ColorMap

A string name of a matplotlib Colormap, or a Colormap object. Cannot be used together with color.  New in version 1.4.0.
width:float, default 100

The percentage of the cell, measured from the left, in which to draw the bars, in [0, 100].
height:float, default 100

The percentage height of the bar in the cell, centrally aligned, in [0,100].  New in version 1.4.0.
align:str, int, float, callable, default ‘mid’

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.
vmin:float, optional

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.
vmax:float, optional

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.
props:str, optional

The base CSS of the cell that is extended to add the bar chart. Defaults to “width: 10em;”.  New in version 1.4.0.     Returns

self:Styler

   Notes This section of the user guide: Table Visualization gives a number of examples for different settings and color coordination.


pandas.io.formats.style.Styler.clear   Styler.clear()[source]

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


pandas.io.formats.style.Styler.env   Styler.env=<jinja2.environment.Environment object>


pandas.io.formats.style.Styler.export   Styler.export()[source]

Export the styles applied to the current Styler. Can be applied to a second Styler with Styler.use.  Returns

styles:dict

    See also  Styler.use

Set the styles on the current Styler.  Styler.copy

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
>>> styler = DataFrame([[1, 2], [3, 4]]).style
>>> styler2 = DataFrame([[9, 9, 9]]).style
>>> styler.hide(axis=0).highlight_max(axis=1)
>>> export = styler.export()
>>> styler2.use(export)


pandas.io.formats.style.Styler.format   Styler.format(formatter=None, subset=None, na_rep=None, precision=None, decimal='.', thousands=None, escape=None, hyperlinks=None)[source]

Format the text display value of cells.  Parameters

formatter:str, callable, dict or None

Object to define how values are displayed. See notes.
subset:label, array-like, IndexSlice, optional

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

Representation for missing values. If na_rep is None, no special formatting is applied.  New in version 1.0.0.
precision:int, optional

Floating point precision to use for display purposes, if not determined by the specified formatter.  New in version 1.3.0.
decimal:str, default “.”

Character used as decimal separator for floats, complex and integers.  New in version 1.3.0.
thousands:str, optional, default None

Character used as thousands separator for floats, complex and integers.  New in version 1.3.0.
escape:str, optional

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.
hyperlinks:{“html”, “latex”}, optional

Convert string patterns containing https://, http://, ftp:// or www. to HTML  tags as clickable URL hyperlinks if “html”, or LaTeX href commands if “latex”.  New in version 1.4.0.     Returns

self:Styler

   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
>>> df = pd.DataFrame([[np.nan, 1.0, 'A'], [2.0, np.nan, 3.0]])
>>> df.style.format(na_rep='MISS', precision=3)
        0       1       2
0    MISS   1.000       A
1   2.000    MISS   3.000
  Using a formatter specification on consistent column dtypes
>>> df.style.format('{:.2f}', na_rep='MISS', subset=[0,1])
        0      1          2
0    MISS   1.00          A
1    2.00   MISS   3.000000
  Using the default formatter for unspecified columns
>>> df.style.format({0: '{:.2f}', 1: '£ {:.1f}'}, na_rep='MISS', precision=1)
...
         0      1     2
0    MISS   £ 1.0     A
1    2.00    MISS   3.0
  Multiple na_rep or precision specifications under the default formatter.
>>> df.style.format(na_rep='MISS', precision=1, subset=[0])
...     .format(na_rep='PASS', precision=2, subset=[1, 2])
        0      1      2
0    MISS   1.00      A
1     2.0   PASS   3.00
  Using a callable formatter function.
>>> func = lambda s: 'STRING' if isinstance(s, str) else 'FLOAT'
>>> df.style.format({0: '{:.1f}', 2: func}, precision=4, na_rep='MISS')
...
        0        1        2
0    MISS   1.0000   STRING
1     2.0     MISS    FLOAT
  Using a formatter with HTML escape and na_rep.
>>> df = pd.DataFrame([['

', '"A&B"', None]])
>>> s = df.style.format(
...     '{0}', escape="html", na_rep="NA"
...     )
>>> s.to_html()
...
<div></div>
"A&B"
NA
...
  Using a formatter with LaTeX escape.
>>> df = pd.DataFrame([["123"], ["~ ^"], ["$%#"]])
>>> df.style.format("\\textbf{{{}}}", escape="latex").to_latex()
...
\begin{tabular}{ll}
{} & {0} \\
0 & \textbf{123} \\
1 & \textbf{\textasciitilde \space \textasciicircum } \\
2 & \textbf{\$\%\#} \\
\end{tabular}


pandas.io.formats.style.Styler.format_index   Styler.format_index(formatter=None, axis=0, level=None, na_rep=None, precision=None, decimal='.', thousands=None, escape=None, hyperlinks=None)[source]

Format the text display value of index labels or column headers.  New in version 1.4.0.   Parameters

formatter:str, callable, dict or None

Object to define how values are displayed. See notes.
axis:{0, “index”, 1, “columns”}

Whether to apply the formatter to the index or column headers.
level:int, str, list

The level(s) over which to apply the generic formatter.
na_rep:str, optional

Representation for missing values. If na_rep is None, no special formatting is applied.
precision:int, optional

Floating point precision to use for display purposes, if not determined by the specified formatter.
decimal:str, default “.”

Character used as decimal separator for floats, complex and integers.
thousands:str, optional, default None

Character used as thousands separator for floats, complex and integers.
escape:str, optional

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.
hyperlinks:{“html”, “latex”}, optional

Convert string patterns containing https://, http://, ftp:// or www. to HTML  tags as clickable URL hyperlinks if “html”, or LaTeX href commands if “latex”.    Returns

self:Styler

   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
>>> df = pd.DataFrame([[1, 2, 3]], columns=[2.0, np.nan, 4.0])
>>> df.style.format_index(axis=1, na_rep='MISS', precision=3)
    2.000    MISS   4.000
0       1       2       3
  Using a formatter specification on consistent dtypes in a level
>>> df.style.format_index('{:.2f}', axis=1, na_rep='MISS')
     2.00   MISS    4.00
0       1      2       3
  Using the default formatter for unspecified levels
>>> df = pd.DataFrame([[1, 2, 3]],
...     columns=pd.MultiIndex.from_arrays([["a", "a", "b"],[2, np.nan, 4]]))
>>> df.style.format_index({0: lambda v: upper(v)}, axis=1, precision=1)
...
               A       B
      2.0    nan     4.0
0       1      2       3
  Using a callable formatter function.
>>> func = lambda s: 'STRING' if isinstance(s, str) else 'FLOAT'
>>> df.style.format_index(func, axis=1, na_rep='MISS')
...
          STRING  STRING
    FLOAT   MISS   FLOAT
0       1      2       3
  Using a formatter with HTML escape and na_rep.
>>> df = pd.DataFrame([[1, 2, 3]], columns=['"A"', 'A&B', None])
>>> s = df.style.format_index('$ {0}', axis=1, escape="html", na_rep="NA")
...
$ "A"
$ A&B
NA
...
  Using a formatter with LaTeX escape.
>>> df = pd.DataFrame([[1, 2, 3]], columns=["123", "~", "$%#"])
>>> df.style.format_index("\\textbf{{{}}}", escape="latex", axis=1).to_latex()
...
\begin{tabular}{lrrr}
{} & {\textbf{123}} & {\textbf{\textasciitilde }} & {\textbf{\$\%\#}} \\
0 & 1 & 2 & 3 \\
\end{tabular}


pandas.io.formats.style.Styler.from_custom_template   classmethodStyler.from_custom_template(searchpath, html_table=None, html_style=None)[source]

Factory function for creating a subclass of Styler. Uses custom templates and Jinja environment.  Changed in version 1.3.0.   Parameters

searchpath:str or list

Path or paths of directories containing the templates.
html_table:str

Name of your custom template to replace the html_table template.  New in version 1.3.0.
html_style:str

Name of your custom template to replace the html_style template.  New in version 1.3.0.     Returns

MyStyler:subclass of Styler

Has the correct env,``template_html``, template_html_table and template_html_style class attributes set.


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

Hide the entire index / column headers, or specific rows / columns from display.  New in version 1.4.0.   Parameters

subset:label, array-like, IndexSlice, optional

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.
axis:{“index”, 0, “columns”, 1}

Apply to the index or columns.
level:int, str, list

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

Whether to hide the level name(s) of the index / columns headers in the case it (or at least one the levels) remains visible.    Returns

self:Styler

   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:  Argument combinations
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:
>>> df = pd.DataFrame([[1,2], [3,4], [5,6]], index=["a", "b", "c"])
>>> df.style.hide(["a", "b"])
     0    1
c    5    6
  Hide the index and retain the data values:
>>> midx = pd.MultiIndex.from_product([["x", "y"], ["a", "b", "c"]])
>>> df = pd.DataFrame(np.random.randn(6,6), index=midx, columns=midx)
>>> df.style.format("{:.1f}").hide()
                 x                    y
   a      b      c      a      b      c
 0.1    0.0    0.4    1.3    0.6   -1.4
 0.7    1.0    1.3    1.5   -0.0   -0.2
 1.4   -0.8    1.6   -0.2   -0.4   -0.3
 0.4    1.0   -0.2   -0.8   -1.2    1.1
-0.6    1.2    1.8    1.9    0.3    0.3
 0.8    0.5   -0.3    1.2    2.2   -0.8
  Hide specific rows in a MultiIndex but retain the index:
>>> df.style.format("{:.1f}").hide(subset=(slice(None), ["a", "c"]))
...
                         x                    y
           a      b      c      a      b      c
x   b    0.7    1.0    1.3    1.5   -0.0   -0.2
y   b   -0.6    1.2    1.8    1.9    0.3    0.3
  Hide specific rows and the index through chaining:
>>> df.style.format("{:.1f}").hide(subset=(slice(None), ["a", "c"])).hide()
...
                 x                    y
   a      b      c      a      b      c
 0.7    1.0    1.3    1.5   -0.0   -0.2
-0.6    1.2    1.8    1.9    0.3    0.3
  Hide a specific level:
>>> df.style.format("{:,.1f}").hide(level=1)
                     x                    y
       a      b      c      a      b      c
x    0.1    0.0    0.4    1.3    0.6   -1.4
     0.7    1.0    1.3    1.5   -0.0   -0.2
     1.4   -0.8    1.6   -0.2   -0.4   -0.3
y    0.4    1.0   -0.2   -0.8   -1.2    1.1
    -0.6    1.2    1.8    1.9    0.3    0.3
     0.8    0.5   -0.3    1.2    2.2   -0.8
  Hiding just the index level names:
>>> df.index.names = ["lev0", "lev1"]
>>> df.style.format("{:,.1f}").hide(names=True)
                         x                    y
           a      b      c      a      b      c
x   a    0.1    0.0    0.4    1.3    0.6   -1.4
    b    0.7    1.0    1.3    1.5   -0.0   -0.2
    c    1.4   -0.8    1.6   -0.2   -0.4   -0.3
y   a    0.4    1.0   -0.2   -0.8   -1.2    1.1
    b   -0.6    1.2    1.8    1.9    0.3    0.3
    c    0.8    0.5   -0.3    1.2    2.2   -0.8
  Examples all produce equivalently transposed effects with axis="columns".