Skip to content

Commit e978279

Browse files
Dr-Irvjreback
authored andcommitted
BUG: Fix Series.get() for ExtensionArray and Categorical (#20885)
1 parent 21ee836 commit e978279

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed

pandas/core/indexes/base.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -3082,12 +3082,17 @@ def get_value(self, series, key):
30823082
# use this, e.g. DatetimeIndex
30833083
s = getattr(series, '_values', None)
30843084
if isinstance(s, (ExtensionArray, Index)) and is_scalar(key):
3085+
# GH 20825
3086+
# Unify Index and ExtensionArray treatment
3087+
# First try to convert the key to a location
3088+
# If that fails, see if key is an integer, and
3089+
# try that
30853090
try:
3086-
return s[key]
3087-
except (IndexError, ValueError):
3088-
3089-
# invalid type as an indexer
3090-
pass
3091+
iloc = self.get_loc(key)
3092+
return s[iloc]
3093+
except KeyError:
3094+
if is_integer(key):
3095+
return s[key]
30913096

30923097
s = com._values_from_object(series)
30933098
k = com._values_from_object(key)

pandas/tests/extension/base/getitem.py

+30
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,36 @@ def test_getitem_slice(self, data):
117117
result = data[slice(1)] # scalar
118118
assert isinstance(result, type(data))
119119

120+
def test_get(self, data):
121+
# GH 20882
122+
s = pd.Series(data, index=[2 * i for i in range(len(data))])
123+
assert s.get(4) == s.iloc[2]
124+
125+
result = s.get([4, 6])
126+
expected = s.iloc[[2, 3]]
127+
self.assert_series_equal(result, expected)
128+
129+
result = s.get(slice(2))
130+
expected = s.iloc[[0, 1]]
131+
self.assert_series_equal(result, expected)
132+
133+
assert s.get(-1) == s.iloc[-1]
134+
assert s.get(s.index.max() + 1) is None
135+
136+
s = pd.Series(data[:6], index=list('abcdef'))
137+
assert s.get('c') == s.iloc[2]
138+
139+
result = s.get(slice('b', 'd'))
140+
expected = s.iloc[[1, 2, 3]]
141+
self.assert_series_equal(result, expected)
142+
143+
result = s.get('Z')
144+
assert result is None
145+
146+
assert s.get(4) == s.iloc[4]
147+
assert s.get(-1) == s.iloc[-1]
148+
assert s.get(len(s)) is None
149+
120150
def test_take_sequence(self, data):
121151
result = pd.Series(data)[[0, 1, 3]]
122152
assert result.iloc[0] == data[0]

0 commit comments

Comments
 (0)