Skip to content

implement .dt accessor for Index classes #18429

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
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.22.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Other API Changes
- `tseries.frequencies.get_freq_group()` and `tseries.frequencies.DAYS` are removed from the public API (:issue:`18034`)
- :func:`Series.truncate` and :func:`DataFrame.truncate` will raise a ``ValueError`` if the index is not sorted instead of an unhelpful ``KeyError`` (:issue:`17935`)
- :func:`Dataframe.unstack` will now default to filling with ``np.nan`` for ``object`` columns. (:issue:`12815`)

- :class:`Index` now has a `.dt` property that behaves like `Series.dt` (:issue:`17134`)

.. _whatsnew_0220.deprecations:

Expand Down
15 changes: 15 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1641,6 +1641,21 @@ def is_all_dates(self):
return False
return is_datetime_array(_ensure_object(self.values))

@property
def dt(self):
"""
For a datetime-like Index object, `self.dt` returns `self` so that
datetime-like attributes can be accessed symmetrically for Index
and Series objects.

For Index objects that are not datetime-like, `self.dt` will raise
an AttributeError.
"""
# Non-raising versions of the `.dt` attribute are available in
# DatetimeIndex, PeriodIndex, and TimedeltaIndex.
raise AttributeError("Can only use .dt accessor with datetimelike "
"values")

def __reduce__(self):
d = dict(data=self._data)
d.update(self._get_attributes_dict())
Expand Down
5 changes: 5 additions & 0 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ def ceil(self, freq):
class DatetimeIndexOpsMixin(object):
""" common ops mixin to support a unified inteface datetimelike Index """

@property
@Appender(Index.dt.__doc__)
def dt(self):
return self

def equals(self, other):
"""
Determines if two Index objects contain the same elements.
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -1017,3 +1017,12 @@ def test_searchsorted_monotonic(self, indices):
# non-monotonic should raise.
with pytest.raises(ValueError):
indices._searchsorted_monotonic(value, side='left')

def test_dt_accessor(self):
# GH#17134
index = self.create_index()
if isinstance(index, (DatetimeIndex, TimedeltaIndex, PeriodIndex)):
assert index.dt is index
else:
with pytest.raises(AttributeError):
index.dt