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: df.resample('MS', closed='right') incorrectly places bins #55278

Closed
Show file tree
Hide file tree
Changes from all 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
11 changes: 2 additions & 9 deletions pandas/_libs/tslibs/dtypes.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -189,13 +189,8 @@ OFFSET_TO_PERIOD_FREQSTR: dict = {
"WEEKDAY": "D",
"EOM": "M",
"BM": "M",
"BQS": "Q",
"QS": "Q",
Comment on lines -192 to -193
Copy link
Member Author

Choose a reason for hiding this comment

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

I find it odd that these "*start" offsets are here to begin with, as they don't have an associated Period:

In [22]: MonthEnd()._period_dtype_code
Out[22]: 3000

In [23]: MonthBegin()._period_dtype_code
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[23], line 1
----> 1 MonthBegin()._period_dtype_code

AttributeError: 'pandas._libs.tslibs.offsets.MonthBegin' object has no attribute '_period_dtype_code'

So, trying this - let's see what fails

Copy link
Member Author

Choose a reason for hiding this comment

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

nvm, this stuff is explicitly tested for...

@pytest.mark.parametrize("off", ["BQ", "QS", "BQS"])
def test_to_period_quarterlyish(self, off):
rng = date_range("01-Jan-2012", periods=8, freq=off)
prng = rng.to_period()
assert prng.freq == "Q-DEC"
@pytest.mark.parametrize("off", ["BA", "AS", "BAS"])
def test_to_period_annualish(self, off):
rng = date_range("01-Jan-2012", periods=8, freq=off)
prng = rng.to_period()
assert prng.freq == "A-DEC"

"BQ": "Q",
"BA": "A",
"AS": "A",
"BAS": "A",
"MS": "M",
"D": "D",
"B": "B",
"min": "min",
Expand All @@ -210,18 +205,16 @@ OFFSET_TO_PERIOD_FREQSTR: dict = {
"ME": "M",
"Y": "A",
"BY": "A",
"YS": "A",
"BYS": "A",
}
cdef dict c_OFFSET_TO_PERIOD_FREQSTR = OFFSET_TO_PERIOD_FREQSTR

cpdef freq_to_period_freqstr(freq_n, freq_name):
if freq_n == 1:
freqstr = f"""{c_OFFSET_TO_PERIOD_FREQSTR.get(
freq_name, freq_name)}"""
freq_name, None)}"""
else:
freqstr = f"""{freq_n}{c_OFFSET_TO_PERIOD_FREQSTR.get(
freq_name, freq_name)}"""
freq_name, None)}"""
return freqstr

# Map deprecated resolution abbreviations to correct resolution abbreviations
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/resample/test_datetime_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -2051,3 +2051,16 @@ def test_resample_M_deprecated():
with tm.assert_produces_warning(UserWarning, match=depr_msg):
result = s.resample("2M").mean()
tm.assert_series_equal(result, expected)


def test_resample_ms_closed_right():
# https://github.com/pandas-dev/pandas/issues/55271
dti = date_range(start="2020-01-31", freq="1min", periods=6000)
df = DataFrame({"ts": dti}, index=dti)
grouped = df.resample("MS", closed="right")
result = grouped.last()
expected = DataFrame(
{"ts": [datetime(2020, 2, 1), datetime(2020, 2, 4, 3, 59)]},
index=DatetimeIndex([datetime(2020, 1, 1), datetime(2020, 2, 1)], freq="MS"),
)
tm.assert_frame_equal(result, expected)
16 changes: 5 additions & 11 deletions pandas/tseries/frequencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,6 @@
# ---------------------------------------------------------------------
# Offset related functions

_need_suffix = ["QS", "BQ", "BQS", "YS", "AS", "BY", "BA", "BYS", "BAS"]

for _prefix in _need_suffix:
for _m in MONTHS:
key = f"{_prefix}-{_m}"
OFFSET_TO_PERIOD_FREQSTR[key] = OFFSET_TO_PERIOD_FREQSTR[_prefix]

for _prefix in ["A", "Q"]:
for _m in MONTHS:
_alias = f"{_prefix}-{_m}"
Expand Down Expand Up @@ -502,10 +495,10 @@ def is_superperiod(source, target) -> bool:
-------
bool
"""
if target is None or source is None:
return False
source = _maybe_coerce_freq(source)
target = _maybe_coerce_freq(target)
if target is None or source is None:
return False

if _is_annual(source):
if _is_annual(target):
Expand Down Expand Up @@ -544,7 +537,7 @@ def is_superperiod(source, target) -> bool:
return False


def _maybe_coerce_freq(code) -> str:
def _maybe_coerce_freq(code) -> str | None:
"""we might need to coerce a code to a rule_code
and uppercase it

Expand All @@ -557,9 +550,10 @@ def _maybe_coerce_freq(code) -> str:
-------
str
"""
assert code is not None
if isinstance(code, DateOffset):
code = freq_to_period_freqstr(1, code.name)
if code is None:
return None
if code in {"min", "s", "ms", "us", "ns"}:
return code
else:
Expand Down
Loading