Skip to content

BUG: Fixed exception when Series.str.get is used with dict values and the index is not an existing key (#20671) #20672

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 2 commits into from
Apr 24, 2018
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
4 changes: 4 additions & 0 deletions doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1053,6 +1053,10 @@ Numeric
- Bug in :meth:`Series.rank` and :meth:`DataFrame.rank` when ``ascending='False'`` failed to return correct ranks for infinity if ``NaN`` were present (:issue:`19538`)
- 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`)

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


Indexing
^^^^^^^^
Expand Down
7 changes: 6 additions & 1 deletion pandas/core/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -1663,7 +1663,12 @@ def str_get(arr, i):
-------
items : Series/Index of objects
"""
f = lambda x: x[i] if len(x) > i >= -len(x) else np.nan
def f(x):
if isinstance(x, dict):
return x.get(i)
elif len(x) > i >= -len(x):
return x[i]
return np.nan
return _na_map(f, arr)


Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2568,6 +2568,31 @@ def test_get(self):
expected = Series(['3', '8', np.nan])
tm.assert_series_equal(result, expected)

def test_get_complex(self):
# GH 20671, getting value not in dict raising `KeyError`
values = Series([(1, 2, 3), [1, 2, 3], {1, 2, 3},
{1: 'a', 2: 'b', 3: 'c'}])

result = values.str.get(1)
expected = Series([2, 2, np.nan, 'a'])
tm.assert_series_equal(result, expected)

result = values.str.get(-1)
expected = Series([3, 3, np.nan, np.nan])
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize('to_type', [tuple, list, np.array])
def test_get_complex_nested(self, to_type):
values = Series([to_type([to_type([1, 2])])])

result = values.str.get(0)
expected = Series([to_type([1, 2])])
tm.assert_series_equal(result, expected)

result = values.str.get(1)
expected = Series([np.nan])
tm.assert_series_equal(result, expected)

def test_more_contains(self):
# PR #1179
s = Series(['A', 'B', 'C', 'Aaba', 'Baca', '', NA,
Expand Down