Skip to content

Added an edge case handler and a test case for Series.first("#M") #52789

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

Closed
wants to merge 3 commits into from
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@ Styler

Other
^^^^^
- Bug in :func:`Series.first` ``first`` not returning all the timestamps of the last day of a month when parameter is month-based (:issue:`51285`)
- Bug in :func:`assert_almost_equal` now throwing assertion error for two unequal sets (:issue:`51727`)
- Bug in :meth:`Series.memory_usage` when ``deep=True`` throw an error with Series of objects and the returned value is incorrect, as it does not take into account GC corrections (:issue:`51858`)

Expand Down
12 changes: 12 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,10 @@
DataFrameRenderer,
)
from pandas.io.formats.printing import pprint_thing
from pandas.tseries.offsets import (
Day,
MonthEnd,
)

if TYPE_CHECKING:
from pandas._libs.tslibs import BaseOffset
Expand Down Expand Up @@ -9074,6 +9078,14 @@ def first(self, offset) -> Self:
end = self.index.searchsorted(end_date, side="left")
return self.iloc[:end]

# if original offset is "#M", MonthEnd only includes
# the first timestamp of the last day of the month
# however, first() should return the rest timestamps of the day as well
if isinstance(offset, MonthEnd):
end_date = end_date.date() + Day()
end = self.index.searchsorted(end_date, side="left")
return self.iloc[:end]

return self.loc[:end]

@final
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/frame/methods/test_first_and_last.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,15 @@ def test_empty_not_input(self, func):
result = getattr(df, func)(offset=1)
tm.assert_frame_equal(df, result)
assert df is not result

@pytest.mark.parametrize("start, periods, freq", [("2018-02-01", 3000, "1H")])
def test_first_with_offsets_in_month(self, frame_or_series, start, periods, freq):
# GH#51285
x = frame_or_series(
[1] * periods, index=bdate_range(start, periods=periods, freq=freq)
)
result = x.first("1M")
expected = frame_or_series(
[1] * 672, index=bdate_range(start, periods=672, freq=freq)
)
tm.assert_equal(result, expected)