Skip to content

Commit b8b647d

Browse files
authored
REF: avoid try/except in _gotitem (#51311)
1 parent aa2d98d commit b8b647d

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

pandas/core/resample.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -394,15 +394,18 @@ def _gotitem(self, key, ndim: int, subset=None):
394394
grouper = self.grouper
395395
if subset is None:
396396
subset = self.obj
397+
if key is not None:
398+
subset = subset[key]
399+
else:
400+
# reached via Apply.agg_dict_like with selection=None and ndim=1
401+
assert subset.ndim == 1
402+
if ndim == 1:
403+
assert subset.ndim == 1
404+
397405
grouped = get_groupby(
398406
subset, by=None, grouper=grouper, axis=self.axis, group_keys=self.group_keys
399407
)
400-
401-
# try the key selection
402-
try:
403-
return grouped[key]
404-
except KeyError:
405-
return grouped
408+
return grouped
406409

407410
def _groupby_and_aggregate(self, how, *args, **kwargs):
408411
"""
@@ -1214,6 +1217,11 @@ def _gotitem(self, key, ndim, subset=None):
12141217
# create a new object to prevent aliasing
12151218
if subset is None:
12161219
subset = self.obj
1220+
if key is not None:
1221+
subset = subset[key]
1222+
else:
1223+
# reached via Apply.agg_dict_like with selection=None, ndim=1
1224+
assert subset.ndim == 1
12171225

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

12321242
new_rs = type(self)(
12331243
groupby=groupby,

pandas/core/window/rolling.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,8 @@ def _gotitem(self, key, ndim, subset=None):
303303
(is_scalar(key) and key in subset) or is_list_like(key)
304304
):
305305
selection = key
306+
elif subset.ndim == 1 and is_scalar(key) and key == subset.name:
307+
selection = key
306308

307309
new_win = type(self)(subset, selection=selection, **kwargs)
308310
return new_win

0 commit comments

Comments
 (0)