Skip to content

Commit a448b97

Browse files
authored
REF: Simplify __getitem__ by doing positional-int check first (#33471)
1 parent c6c5367 commit a448b97

File tree

1 file changed

+22
-19
lines changed

1 file changed

+22
-19
lines changed

pandas/core/series.py

+22-19
Original file line numberDiff line numberDiff line change
@@ -881,32 +881,35 @@ def __getitem__(self, key):
881881
if isinstance(key, (list, tuple)):
882882
key = unpack_1tuple(key)
883883

884-
if key_is_scalar or isinstance(self.index, MultiIndex):
884+
if is_integer(key) and self.index._should_fallback_to_positional():
885+
return self._values[key]
886+
887+
elif key_is_scalar:
888+
return self._get_value(key)
889+
890+
if (
891+
isinstance(key, tuple)
892+
and is_hashable(key)
893+
and isinstance(self.index, MultiIndex)
894+
):
885895
# Otherwise index.get_value will raise InvalidIndexError
886896
try:
887-
result = self.index.get_value(self, key)
897+
result = self._get_value(key)
888898

889899
return result
890-
except InvalidIndexError:
891-
if not isinstance(self.index, MultiIndex):
892-
raise
893900

894-
except (KeyError, ValueError):
895-
if isinstance(key, tuple) and isinstance(self.index, MultiIndex):
896-
# kludge
897-
pass
898-
else:
899-
raise
901+
except KeyError:
902+
# We still have the corner case where this tuple is a key
903+
# in the first level of our MultiIndex
904+
return self._get_values_tuple(key)
900905

901-
if not key_is_scalar:
902-
# avoid expensive checks if we know we have a scalar
903-
if is_iterator(key):
904-
key = list(key)
906+
if is_iterator(key):
907+
key = list(key)
905908

906-
if com.is_bool_indexer(key):
907-
key = check_bool_indexer(self.index, key)
908-
key = np.asarray(key, dtype=bool)
909-
return self._get_values(key)
909+
if com.is_bool_indexer(key):
910+
key = check_bool_indexer(self.index, key)
911+
key = np.asarray(key, dtype=bool)
912+
return self._get_values(key)
910913

911914
return self._get_with(key)
912915

0 commit comments

Comments
 (0)