Skip to content

CLN: simplify DTA.__getitem__ #33714

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

Merged
merged 1 commit into from
Apr 24, 2020
Merged
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
31 changes: 11 additions & 20 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,21 +527,6 @@ def __getitem__(self, key):
This getitem defers to the underlying array, which by-definition can
only handle list-likes, slices, and integer scalars
"""
is_int = lib.is_integer(key)
if lib.is_scalar(key) and not is_int:
raise IndexError(
"only integers, slices (`:`), ellipsis (`...`), "
"numpy.newaxis (`None`) and integer or boolean "
"arrays are valid indices"
)

getitem = self._data.__getitem__
if is_int:
val = getitem(key)
if lib.is_scalar(val):
# i.e. self.ndim == 1
return self._box_func(val)
return type(self)(val, dtype=self.dtype)

if com.is_bool_indexer(key):
# first convert to boolean, because check_array_indexer doesn't
Expand All @@ -558,6 +543,16 @@ def __getitem__(self, key):
else:
key = check_array_indexer(self, key)

freq = self._get_getitem_freq(key)
result = self._data[key]
if lib.is_scalar(result):
return self._box_func(result)
return self._simple_new(result, dtype=self.dtype, freq=freq)

def _get_getitem_freq(self, key):
"""
Find the `freq` attribute to assign to the result of a __getitem__ lookup.
"""
is_period = is_period_dtype(self.dtype)
if is_period:
freq = self.freq
Expand All @@ -572,11 +567,7 @@ def __getitem__(self, key):
# GH#21282 indexing with Ellipsis is similar to a full slice,
# should preserve `freq` attribute
freq = self.freq

result = getitem(key)
if lib.is_scalar(result):
return self._box_func(result)
return self._simple_new(result, dtype=self.dtype, freq=freq)
return freq

def __setitem__(
self,
Expand Down