Skip to content
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

BUG: Collision between equivalent frequencies 'QS-FEB' and 'QS-NOV' #61086

Open
2 of 3 tasks
rwijtvliet opened this issue Mar 8, 2025 · 7 comments · May be fixed by #61142
Open
2 of 3 tasks

BUG: Collision between equivalent frequencies 'QS-FEB' and 'QS-NOV' #61086

rwijtvliet opened this issue Mar 8, 2025 · 7 comments · May be fixed by #61142
Assignees
Labels
Bug Datetime Datetime data dtype Frequency DateOffsets

Comments

@rwijtvliet
Copy link

rwijtvliet commented Mar 8, 2025

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

>>> import pandas as pd
>>> i = pd.date_range('2020-02-01', freq='QS-MAY', periods=3)
>>> i
DatetimeIndex(['2020-02-01', '2020-05-01', '2020-08-01'], dtype='datetime64[ns]', freq='QS-MAY')
>>> pd.DatetimeIndex(i, freq='QS-FEB')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python312\Lib\site-packages\pandas\core\indexes\datetimes.py", line 370, in __new__
    dtarr = DatetimeArray._from_sequence_not_strict(
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python312\Lib\site-packages\pandas\core\arrays\datetimes.py", line 394, in _from_sequence_not_strict
    result._maybe_pin_freq(freq, validate_kwds)
  File "C:\Program Files\Python312\Lib\site-packages\pandas\core\arrays\datetimelike.py", line 2094, in _maybe_pin_freq
    _validate_inferred_freq(freq, self._freq)
  File "C:\Program Files\Python312\Lib\site-packages\pandas\core\arrays\datetimelike.py", line 2526, in _validate_inferred_freq
    raise ValueError(
ValueError: Inferred frequency <QuarterBegin: startingMonth=5> from passed values does not conform to passed frequency QS-FEB

Issue Description

pd.DatetimeIndex(...), when passed both an index with a frequency, AND a frequency, throws an error if the frequencies are unequal - even if they are equivalent.

Expected Behavior

If the frequencies are unequal, but equivalent (like in the example), an index with the specified (new) frequency should be returned.

That the frequencies are equivalent can be seen in the following snippet: simply direct setting the frequency of i to the specified frequency DOES work:

>>> i = pd.date_range('2020-02-01', freq='QS-MAY', periods=3)
>>> i.freq = 'QS-FEB'
>>> i
DatetimeIndex(['2020-02-01', '2020-05-01', '2020-08-01'], dtype='datetime64[ns]', freq='QS-FEB')

I think this only occurs for quarter-frequency, where "equivalent" means that the starting month mod 3 is equal.

Current workaround:

We don't want to change i, so the current workaround to i2 = pd.DatetimeIndex(i, freq='QS-FEB') is

i2 = i.copy()
i2.freq = 'QS-FEB'

...which is cumbersome, because it requires 2 steps and cannot be used in list comprehensions etc.

Alternatively, there is the elegant

i2 = pd.DatetimeIndex(i, freq=None).to_frame().asfreq(i.freq).index

Installed Versions

INSTALLED VERSIONS ------------------ commit : 0691c5c python : 3.12.2 python-bits : 64 OS : Windows OS-release : 10 Version : 10.0.19045 machine : AMD64 processor : Intel64 Family 6 Model 140 Stepping 1, GenuineIntel byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : English_United States.1252

pandas : 2.2.3
numpy : 2.1.1
pytz : 2024.2
dateutil : 2.9.0.post0
pip : 24.2
Cython : None
sphinx : None
IPython : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : None
lxml.etree : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : None
pyreadstat : None
pytest : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2024.2
qtpy : None
pyqt5 : None

@rwijtvliet rwijtvliet added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Mar 8, 2025
@rhshadrach
Copy link
Member

rhshadrach commented Mar 9, 2025

Thanks for the report. When setting the attribute, pandas generates the NumPy array with the new frequency and confirms that it matches the data underlying the DatetimeIndex. I'd be supportive of doing the same in DatetimeIndex.__init__.

I think we should also just be comparing frequency strings for those that do not have equivalents, and possibly fast-pathing other cases (i.e. not generating an entire new NumPy array). But that can be for another issue.

Edit: Any frequency can be equivalent to some other, I think.

@rhshadrach rhshadrach added Datetime Datetime data dtype and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Mar 9, 2025
@rwijtvliet
Copy link
Author

rwijtvliet commented Mar 9, 2025

Thanks for the quick triage!

Another welcome addition would be a method like DatetimeIndex.set_freq(), returning a copy of the index but with the specified frequency.

Analogous methods exist for changing other properties of (a copy of) the index - to such as DatetimeIndex.rename() (for the index name), .tz_localize() and .tz_convert() (for the timezone).

If that exists, I'd prefer it over using DatetimeIndex.__init__, as it is more specific and signals intent.

@ycdjun
Copy link

ycdjun commented Mar 12, 2025

Take

ycdjun pushed a commit to ycdjun/pandas that referenced this issue Mar 18, 2025
@ycdjun ycdjun linked a pull request Mar 18, 2025 that will close this issue
5 tasks
@rhshadrach
Copy link
Member

Another welcome addition would be a method like DatetimeIndex.set_freq(), returning a copy of the index but with the specified frequency.

I think this should be separated off into its own issue. Can you open a new one with this enhancement request.

@rwijtvliet
Copy link
Author

Another welcome addition would be a method like DatetimeIndex.set_freq(), returning a copy of the index but with the specified frequency.

I think this should be separated off into its own issue. Can you open a new one with this enhancement request.

Yes, I agree. See here.

ycdjun pushed a commit to ycdjun/pandas that referenced this issue Mar 19, 2025
@rhshadrach rhshadrach added the Frequency DateOffsets label Mar 19, 2025
ycdjun pushed a commit to ycdjun/pandas that referenced this issue Mar 20, 2025
@jbrockmendel
Copy link
Member

  1. As long as there are equivalent-but-not-equal offsets, seems like we need to do a check other than equality in validate_inferred_freq
  2. My knee-jerk is "can we avoid having equivalent-but-not-equal offsets?" What is the use case where you really need to distinguish between QS-FEB vs QS-NOV? Would it be onerous to have only one of these?

@rwijtvliet
Copy link
Author

rwijtvliet commented Mar 24, 2025

To react to your point 2.:

One advantage of the distinction is e.g. business years starting in e.g. November. Aggregating to years, we need to use "YS-NOV". Aggregating to quarters can currently be done with "QS-NOV", which is more intuitive than having to use "QS-FEB".

However, I agree with you and think the disadvantages outweigh this advantage. And the current implementation is unreliable anyway:

i = pd.date_range('2025-02', freq='QS-MAY', periods=3)
i.inferred_freq # 'QS-NOV' (!)

From where I'm standing, the best compromise is to have 3 main QS-frequencies (QS-JAN, -FEB, -MAR), and consider the others as aliases.

  • Meaning: whenever a frequency object is created, always one of the 3 "main" quarter-frequencies is used/stored.
  • And with the aliases: comparing the DateOffset <QuarterBegin: startingMonth=2>, to "QS-NOV" would still evaluate to True.
  • And also, in my business years example above, one could still use 'QS-NOV' when aggregating. The resulting index would have frequency "QS-FEB", though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Datetime Datetime data dtype Frequency DateOffsets
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants