Skip to content

REF/BUG: Index.get_value called incorrectly, de-duplicate+simplify #31134

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 3 commits into from
Jan 20, 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
59 changes: 25 additions & 34 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@
from pandas.core.arrays import ExtensionArray
from pandas.core.base import IndexOpsMixin, PandasObject
import pandas.core.common as com
from pandas.core.construction import extract_array
from pandas.core.indexers import maybe_convert_indices
from pandas.core.indexes.frozen import FrozenList
import pandas.core.missing as missing
Expand Down Expand Up @@ -4618,48 +4617,40 @@ def get_value(self, series, key):
# would convert to numpy arrays and raise later any way) - GH29926
raise InvalidIndexError(key)

# if we have something that is Index-like, then
# use this, e.g. DatetimeIndex
# Things like `Series._get_value` (via .at) pass the EA directly here.
s = extract_array(series, extract_numpy=True)
if isinstance(s, ExtensionArray):
try:
# GH 20882, 21257
# First try to convert the key to a location
# If that fails, raise a KeyError if an integer
# index, otherwise, see if key is an integer, and
# try that
try:
iloc = self.get_loc(key)
return s[iloc]
except KeyError:
if len(self) > 0 and (self.holds_integer() or self.is_boolean()):
raise
elif is_integer(key):
return s[key]

k = self._convert_scalar_indexer(key, kind="getitem")
try:
loc = self._engine.get_loc(k)

except KeyError as e1:
loc = self._engine.get_loc(key)
except KeyError:
if len(self) > 0 and (self.holds_integer() or self.is_boolean()):
raise

try:
return libindex.get_value_at(s, key)
except IndexError:
elif is_integer(key):
# If the Index cannot hold integer, then this is unambiguously
# a locational lookup.
loc = key
else:
raise
except Exception:
raise e1
except TypeError:
# e.g. "[False] is an invalid key"
raise IndexError(key)

else:
if is_scalar(loc):
tz = getattr(series.dtype, "tz", None)
return libindex.get_value_at(s, loc, tz=tz)
return series.iloc[loc]
return self._get_values_for_loc(series, loc)

def _get_values_for_loc(self, series, loc):
"""
Copy link
Contributor

Choose a reason for hiding this comment

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

add Paramters / Returns & typing as much as you can.

This likely duplicates some existing routines, no?

Copy link
Member Author

Choose a reason for hiding this comment

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

No, it de-duplicates code that we have I think in two places in Index.get_value and one each in DTI and TDI.

That said, this is one of the things we'll be able to simplify if/when we do the _values thing mentioned in #31037.

Will annotate in next pass

Do a positional lookup on the given Series, returning either a scalar
or a Series.

Assumes that `series.index is self`
"""
if is_integer(loc):
if isinstance(series._values, np.ndarray):
# Since we have an ndarray and not DatetimeArray, we dont
# have to worry about a tz.
return libindex.get_value_at(series._values, loc, tz=None)
return series._values[loc]

return series.iloc[loc]

def set_value(self, arr, key, value):
"""
Expand Down
5 changes: 2 additions & 3 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,9 +667,8 @@ def get_value(self, series, key):
return com.maybe_box(self, value, series, key)

def get_value_maybe_box(self, series, key):
key = self._maybe_cast_for_get_loc(key)
values = self._engine.get_value(com.values_from_object(series), key, tz=self.tz)
return com.maybe_box(self, values, series, key)
loc = self.get_loc(key)
return self._get_values_for_loc(series, loc)

def get_loc(self, key, method=None, tolerance=None):
"""
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,8 @@ def get_value(self, series, key):
return com.maybe_box(self, value, series, key)

def get_value_maybe_box(self, series, key: Timedelta):
values = self._engine.get_value(com.values_from_object(series), key)
return com.maybe_box(self, values, series, key)
loc = self.get_loc(key)
return self._get_values_for_loc(series, loc)

def get_loc(self, key, method=None, tolerance=None):
"""
Expand Down
12 changes: 8 additions & 4 deletions pandas/tests/indexes/datetimes/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -621,17 +621,21 @@ def test_get_value(self):
# specifically make sure we have test for np.datetime64 key
dti = pd.date_range("2016-01-01", periods=3)

arr = np.arange(6, 8)
arr = np.arange(6, 9)
ser = pd.Series(arr, index=dti)

key = dti[1]

result = dti.get_value(arr, key)
with pytest.raises(AttributeError, match="has no attribute '_values'"):
dti.get_value(arr, key)

result = dti.get_value(ser, key)
assert result == 7

result = dti.get_value(arr, key.to_pydatetime())
result = dti.get_value(ser, key.to_pydatetime())
assert result == 7

result = dti.get_value(arr, key.to_datetime64())
result = dti.get_value(ser, key.to_datetime64())
assert result == 7

def test_get_loc(self):
Expand Down
7 changes: 6 additions & 1 deletion pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1915,7 +1915,12 @@ def test_get_value(self, index):
values = np.random.randn(100)
value = index[67]

tm.assert_almost_equal(index.get_value(values, value), values[67])
with pytest.raises(AttributeError, match="has no attribute '_values'"):
# Index.get_value requires a Series, not an ndarray
index.get_value(values, value)

result = index.get_value(Series(values, index=values), value)
tm.assert_almost_equal(result, values[67])

@pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}])
@pytest.mark.parametrize(
Expand Down