diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index ea08a0a6fe07b..82bfe526cf161 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -86,7 +86,7 @@ Other API Changes - :class:`DatetimeTZDtype` will now standardize pytz timezones to a common timezone instance (:issue:`24713`) - ``Timestamp`` and ``Timedelta`` scalars now implement the :meth:`to_numpy` method as aliases to :meth:`Timestamp.to_datetime64` and :meth:`Timedelta.to_timedelta64`, respectively. (:issue:`24653`) - :meth:`Timestamp.strptime` will now rise a ``NotImplementedError`` (:issue:`25016`) -- +- Bug in :meth:`DatetimeIndex.snap` which didn't preserving the ``name`` of the input :class:`Index` (:issue:`25575`) .. _whatsnew_0250.deprecations: diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index b8d052ce7be04..b65e59a3d58b7 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -787,8 +787,8 @@ def snap(self, freq='S'): snapped[i] = s # we know it conforms; skip check - return DatetimeIndex._simple_new(snapped, freq=freq) - # TODO: what about self.name? tz? if so, use shallow_copy? + return DatetimeIndex._simple_new(snapped, name=self.name, tz=self.tz, + freq=freq) def join(self, other, how='left', level=None, return_indexers=False, sort=False): diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index 0efc9feb0dbd4..8e4c7d9b17efc 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -52,20 +52,28 @@ def test_fancy_setitem(): assert (s[48:54] == -3).all() -def test_dti_snap(): +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +@pytest.mark.parametrize('tz', [None, 'Asia/Shanghai', 'Europe/Berlin']) +@pytest.mark.parametrize('name', [None, 'my_dti']) +def test_dti_snap(name, tz): dti = DatetimeIndex(['1/1/2002', '1/2/2002', '1/3/2002', '1/4/2002', - '1/5/2002', '1/6/2002', '1/7/2002'], freq='D') + '1/5/2002', '1/6/2002', '1/7/2002'], + name=name, tz=tz, freq='D') - res = dti.snap(freq='W-MON') - exp = date_range('12/31/2001', '1/7/2002', freq='w-mon') - exp = exp.repeat([3, 4]) - assert (res == exp).all() + result = dti.snap(freq='W-MON') + expected = date_range('12/31/2001', '1/7/2002', + name=name, tz=tz, freq='w-mon') + expected = expected.repeat([3, 4]) + tm.assert_index_equal(result, expected) + assert result.tz == expected.tz - res = dti.snap(freq='B') + result = dti.snap(freq='B') - exp = date_range('1/1/2002', '1/7/2002', freq='b') - exp = exp.repeat([1, 1, 1, 2, 2]) - assert (res == exp).all() + expected = date_range('1/1/2002', '1/7/2002', + name=name, tz=tz, freq='b') + expected = expected.repeat([1, 1, 1, 2, 2]) + tm.assert_index_equal(result, expected) + assert result.tz == expected.tz def test_dti_reset_index_round_trip():