Skip to content

REF: avoid try/except in _gotitem #51311

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
Feb 13, 2023
Merged
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
22 changes: 16 additions & 6 deletions pandas/core/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,15 +394,18 @@ def _gotitem(self, key, ndim: int, subset=None):
grouper = self.grouper
if subset is None:
subset = self.obj
if key is not None:
subset = subset[key]
else:
# reached via Apply.agg_dict_like with selection=None and ndim=1
assert subset.ndim == 1
if ndim == 1:
assert subset.ndim == 1

grouped = get_groupby(
subset, by=None, grouper=grouper, axis=self.axis, group_keys=self.group_keys
)

# try the key selection
try:
return grouped[key]
except KeyError:
return grouped
return grouped

def _groupby_and_aggregate(self, how, *args, **kwargs):
"""
Expand Down Expand Up @@ -1214,6 +1217,11 @@ def _gotitem(self, key, ndim, subset=None):
# create a new object to prevent aliasing
if subset is None:
subset = self.obj
if key is not None:
subset = subset[key]
else:
# reached via Apply.agg_dict_like with selection=None, ndim=1
assert subset.ndim == 1

# Try to select from a DataFrame, falling back to a Series
try:
Expand All @@ -1228,6 +1236,8 @@ def _gotitem(self, key, ndim, subset=None):
(lib.is_scalar(key) and key in subset) or lib.is_list_like(key)
):
selection = key
elif subset.ndim == 1 and lib.is_scalar(key) and key == subset.name:
selection = key

new_rs = type(self)(
groupby=groupby,
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/window/rolling.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,8 @@ def _gotitem(self, key, ndim, subset=None):
(is_scalar(key) and key in subset) or is_list_like(key)
):
selection = key
elif subset.ndim == 1 and is_scalar(key) and key == subset.name:
selection = key

new_win = type(self)(subset, selection=selection, **kwargs)
return new_win
Expand Down