RangeIndex#

class RangeIndex#

Immutable Index implementing a monotonic integer range.

Example#

import pandasCore as pd

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

Attributes#

Attribute

Description

Example

dtype

Return the dtype object of the underlying data

empty

Whether the Index is empty

has_duplicates

Return if the Index has duplicate values

is_monotonic_decreasing

Return boolean if values in the object are monotonically decreasing

is_monotonic_increasing

Return boolean if values in the object are monotonically increasing

is_unique

Return if the Index has unique values

name

Return Index or MultiIndex name

nbytes

Return the number of bytes in the underlying data

ndim

Number of dimensions of the underlying data, by definition 1

nlevels

Number of levels

shape

Return a tuple of the shape of the underlying data

size

Return the number of elements

start

The value of the start parameter

step

The value of the step parameter

stop

The value of the stop parameter

str

Vectorized string functions for Index.

View

Construction#

Method

Description

Example

__init__() (*args, **kwargs) | () | (start: object = None, stop: object = None, step: object = None, dtype: object = None, copy: bool = False, name: str | None = None)

Create an empty RangeIndex

View

Indexing / Selection#

Method

Description

Example

__getitem__() (arg0: object)

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

Return a new Index of the values selected by the indices

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: object = 0)

Return index with requested level(s) removed

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

Make new Index inserting new item at location

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

Create index with target’s values

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

Alter Index or MultiIndex name

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

Set Index or MultiIndex name

Missing Data#

Method

Description

Example

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

Return Index without NA/NaN 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 value

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

Return the minimum value

nunique() (dropna: bool = True)

Return number of unique elements in the object

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

Return a Series containing counts of unique values

Aggregation#

Method

Description

Example

groupby() (values: object)

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__() (arg0: object)

__ge__() (arg0: typing.SupportsInt)

__gt__() (arg0: typing.SupportsInt)

__le__() (arg0: typing.SupportsInt)

__lt__() (arg0: typing.SupportsInt)

__ne__() (arg0: object)

equals() (other: object)

Determine if two Index objects contain the same elements

Sorting#

Method

Description

Example

argsort() (*args, **kwargs)

Return the integer 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 Index

transpose() (*args, **kwargs)

Return the transpose, which is itself

Combining#

Method

Description

Example

append() (other: object)

Append a collection of Index options together

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

Compute join between this and another RangeIndex

Time Series#

Method

Description

Example

asof() (label: typing.SupportsInt)

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

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

Computes the difference between consecutive values

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

Shift index by desired number of periods

I/O#

Method

Description

Example

to_flat_index() ()

Identity method - returns itself for non-MultiIndex

to_list() ()

Return a list of the values

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

A NumPy ndarray representing the values in this Index

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

Create a Series with both index and values equal to the index keys

tolist() ()

Return a list of the values

Conversion#

Method

Description

Example

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

Create an Index with values cast to dtypes

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

Make a copy of this object

infer_objects() (copy: bool = True)

Attempt to infer better dtypes for object columns

view() (cls: object = None)

New view of the index

Iteration#

Method

Description

Example

__contains__() (arg0: typing.SupportsInt)

__iter__() ()

__len__() ()

Set Operations#

Method

Description

Example

difference() (other: object, sort: object = None)

Return a new Index with elements of index not in other

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

Return Index with duplicate values removed

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

Indicate duplicate index values

intersection() (other: object, sort: bool = False)

Form the intersection of two Index objects

isin() (values: object, level: object = None)

Return a boolean array where the index values are in values

symmetric_difference() (other: object, result_name: object = None, sort: object = None)

Compute the symmetric difference of two Index objects

union() (other: object, sort: object = None)

Form the union of two Index objects

unique() (level: object = None)

Return unique values in the index

Datetime Methods#

Method

Description

Example

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

Round each value in the Index to the given number of decimals

Other Methods#

Method

Description

Example

__hash__()

__repr__() ()

__str__() (self, /)

Return str(self).

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 int position of the largest value in the Series

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

Return int position of the smallest value in the Series

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

Return the locations (indices) of labels in the index

delete() (loc: object)

Make new Index with passed location(-s) 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')

Render a string representation of the Index

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

Compute indexer and mask for new index given current index

get_indexer_for() (target: object)

Get indexer for target elements

get_indexer_non_unique() (target: object)

Compute indexer and mask for new index given current index

get_level_values() (level: object)

Return an Index of values for requested level

get_loc() (key: typing.SupportsInt)

Get integer location for requested label

get_slice_bound() (label: typing.SupportsInt, side: str)

Calculate slice bound that corresponds to given label

holds_integer() ()

Whether the index holds integer dtypes

identical() (other: object)

Similar to equals, but also checks that names and dtypes are equal

item() ()

Return the first element of the underlying data as a Python scalar

memory_usage() (deep: bool = False)

Memory usage of the values

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

Return a new Index of the values set with the mask

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

Return a flattened array

repeat() (repeats: object, axis: object = None)

Repeat elements of a Index

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

Compute slice indexer for input labels and step

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

Compute slice locations for input labels

sort() (*args, **kwargs)

DEPRECATED: use sort_values instead

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

For internal compatibility with MultiIndex

Code Examples#

The following examples are extracted from the test suite.

str (test_interval_multi_range_str.py:209)
199def test_rangeindex_str_call_with_data():
200    """Test RangeIndex.str(data) call."""
201    print("Testing RangeIndex.str(data) call...")
202
203    # Create a RangeIndex
204    ri = pandasCore.RangeIndex(3)
205
206    # Call RangeIndex.str with the index as argument
207    try:
208        str_accessor = pandasCore.RangeIndex.str(ri)
209        print(f"  RangeIndex.str(ri) returned: {type(str_accessor)}")
210        print("  PASSED: RangeIndex.str(data) call works")
211    except Exception as e:
212        # Expected to raise error since RangeIndex doesn't contain strings
213        print(f"  Error (expected for non-string data): {e}")
214        print("  PASSED: Appropriate error raised for non-string Index")
215
216# =============================================================================
217# Main test function
218# =============================================================================
__init__ (test_example.py:222)
212        f_print_error(f"Exception: {e}")
213        return False
214
215
216def test_range_index():
217    """Test RangeIndex creation"""
218    f_print_header("Test: RangeIndex Creation")
219
220    try:
221        # Create RangeIndex
222        idx = pandasCore.RangeIndex(0, 10, 2)
223        f_print_success("Created RangeIndex(0, 10, 2)")
224
225        # Check properties
226        if idx.start == 0:
227            f_print_success(f"start is correct: {idx.start}")
228        else:
229            f_print_error(f"start is wrong: {idx.start}, expected 0")
230            return False
231
232        if idx.stop == 10: