IntervalIndex#

class IntervalIndex#

Immutable index backed by interval data.

Example#

import pandasCore as pd

# Create IntervalIndex
idx = pd.IntervalIndex([1, 2, 3], name='my_index')
print(len(idx))  # 3

Attributes#

Attribute

Description

Example

closed

String describing the inclusive side(s) of the intervals

dtype

Return the dtype object of the underlying data

empty

Indicator whether IntervalIndex is empty

has_duplicates

Return if the index has duplicate values

is_empty

Indicates if an interval is empty (left == right and not both-closed)

is_monotonic_decreasing

Return if the index is monotonic decreasing

is_monotonic_increasing

Return if the index is monotonic increasing

is_non_overlapping_monotonic

Return True if intervals are non-overlapping and monotonically sorted

is_overlapping

Return True if any intervals overlap

is_unique

Return if the index has unique values

left

Return the left bounds of the intervals

length

Return the length of each interval

mid

Return the midpoint of each interval

name

Return the name of the IntervalIndex

ndim

Number of dimensions of the underlying data

nlevels

Number of levels in this index

right

Return the right bounds of the intervals

shape

Return a tuple of the shape of the underlying data

size

Return the number of elements in the IntervalIndex

str

Vectorized string functions for Index.

View

Construction#

Method

Description

Example

__init__() (*args, **kwargs) | () | (data: collections.abc.Sequence[tuple[typing.SupportsFloat, typing.SupportsFloat]], closed: object = None, dtype: object = None, copy: bool = False, name: object = None, verify_integrity: bool = True)

Create an empty IntervalIndex

View

Indexing / Selection#

Method

Description

Example

__getitem__() (arg0: typing.SupportsInt)

take() (indices: collections.abc.Sequence[typing.SupportsInt], axis: typing.SupportsInt = 0, allow_fill: bool = True, fill_value: object = None, **kwargs)

Return new IntervalIndex with elements at specified positions

where() (cond: object, other: object = None)

Replace values where the condition is False.

Data Manipulation#

Method

Description

Example

drop() (labels: object, errors: str = 'raise')

Make new Index with passed list of labels deleted

droplevel() (level: typing.SupportsInt = 0)

Return index with requested level(s) removed.

insert() (loc: typing.SupportsInt, item: object)

Make new IntervalIndex inserting new item at location

reindex() (target: pandasCore.IntervalIndex, method: object = None, level: object = None, limit: object = None, tolerance: object = None)

Conform Index to new index with optional filling logic

rename() (name: object, *, inplace: bool = False)

Alter IntervalIndex name.

set_names() (names: object, *, level: object = None, inplace: bool = False)

Set IntervalIndex name

Missing Data#

Method

Description

Example

dropna() (how: str = 'any')

Return IntervalIndex without NA values

fillna() (value: object = None, downcast: object = None)

Fill NA/NaN values with the specified value

isna() ()

Detect missing values

isnull() ()

Detect missing values (alias for isna)

notna() ()

Detect existing (non-missing) values

notnull() ()

Detect existing (non-missing) values (alias for notna)

Statistics#

Method

Description

Example

max() (axis: object = None, skipna: bool = True, *args, **kwargs)

Return the maximum interval (by left bound)

min() (axis: object = None, skipna: bool = True, *args, **kwargs)

Return the minimum interval (by left bound)

nunique() (dropna: bool = True)

Return number of unique elements in the index

value_counts() (normalize: bool = False, sort: bool = True, ascending: bool = False, bins: object = None, dropna: bool = True)

Return a dict containing counts of unique values

Aggregation#

Method

Description

Example

groupby() (values: collections.abc.Sequence[typing.SupportsInt])

Group the index labels by a given array of values

map() (mapper: object, na_action: object = None)

Map values using an input mapping or function

Comparison#

Method

Description

Example

__eq__() (self, value, /)

Return self==value.

__ge__() (self, value, /)

Return self>=value.

__gt__() (self, value, /)

Return self>value.

__le__() (self, value, /)

Return self<=value.

__lt__() (self, value, /)

Return self<value.

__ne__() (self, value, /)

Return self!=value.

equals() (other: pandasCore.IntervalIndex)

Determine if two IntervalIndex objects are equal

Sorting#

Method

Description

Example

argsort() (*args, **kwargs)

Return the indices that would sort the index

searchsorted() (value: object, side: str = 'left', sorter: object = None)

Find indices where elements should be inserted to maintain order

sort_values() (*, return_indexer: bool = False, ascending: bool = True, na_position: str = 'last', key: object = None)

Return a sorted copy of the index

Reshaping#

Method

Description

Example

to_frame() (index: bool = True, name: object = None)

Create a DataFrame with a column containing the IntervalIndex values

transpose() ()

Return the transpose (self for 1D index)

Combining#

Method

Description

Example

append() (other: pandasCore.IntervalIndex)

Append another IntervalIndex to this one

join() (other: pandasCore.IntervalIndex, *, how: str = 'left', level: object = None, return_indexers: bool = False, sort: bool = False)

Join this index with another

Time Series#

Method

Description

Example

asof() (label: object)

Return the label from the index, or, if not present, the previous one.

diff() (periods: typing.SupportsInt = 1)

Compute first-order differences

shift() (periods: typing.SupportsInt = 1, freq: object = None)

Shift index by desired number of periods

I/O#

Method

Description

Example

to_flat_index() ()

Return a flattened index

to_list() ()

Return a list of the intervals as tuples

to_numpy() (dtype: object = None, copy: bool = False, na_value: object = None, **kwargs)

A NumPy ndarray representing the values in this Series or Index

to_series() (index: object = None, name: object = None)

Create a Series with the IntervalIndex values

to_tuples() ()

Return a list of tuples of the form (left, right)

tolist() ()

Return a list of the intervals as tuples

Conversion#

Method

Description

Example

astype() (dtype: str, copy: bool = True)

Cast to a specified dtype.

copy() (name: object = None, deep: bool = False)

Make a copy of this IntervalIndex.

infer_objects() (copy: bool = True)

Infer objects type and return a converted version.

view() (cls: object = None)

Return a view of the index.

Iteration#

Method

Description

Example

__contains__() (key: tuple[typing.SupportsFloat, typing.SupportsFloat])

__iter__() ()

__len__() ()

Set Operations#

Method

Description

Example

difference() (other: pandasCore.IntervalIndex, sort: object = None)

Form the set difference of two IntervalIndex objects

drop_duplicates() (*, keep: str = 'first')

Return IntervalIndex with duplicate values removed

duplicated() (keep: str = 'first')

Indicate duplicate index values

intersection() (other: pandasCore.IntervalIndex, sort: bool = False)

Form the intersection of two IntervalIndex objects

isin() (values: collections.abc.Sequence[tuple[typing.SupportsFloat, typing.SupportsFloat]], level: object = None)

Check if values are in the IntervalIndex

symmetric_difference() (other: pandasCore.IntervalIndex, result_name: object = None, sort: object = None)

Form the symmetric difference of two IntervalIndex objects

union() (other: pandasCore.IntervalIndex, sort: object = None)

Form the union of two IntervalIndex objects

unique() (level: object = None)

Return unique values in the index

String Methods#

Method

Description

Example

contains() (other: typing.SupportsFloat)

Check elementwise if the Intervals contain the value.

Datetime Methods#

Method

Description

Example

round() (decimals: typing.SupportsInt = 0)

Round interval bounds to specified number of decimals

Other Methods#

Method

Description

Example

__hash__() (self, /)

Return hash(self).

__repr__() ()

__str__() ()

all() (*args, **kwargs)

Return whether all elements are truthy

any() (*args, **kwargs)

Return whether any element is truthy

argmax() (axis: object = None, skipna: bool = True, *args, **kwargs)

Return the index of the maximum value

argmin() (axis: object = None, skipna: bool = True, *args, **kwargs)

Return the index of the minimum value

asof_locs() (where: object, mask: object = None)

Return the locations (indices) of labels in the index.

delete() (loc: typing.SupportsInt)

Make new IntervalIndex with element at position deleted

factorize() (sort: bool = False, use_na_sentinel: bool = True)

Encode the object as an enumerated type or categorical variable

format() (name: bool = False, formatter: object = None, na_rep: str = 'NaN')

Format the IntervalIndex as list of strings

get_indexer() (target: pandasCore.IntervalIndex, method: object = None, limit: object = None, tolerance: object = None)

Compute indexer for new index given the current index

get_indexer_for() (target: pandasCore.IntervalIndex)

Guaranteed return of an indexer even when non-unique

get_indexer_non_unique() (target: pandasCore.IntervalIndex)

Compute indexer and mask for new index given the current index.

get_level_values() (level: object)

Return an IntervalIndex of values for requested level

get_loc() (key: tuple[typing.SupportsFloat, typing.SupportsFloat])

Get integer location for requested label

get_slice_bound() (label: object, side: str)

Calculate slice bound that corresponds to given label.

holds_integer() ()

Check if the index holds integers (always False for float64 Interva…

identical() (other: pandasCore.IntervalIndex)

Determine if two IntervalIndex objects are identical

item() ()

Return the first element as a scalar (only for single-element index)

memory_usage() (deep: bool = False)

Return memory usage of the index in bytes

overlaps() (left: typing.SupportsFloat, right: typing.SupportsFloat)

Check elementwise if an interval overlaps the values.

putmask() (mask: object, value: object)

Return a new IntervalIndex with values put where mask is True.

ravel() (order: str = 'C')

Return a flattened view of the index.

repeat() (repeats: typing.SupportsInt, axis: object = None)

Repeat elements of the index

set_closed() (closed: str)

Return an IntervalIndex with the specified closed side.

slice_indexer() (start: object = None, end: object = None, step: object = None)

Compute slice indexer for input labels.

slice_locs() (start: object = None, end: object = None, step: object = None)

Compute slice locations for input labels

sort() (ascending: bool = True)

Return a sorted copy of the index.

sortlevel() (level: object = None, ascending: bool = True, sort_remaining: object = None, na_position: str = 'first')

Sort index by level

Code Examples#

The following examples are extracted from the test suite.

str (test_interval_multi_range_str.py:79)
69def test_intervalindex_str_call_with_data():
70    """Test IntervalIndex.str(data) call."""
71    print("Testing IntervalIndex.str(data) call...")
72
73    # Create an IntervalIndex
74    ii = pandasCore.IntervalIndex.from_breaks([0, 1, 2])
75
76    # Call IntervalIndex.str with the index as argument
77    try:
78        str_accessor = pandasCore.IntervalIndex.str(ii)
79        print(f"  IntervalIndex.str(ii) returned: {type(str_accessor)}")
80        print("  PASSED: IntervalIndex.str(data) call works")
81    except Exception as e:
82        # Expected to raise error since IntervalIndex doesn't contain strings
83        print(f"  Error (expected for non-string data): {e}")
84        print("  PASSED: Appropriate error raised for non-string Index")
85
86# =============================================================================
87# MultiIndex.str tests
88# =============================================================================
__init__ (test_intervalindex.py:87)
77    ctx.assert_equal((0.0, 1.0), ii[0], "from_tuples first interval")
78    ctx.assert_equal((2.0, 3.0), ii[1], "from_tuples second interval")
79    ctx.assert_equal((4.0, 5.0), ii[2], "from_tuples third interval")
80
81
82def test_constructor():
83    """Test IntervalIndex constructor with list of tuples"""
84    f_print_header("Test: constructor")
85
86    data = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]
87    ii = pandasCore.IntervalIndex(data)
88
89    ctx.assert_equal(3, ii.size, "constructor size")
90    ctx.assert_equal("right", ii.closed, "constructor closed")
91
92    # With closed parameter
93    ii_both = pandasCore.IntervalIndex(data, closed="both")
94    ctx.assert_equal("both", ii_both.closed, "constructor closed=both")
95
96
97def test_properties():