Skip to content

Commit 045f0d0

Browse files
phoflluckyvs1
authored andcommitted
BUG: first("1M") returning two months when first day is last day of month (pandas-dev#38331)
1 parent 466b855 commit 045f0d0

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

doc/source/whatsnew/v1.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,7 @@ Datetimelike
606606
- Bug in :meth:`Series.isin` with ``datetime64[ns]`` dtype and :meth:`.DatetimeIndex.isin` failing to consider timezone-aware and timezone-naive datetimes as always different (:issue:`35728`)
607607
- Bug in :meth:`Series.isin` with ``PeriodDtype`` dtype and :meth:`PeriodIndex.isin` failing to consider arguments with different ``PeriodDtype`` as always different (:issue:`37528`)
608608
- Bug in :class:`Period` constructor now correctly handles nanoseconds in the ``value`` argument (:issue:`34621` and :issue:`17053`)
609+
- Bug in :meth:`DataFrame.first` and :meth:`Series.first` returning two months for offset one month when first day is last calendar day (:issue:`29623`)
609610

610611
Timedelta
611612
^^^^^^^^^

pandas/core/generic.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -8420,7 +8420,11 @@ def first(self: FrameOrSeries, offset) -> FrameOrSeries:
84208420
return self
84218421

84228422
offset = to_offset(offset)
8423-
end_date = end = self.index[0] + offset
8423+
if not isinstance(offset, Tick) and offset.is_on_offset(self.index[0]):
8424+
# GH#29623 if first value is end of period
8425+
end_date = end = self.index[0]
8426+
else:
8427+
end_date = end = self.index[0] + offset
84248428

84258429
# Tick-like, e.g. 3 weeks
84268430
if isinstance(offset, Tick):

pandas/tests/frame/methods/test_first_and_last.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"""
44
import pytest
55

6-
from pandas import DataFrame
6+
from pandas import DataFrame, bdate_range
77
import pandas._testing as tm
88

99

@@ -69,3 +69,13 @@ def test_last_subset(self, frame_or_series):
6969

7070
result = ts[:0].last("3M")
7171
tm.assert_equal(result, ts[:0])
72+
73+
@pytest.mark.parametrize("start, periods", [("2010-03-31", 1), ("2010-03-30", 2)])
74+
def test_first_with_first_day_last_of_month(self, frame_or_series, start, periods):
75+
# GH#29623
76+
x = frame_or_series([1] * 100, index=bdate_range(start, periods=100))
77+
result = x.first("1M")
78+
expected = frame_or_series(
79+
[1] * periods, index=bdate_range(start, periods=periods)
80+
)
81+
tm.assert_equal(result, expected)

0 commit comments

Comments
 (0)