PeriodIndex =========== .. currentmodule:: pandasCore .. class:: PeriodIndex Immutable ndarray holding ordinal values indicating regular periods in time. Example ------- .. code-block:: python import pandasCore as pd # Create PeriodIndex idx = pd.PeriodIndex([1, 2, 3], name='my_index') print(len(idx)) # 3 Attributes ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Attribute - Description - Example * - :attr:`~PeriodIndex.day` - The day of the period - * - :attr:`~PeriodIndex.day_of_week` - The day of the week (0=Monday, 6=Sunday) - * - :attr:`~PeriodIndex.day_of_year` - The day of the year - * - :attr:`~PeriodIndex.dayofweek` - The day of the week (0=Monday, 6=Sunday) - * - :attr:`~PeriodIndex.dayofyear` - The day of the year - * - :attr:`~PeriodIndex.days_in_month` - The number of days in the month - * - :attr:`~PeriodIndex.dtype` - Return the dtype string for this PeriodIndex (e.g., 'period[D]') - * - :attr:`~PeriodIndex.empty` - Indicator whether PeriodIndex is empty - * - :attr:`~PeriodIndex.end_time` - Get the Timestamp for the end of the period - * - :attr:`~PeriodIndex.freq` - Return the frequency string - * - :attr:`~PeriodIndex.freqstr` - Return the frequency string for this PeriodIndex - * - :attr:`~PeriodIndex.has_duplicates` - Return True if there are duplicate values - * - :attr:`~PeriodIndex.hour` - The hour of the period - * - :attr:`~PeriodIndex.inferred_type` - Return a string of the type inferred from the values - * - :attr:`~PeriodIndex.is_full` - Return True if the index contains a full sequence of consecutive pe... - * - :attr:`~PeriodIndex.is_leap_year` - Indicator for whether the period is in a leap year - * - :attr:`~PeriodIndex.is_monotonic_decreasing` - Return if the index is monotonic decreasing - * - :attr:`~PeriodIndex.is_monotonic_increasing` - Return if the index is monotonic increasing - * - :attr:`~PeriodIndex.is_month_end` - Indicator for whether the period is at the end of the month - * - :attr:`~PeriodIndex.is_month_start` - Indicator for whether the period is at the start of the month - * - :attr:`~PeriodIndex.is_quarter_end` - Indicator for whether the period is at the end of a quarter - * - :attr:`~PeriodIndex.is_quarter_start` - Indicator for whether the period is at the start of a quarter - * - :attr:`~PeriodIndex.is_unique` - Return if the index has unique values - * - :attr:`~PeriodIndex.is_year_end` - Indicator for whether the period is at the end of a year - * - :attr:`~PeriodIndex.is_year_start` - Indicator for whether the period is at the start of a year - * - :attr:`~PeriodIndex.minute` - The minute of the period - * - :attr:`~PeriodIndex.month` - The month of the period - * - :attr:`~PeriodIndex.name` - Return the name of the PeriodIndex - * - :attr:`~PeriodIndex.ndim` - Return the number of dimensions - * - :attr:`~PeriodIndex.nlevels` - Return the number of levels - * - :attr:`~PeriodIndex.quarter` - The quarter of the period - * - :attr:`~PeriodIndex.qyear` - The quarter-year of the period - * - :attr:`~PeriodIndex.second` - The second of the period - * - :attr:`~PeriodIndex.shape` - Return a tuple of the shape of the underlying data - * - :attr:`~PeriodIndex.size` - Return the number of elements in the PeriodIndex - * - :attr:`~PeriodIndex.start_time` - Get the Timestamp for the start of the period - * - :attr:`~PeriodIndex.str` - Vectorized string functions for Index. - :ref:`View ` * - :attr:`~PeriodIndex.week` - The week of the year - * - :attr:`~PeriodIndex.weekofyear` - The week of the year (alias for week) - * - :attr:`~PeriodIndex.year` - The year of the period - Construction ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.__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... - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.__getitem__` ``(arg0: object)`` - - * - :meth:`~PeriodIndex.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 - * - :meth:`~PeriodIndex.where` ``(cond: collections.abc.Sequence[bool], other: object = None)`` - Replace values where the condition is False. - Data Manipulation ----------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.drop` ``(labels: object, errors: str = 'raise')`` - Make new PeriodIndex with passed list of labels deleted. - * - :meth:`~PeriodIndex.droplevel` ``(level: typing.SupportsInt = 0)`` - Return index with requested level(s) removed. - * - :meth:`~PeriodIndex.insert` ``(loc: typing.SupportsInt, item: object)`` - Make new PeriodIndex inserting new item at location - * - :meth:`~PeriodIndex.reindex` ``(target: object, method: object = None, level: object = None, limit: object = None, tolerance: object = None)`` - Conform Index to new index with optional filling logic - * - :meth:`~PeriodIndex.rename` ``(name: object, *, inplace: bool = False)`` - Alter PeriodIndex name. - * - :meth:`~PeriodIndex.set_names` ``(names: object, *, level: object = None, inplace: bool = False)`` - Set PeriodIndex name - Missing Data ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.dropna` ``(how: str = 'any')`` - Return PeriodIndex without NA values - * - :meth:`~PeriodIndex.fillna` ``(value: object = None, downcast: object = None)`` - Fill NA/NaT values with specified value - * - :meth:`~PeriodIndex.isna` ``()`` - Detect missing values - * - :meth:`~PeriodIndex.isnull` ``()`` - Detect missing values (alias for isna) - * - :meth:`~PeriodIndex.notna` ``()`` - Detect existing (non-missing) values - * - :meth:`~PeriodIndex.notnull` ``()`` - Detect existing (non-missing) values (alias for notna) - Statistics ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.max` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return the maximum value of the Index. - * - :meth:`~PeriodIndex.mean` ``(skipna: bool = True, axis: object = 0)`` - Return the mean of the PeriodIndex values. - * - :meth:`~PeriodIndex.min` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return the minimum value of the Index. - * - :meth:`~PeriodIndex.nunique` ``(dropna: bool = True)`` - Return number of unique elements in the index - * - :meth:`~PeriodIndex.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 ----------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.groupby` ``(values: collections.abc.Sequence[typing.SupportsInt])`` - Group the index labels by a given array of values - * - :meth:`~PeriodIndex.map` ``(mapper: collections.abc.Callable, na_action: object = None)`` - Map values using an input mapping or function. - Comparison ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.__eq__` ``(arg0: object)`` - - * - :meth:`~PeriodIndex.__ge__` ``(arg0: object)`` - - * - :meth:`~PeriodIndex.__gt__` ``(arg0: object)`` - - * - :meth:`~PeriodIndex.__le__` ``(arg0: object)`` - - * - :meth:`~PeriodIndex.__lt__` ``(arg0: object)`` - - * - :meth:`~PeriodIndex.__ne__` ``(arg0: object)`` - - * - :meth:`~PeriodIndex.equals` ``(other: pandasCore.PeriodIndex)`` - Determine if two PeriodIndex objects are equal - Sorting ------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.argsort` ``(*args, **kwargs)`` - Return the indices that would sort the index - * - :meth:`~PeriodIndex.searchsorted` ``(value: object, side: str = 'left', sorter: object = None)`` - Find indices where elements should be inserted to maintain order - * - :meth:`~PeriodIndex.sort_values` ``(*, return_indexer: bool = False, ascending: bool = True, na_position: str = 'last', key: object = None)`` - Return a sorted copy of the index - Reshaping --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.to_frame` ``(index: bool = True, name: str | None = None)`` - Create a DataFrame with a column containing the Index - * - :meth:`~PeriodIndex.transpose` ``()`` - Return the transpose (returns self for 1D) - Combining --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.append` ``(other: pandasCore.PeriodIndex)`` - Append another PeriodIndex to this one - * - :meth:`~PeriodIndex.join` ``(other: pandasCore.PeriodIndex, *, how: str = 'left', level: object = None, return_indexers: bool = False, sort: bool = False)`` - Join two PeriodIndex objects - Time Series ----------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.asfreq` ``(freq: object = None, how: str = 'E')`` - Convert the PeriodIndex to the specified frequency. - * - :meth:`~PeriodIndex.asof` ``(label: typing.SupportsInt)`` - Return the label from the index, or, if not present, the previous one - * - :meth:`~PeriodIndex.diff` ``(periods: typing.SupportsInt = 1)`` - Compute the difference between consecutive elements - * - :meth:`~PeriodIndex.shift` ``(periods: typing.SupportsInt = 1, freq: object = None)`` - Shift index by desired number of periods. - * - :meth:`~PeriodIndex.to_timestamp` ``(freq: object = None, how: str = 'start')`` - Cast to DatetimeArray/Index of timestamps. - I/O --- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.to_flat_index` ``()`` - Identity method (PeriodIndex is already 1D) - * - :meth:`~PeriodIndex.to_list` ``()`` - Return a list of Period objects - * - :meth:`~PeriodIndex.to_numpy` ``(dtype: object = None, copy: bool = False, na_value: object = None, **kwargs)`` - Return the values as a NumPy array. - * - :meth:`~PeriodIndex.to_series` ``(index: object = None, name: object = None)`` - Create a Series with both index and values equal to the index keys - * - :meth:`~PeriodIndex.tolist` ``()`` - Return a list of Period objects - Conversion ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.astype` ``(dtype: str, copy: bool = True)`` - Cast to a specified dtype. - * - :meth:`~PeriodIndex.copy` ``(name: object = None, deep: bool = False)`` - Make a copy of this PeriodIndex. - * - :meth:`~PeriodIndex.infer_objects` ``(copy: bool = True)`` - Attempt to infer better dtype (no-op for PeriodIndex) - * - :meth:`~PeriodIndex.view` ``(cls: object = None)`` - Return a view on the index - Iteration --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.__contains__` ``(key: object)`` - - * - :meth:`~PeriodIndex.__iter__` ``()`` - - * - :meth:`~PeriodIndex.__len__` ``()`` - - Set Operations -------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.difference` ``(other: pandasCore.PeriodIndex, sort: object = None)`` - Return a new PeriodIndex with elements not in other - * - :meth:`~PeriodIndex.drop_duplicates` ``(*, keep: str = 'first')`` - Return PeriodIndex with duplicate values removed - * - :meth:`~PeriodIndex.duplicated` ``(keep: str = 'first')`` - Indicate duplicate index values - * - :meth:`~PeriodIndex.intersection` ``(other: pandasCore.PeriodIndex, sort: bool = False)`` - Form the intersection of two PeriodIndex objects - * - :meth:`~PeriodIndex.isin` ``(values: object, level: object = None)`` - Check if values are in the PeriodIndex - * - :meth:`~PeriodIndex.symmetric_difference` ``(other: pandasCore.PeriodIndex, result_name: object = None, sort: object = None)`` - Return the symmetric difference with another PeriodIndex - * - :meth:`~PeriodIndex.union` ``(other: pandasCore.PeriodIndex, sort: object = None)`` - Form the union of two PeriodIndex objects - * - :meth:`~PeriodIndex.unique` ``(level: object = None)`` - Return unique values in the index - Datetime Methods ---------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.round` ``(decimals: typing.SupportsInt = 0)`` - Round PeriodIndex values. - * - :meth:`~PeriodIndex.strftime` ``(date_format: str)`` - Convert to string using specified date_format. - Other Methods ------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~PeriodIndex.__hash__` - - * - :meth:`~PeriodIndex.__repr__` ``()`` - - * - :meth:`~PeriodIndex.__str__` ``()`` - - * - :meth:`~PeriodIndex.all` ``(*args, **kwargs)`` - Return whether all elements are truthy - * - :meth:`~PeriodIndex.any` ``(*args, **kwargs)`` - Return whether any element is truthy - * - :meth:`~PeriodIndex.argmax` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return the index of the maximum value - * - :meth:`~PeriodIndex.argmin` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return the index of the minimum value - * - :meth:`~PeriodIndex.asof_locs` ``(where: collections.abc.Sequence[typing.SupportsInt], mask: collections.abc.Sequence[bool] | None = None)`` - Return the locations (indices) of labels in the index - * - :meth:`~PeriodIndex.delete` ``(loc: typing.SupportsInt)`` - Make new PeriodIndex with element at position deleted - * - :meth:`~PeriodIndex.factorize` ``(sort: bool = False, use_na_sentinel: bool = True)`` - Encode the object as an enumerated type or categorical variable - * - :meth:`~PeriodIndex.format` ``(name: bool = False, formatter: object = None, na_rep: str = 'NaT', date_format: object = None)`` - Render a string representation of the Index - * - :meth:`~PeriodIndex.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 - * - :meth:`~PeriodIndex.get_indexer_for` ``(target: collections.abc.Sequence[typing.SupportsInt])`` - Get indexer for target values - * - :meth:`~PeriodIndex.get_indexer_non_unique` ``(target: pandasCore.PeriodIndex)`` - Get indexer for non-unique targets - * - :meth:`~PeriodIndex.get_level_values` ``(level: object)`` - Return an Index of values for requested level - * - :meth:`~PeriodIndex.get_loc` ``(key: typing.SupportsInt)`` - Get integer location for requested label - * - :meth:`~PeriodIndex.get_slice_bound` ``(label: typing.SupportsInt, side: str)`` - Get slice bound for a given label - * - :meth:`~PeriodIndex.holds_integer` ``()`` - Check if the index holds integers (always False for PeriodIndex) - * - :meth:`~PeriodIndex.identical` ``(other: pandasCore.PeriodIndex)`` - Determine if two PeriodIndex objects are identical - * - :meth:`~PeriodIndex.item` ``()`` - Return the first element as a scalar (only for single-element index) - * - :meth:`~PeriodIndex.memory_usage` ``(deep: bool = False)`` - Memory usage of the values - * - :meth:`~PeriodIndex.putmask` ``(mask: collections.abc.Sequence[bool], value: typing.SupportsInt)`` - Return a new PeriodIndex with values put where mask is True. - * - :meth:`~PeriodIndex.ravel` ``(order: str = 'C')`` - Return a flattened array of the index values. - * - :meth:`~PeriodIndex.repeat` ``(repeats: typing.SupportsInt, axis: object = None)`` - Repeat elements of a PeriodIndex - * - :meth:`~PeriodIndex.slice_indexer` ``(start: object = None, end: object = None, step: object = None)`` - Compute slice locations for input labels. - * - :meth:`~PeriodIndex.slice_locs` ``(start: object = None, end: object = None, step: object = None)`` - Compute slice locations for input labels - * - :meth:`~PeriodIndex.sort` ``(*args, **kwargs) | (*args, **kwargs) | (*args, **kwargs)`` - Return a sorted copy of the index - * - :meth:`~PeriodIndex.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. .. _example-periodindex-str-0: .. dropdown:: str (test_timedelta_period_str.py:141) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 131 :emphasize-lines: 11 def test_periodindex_str_call_with_data(): """Test PeriodIndex.str(data) call.""" print("Testing PeriodIndex.str(data) call...") # Create a PeriodIndex pi = pandasCore.PeriodIndex(['2020-01', '2020-02'], freq='M') # Call PeriodIndex.str with the index as argument try: str_accessor = pandasCore.PeriodIndex.str(pi) print(f" PeriodIndex.str(pi) returned: {type(str_accessor)}") print(" PASSED: PeriodIndex.str(data) call works") except Exception as e: # Expected to raise error since PeriodIndex doesn't contain strings print(f" Error (expected for non-string data): {e}") print(" PASSED: Appropriate error raised for non-string Index") # ============================================================================= # Main test function # ============================================================================= .. _example-periodindex-dunder-initdunder--1: .. dropdown:: __init__ (test_index_methods.py:48) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 38 :emphasize-lines: 11 global tests_run tests_run += 1 idx = pandasCore.TimedeltaIndex(['1 day', '2 days']) result = idx.transpose() assert len(result) == 2, f"Expected 2 elements, got {len(result)}" def test_periodindex_sort(): """Test PeriodIndex.sort""" global tests_run tests_run += 1 idx = pandasCore.PeriodIndex(['2023-03', '2023-01', '2023-02'], freq='M') result = idx.sort() assert len(result) == 3, f"Expected 3 elements, got {len(result)}" def test_periodindex_view(): """Test PeriodIndex.view""" global tests_run tests_run += 1 idx = pandasCore.PeriodIndex(['2023-01', '2023-02'], freq='M') result = idx.view() assert len(result) == 2, f"Expected 2 elements, got {len(result)}"