Skip to content

CLN: MultiIndex.get_value is a hive of scum and villainy #31662

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 14 commits into from
Feb 5, 2020
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
63 changes: 15 additions & 48 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import datetime
from sys import getsizeof
from typing import Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union
import warnings
Expand All @@ -7,7 +6,7 @@

from pandas._config import get_option

from pandas._libs import Timestamp, algos as libalgos, index as libindex, lib, tslibs
from pandas._libs import algos as libalgos, index as libindex, lib
from pandas._libs.hashtable import duplicated_int64
from pandas._typing import AnyArrayLike, ArrayLike, Scalar
from pandas.compat.numpy import function as nv
Expand Down Expand Up @@ -2321,65 +2320,33 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):

def get_value(self, series, key):
# Label-based
s = com.values_from_object(series)
k = com.values_from_object(key)
if not is_hashable(key) or is_iterator(key):
# We allow tuples if they are hashable, whereas other Index
# subclasses require scalar.
# We have to explicitly exclude generators, as these are hashable.
raise InvalidIndexError(key)

def _try_mi(k):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should think about making try_mi non-nested (just for cleanliness), give it a better name and type in the future.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yah there's plenty more to do here, but this is a big step

# TODO: what if a level contains tuples??
loc = self.get_loc(k)

new_values = series._values[loc]
if is_scalar(loc):
return new_values

new_index = self[loc]
new_index = maybe_droplevels(new_index, k)
return series._constructor(
new_values, index=new_index, name=series.name
).__finalize__(self)

try:
return self._engine.get_value(s, k)
except KeyError as e1:
try:
return _try_mi(key)
except KeyError:
pass

try:
return libindex.get_value_at(s, k)
except IndexError:
return _try_mi(key)
except KeyError:
if is_integer(key):
return series._values[key]
else:
raise
except TypeError:
# generator/iterator-like
if is_iterator(key):
raise InvalidIndexError(key)
else:
raise e1
except Exception: # pragma: no cover
raise e1
except TypeError:

# a Timestamp will raise a TypeError in a multi-index
# rather than a KeyError, try it here
# note that a string that 'looks' like a Timestamp will raise
# a KeyError! (GH5725)
if isinstance(key, (datetime.datetime, np.datetime64, str)):
try:
return _try_mi(key)
except KeyError:
raise
except (IndexError, ValueError, TypeError):
pass

try:
return _try_mi(Timestamp(key))
except (
KeyError,
TypeError,
IndexError,
ValueError,
tslibs.OutOfBoundsDatetime,
):
pass

raise InvalidIndexError(key)

def _convert_listlike_indexer(self, keyarr, kind=None):
"""
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexing/multiindex/test_getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ def test_series_getitem_returns_scalar(
(lambda s: s[(2000, 3, 4)], KeyError, r"^\(2000, 3, 4\)$"),
(lambda s: s.loc[(2000, 3, 4)], KeyError, r"^\(2000, 3, 4\)$"),
(lambda s: s.loc[(2000, 3, 4, 5)], IndexingError, "Too many indexers"),
(lambda s: s.__getitem__(len(s)), IndexError, "index out of bounds"),
(lambda s: s[len(s)], IndexError, "index out of bounds"),
(lambda s: s.__getitem__(len(s)), IndexError, "is out of bounds"),
(lambda s: s[len(s)], IndexError, "is out of bounds"),
(
lambda s: s.iloc[len(s)],
IndexError,
Expand Down