Skip to content

Commit efabfc8

Browse files
datapythonistajreback
authored andcommitted
BUG: Fixed exception when Series.str.get is used with dict values and the index is not an existing key (#20671) (#20672)
1 parent 545d2de commit efabfc8

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

doc/source/whatsnew/v0.23.0.txt

+4
Original file line numberDiff line numberDiff line change
@@ -1098,6 +1098,10 @@ Numeric
10981098
- Multiplication and division of numeric-dtyped :class:`Index` objects with timedelta-like scalars returns ``TimedeltaIndex`` instead of raising ``TypeError`` (:issue:`19333`)
10991099
- Bug where ``NaN`` was returned instead of 0 by :func:`Series.pct_change` and :func:`DataFrame.pct_change` when ``fill_method`` is not ``None`` (:issue:`19873`)
11001100

1101+
Strings
1102+
^^^^^^^
1103+
- Bug in :func:`Series.str.get` with a dictionary in the values and the index not in the keys, raising `KeyError` (:issue:`20671`)
1104+
11011105

11021106
Indexing
11031107
^^^^^^^^

pandas/core/strings.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1679,7 +1679,12 @@ def str_get(arr, i):
16791679
-------
16801680
items : Series/Index of objects
16811681
"""
1682-
f = lambda x: x[i] if len(x) > i >= -len(x) else np.nan
1682+
def f(x):
1683+
if isinstance(x, dict):
1684+
return x.get(i)
1685+
elif len(x) > i >= -len(x):
1686+
return x[i]
1687+
return np.nan
16831688
return _na_map(f, arr)
16841689

16851690

pandas/tests/test_strings.py

+25
Original file line numberDiff line numberDiff line change
@@ -2568,6 +2568,31 @@ def test_get(self):
25682568
expected = Series(['3', '8', np.nan])
25692569
tm.assert_series_equal(result, expected)
25702570

2571+
def test_get_complex(self):
2572+
# GH 20671, getting value not in dict raising `KeyError`
2573+
values = Series([(1, 2, 3), [1, 2, 3], {1, 2, 3},
2574+
{1: 'a', 2: 'b', 3: 'c'}])
2575+
2576+
result = values.str.get(1)
2577+
expected = Series([2, 2, np.nan, 'a'])
2578+
tm.assert_series_equal(result, expected)
2579+
2580+
result = values.str.get(-1)
2581+
expected = Series([3, 3, np.nan, np.nan])
2582+
tm.assert_series_equal(result, expected)
2583+
2584+
@pytest.mark.parametrize('to_type', [tuple, list, np.array])
2585+
def test_get_complex_nested(self, to_type):
2586+
values = Series([to_type([to_type([1, 2])])])
2587+
2588+
result = values.str.get(0)
2589+
expected = Series([to_type([1, 2])])
2590+
tm.assert_series_equal(result, expected)
2591+
2592+
result = values.str.get(1)
2593+
expected = Series([np.nan])
2594+
tm.assert_series_equal(result, expected)
2595+
25712596
def test_more_contains(self):
25722597
# PR #1179
25732598
s = Series(['A', 'B', 'C', 'Aaba', 'Baca', '', NA,

0 commit comments

Comments
 (0)