Skip to content

DOC: add an example to PeriodIndex.to_timestamp to clarify the behavior in case len(index)<3 #57384

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,20 @@ def to_timestamp(self, freq=None, how: str = "start") -> DatetimeArray:
>>> idx.to_timestamp()
DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'],
dtype='datetime64[ns]', freq='MS')

The frequency will not be inferred if the index contains less than
three elements and values of index are not strictly monotonic:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the way this is phrased it sounds like (pseudocode):

if len(index) < 3 and not index.is_monotonic():
    dont_infer_frequency(...)

Instead, I think it's more like

if len(index) < 3 or not index.is_monotonic():
    dont_infer_frequency(...)

?

How about

        The frequency will not be inferred if the index contains less than
        three elements, or if the values of index are not strictly monotonic:

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks, you are right, my wording isn't correct. I changed it as you suggested.


>>> idx = pd.PeriodIndex(["2023-01", "2023-02"], freq="M")
>>> idx.to_timestamp()
DatetimeIndex(['2023-01-01', '2023-02-01'], dtype='datetime64[ns]', freq=None)

>>> idx = pd.PeriodIndex(
... ["2023-01", "2023-02", "2023-02", "2023-03"], freq="2M"
... )
>>> idx.to_timestamp()
DatetimeIndex(['2023-01-01', '2023-02-01', '2023-02-01', '2023-03-01'],
dtype='datetime64[ns]', freq=None)
"""
from pandas.core.arrays import DatetimeArray

Expand Down