PeriodIndex#

class PeriodIndex#

Immutable ndarray holding ordinal values indicating regular periods in time.

Example#

import pandasCore as pd

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

Attributes#

Attribute

Description

Example

day

The day of the period

day_of_week

The day of the week (0=Monday, 6=Sunday)

day_of_year

The day of the year

dayofweek

The day of the week (0=Monday, 6=Sunday)

dayofyear

The day of the year

days_in_month

The number of days in the month

dtype

Return the dtype string for this PeriodIndex (e.g., ‘period[D]’)

empty

Indicator whether PeriodIndex is empty

end_time

Get the Timestamp for the end of the period

freq

Return the frequency string

freqstr

Return the frequency string for this PeriodIndex

has_duplicates

Return True if there are duplicate values

hour

The hour of the period

inferred_type

Return a string of the type inferred from the values

is_full

Return True if the index contains a full sequence of consecutive pe…

is_leap_year

Indicator for whether the period is in a leap year

is_monotonic_decreasing

Return if the index is monotonic decreasing

is_monotonic_increasing

Return if the index is monotonic increasing

is_month_end

Indicator for whether the period is at the end of the month

is_month_start

Indicator for whether the period is at the start of the month

is_quarter_end

Indicator for whether the period is at the end of a quarter

is_quarter_start

Indicator for whether the period is at the start of a quarter

is_unique

Return if the index has unique values

is_year_end

Indicator for whether the period is at the end of a year

is_year_start

Indicator for whether the period is at the start of a year

minute

The minute of the period

month

The month of the period

name

Return the name of the PeriodIndex

ndim

Return the number of dimensions

nlevels

Return the number of levels

quarter

The quarter of the period

qyear

The quarter-year of the period

second

The second of the period

shape

Return a tuple of the shape of the underlying data

size

Return the number of elements in the PeriodIndex

start_time

Get the Timestamp for the start of the period

str

Vectorized string functions for Index.

View

week

The week of the year

weekofyear

The week of the year (alias for week)

year

The year of the period

Construction#

Method

Description

Example

__init__() (data: object = None, ordinal: object = None, freq: object = None, dtype: object = None, copy: bool = False, name: object = None, **kwargs)

Immutable ndarray holding ordinal values indicating regular periods…

View

Indexing / Selection#

Method

Description

Example

__getitem__() (arg0: object)

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

Return new PeriodIndex with elements at specified positions

where() (cond: collections.abc.Sequence[bool], other: object = None)

Replace values where the condition is False.

Data Manipulation#

Method

Description

Example

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

Make new PeriodIndex 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 PeriodIndex inserting new item at location

reindex() (target: object, 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 PeriodIndex name.

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

Set PeriodIndex name

Missing Data#

Method

Description

Example

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

Return PeriodIndex without NA values

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

Fill NA/NaT values with 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 of the Index.

mean() (skipna: bool = True, axis: object = 0)

Return the mean of the PeriodIndex values.

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

Return the minimum value of the Index.

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: collections.abc.Callable, na_action: object = None)

Map values using an input mapping or function.

Comparison#

Method

Description

Example

__eq__() (arg0: object)

__ge__() (arg0: object)

__gt__() (arg0: object)

__le__() (arg0: object)

__lt__() (arg0: object)

__ne__() (arg0: object)

equals() (other: pandasCore.PeriodIndex)

Determine if two PeriodIndex 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: str | None = None)

Create a DataFrame with a column containing the Index

transpose() ()

Return the transpose (returns self for 1D)

Combining#

Method

Description

Example

append() (other: pandasCore.PeriodIndex)

Append another PeriodIndex to this one

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

Join two PeriodIndex objects

Time Series#

Method

Description

Example

asfreq() (freq: object = None, how: str = 'E')

Convert the PeriodIndex to the specified frequency.

asof() (label: typing.SupportsInt)

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

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

Compute the difference between consecutive elements

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

Shift index by desired number of periods.

to_timestamp() (freq: object = None, how: str = 'start')

Cast to DatetimeArray/Index of timestamps.

I/O#

Method

Description

Example

to_flat_index() ()

Identity method (PeriodIndex is already 1D)

to_list() ()

Return a list of Period objects

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

Return the values as a NumPy array.

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 Period objects

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

infer_objects() (copy: bool = True)

Attempt to infer better dtype (no-op for PeriodIndex)

view() (cls: object = None)

Return a view on the index

Iteration#

Method

Description

Example

__contains__() (key: object)

__iter__() ()

__len__() ()

Set Operations#

Method

Description

Example

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

Return a new PeriodIndex with elements not in other

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

Return PeriodIndex with duplicate values removed

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

Indicate duplicate index values

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

Form the intersection of two PeriodIndex objects

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

Check if values are in the PeriodIndex

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

Return the symmetric difference with another PeriodIndex

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

Form the union of two PeriodIndex objects

unique() (level: object = None)

Return unique values in the index

Datetime Methods#

Method

Description

Example

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

Round PeriodIndex values.

strftime() (date_format: str)

Convert to string using specified date_format.

Other Methods#

Method

Description

Example

__hash__()

__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: collections.abc.Sequence[typing.SupportsInt], mask: collections.abc.Sequence[bool] | None = None)

Return the locations (indices) of labels in the index

delete() (loc: typing.SupportsInt)

Make new PeriodIndex 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 = 'NaT', date_format: object = None)

Render a string representation of the Index

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

Compute indexer and mask for new index given the current index

get_indexer_for() (target: collections.abc.Sequence[typing.SupportsInt])

Get indexer for target values

get_indexer_non_unique() (target: pandasCore.PeriodIndex)

Get indexer for non-unique targets

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)

Get slice bound for a given label

holds_integer() ()

Check if the index holds integers (always False for PeriodIndex)

identical() (other: pandasCore.PeriodIndex)

Determine if two PeriodIndex objects are identical

item() ()

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

memory_usage() (deep: bool = False)

Memory usage of the values

putmask() (mask: collections.abc.Sequence[bool], value: typing.SupportsInt)

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

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

Return a flattened array of the index values.

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

Repeat elements of a PeriodIndex

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

Compute slice locations for input labels.

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

Compute slice locations for input labels

sort() (*args, **kwargs) | (*args, **kwargs) | (*args, **kwargs)

Return a sorted copy of the index

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

Sort MultiIndex at the requested level

Code Examples#

The following examples are extracted from the test suite.

str (test_timedelta_period_str.py:141)
131def test_periodindex_str_call_with_data():
132    """Test PeriodIndex.str(data) call."""
133    print("Testing PeriodIndex.str(data) call...")
134
135    # Create a PeriodIndex
136    pi = pandasCore.PeriodIndex(['2020-01', '2020-02'], freq='M')
137
138    # Call PeriodIndex.str with the index as argument
139    try:
140        str_accessor = pandasCore.PeriodIndex.str(pi)
141        print(f"  PeriodIndex.str(pi) returned: {type(str_accessor)}")
142        print("  PASSED: PeriodIndex.str(data) call works")
143    except Exception as e:
144        # Expected to raise error since PeriodIndex doesn't contain strings
145        print(f"  Error (expected for non-string data): {e}")
146        print("  PASSED: Appropriate error raised for non-string Index")
147
148# =============================================================================
149# Main test function
150# =============================================================================
__init__ (test_index_methods.py:48)
38    global tests_run
39    tests_run += 1
40    idx = pandasCore.TimedeltaIndex(['1 day', '2 days'])
41    result = idx.transpose()
42    assert len(result) == 2, f"Expected 2 elements, got {len(result)}"
43
44def test_periodindex_sort():
45    """Test PeriodIndex.sort"""
46    global tests_run
47    tests_run += 1
48    idx = pandasCore.PeriodIndex(['2023-03', '2023-01', '2023-02'], freq='M')
49    result = idx.sort()
50    assert len(result) == 3, f"Expected 3 elements, got {len(result)}"
51
52def test_periodindex_view():
53    """Test PeriodIndex.view"""
54    global tests_run
55    tests_run += 1
56    idx = pandasCore.PeriodIndex(['2023-01', '2023-02'], freq='M')
57    result = idx.view()
58    assert len(result) == 2, f"Expected 2 elements, got {len(result)}"