diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index d50daad9a22b1..e7a564c8f3f90 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -996,15 +996,15 @@ def rpartition(self, sep=" ", expand=True): def get(self, i): """ - Extract element from each component at specified position. + Extract element from each component at specified position or with specified key. - Extract element from lists, tuples, or strings in each element in the + Extract element from lists, tuples, dict, or strings in each element in the Series/Index. Parameters ---------- - i : int - Position of element to extract. + i : int or hashable dict label + Position or key of element to extract. Returns ------- @@ -1044,6 +1044,15 @@ def get(self, i): 4 NaN 5 None dtype: object + + Return element with given key + + >>> s = pd.Series([{"name": "Hello", "value": "World"}, + ... {"name": "Goodbye", "value": "Planet"}]) + >>> s.str.get('name') + 0 Hello + 1 Goodbye + dtype: object """ result = self._data.array._str_get(i) return self._wrap_result(result) diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index 0e55676699c21..ffa8b557d2379 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -828,3 +828,20 @@ def test_zfill_with_leading_sign(): value = Series(["-cat", "-1", "+dog"]) expected = Series(["-0cat", "-0001", "+0dog"]) tm.assert_series_equal(value.str.zfill(5), expected) + + +def test_get_with_dict_label(): + # GH47911 + s = Series( + [ + {"name": "Hello", "value": "World"}, + {"name": "Goodbye", "value": "Planet"}, + {"value": "Sea"}, + ] + ) + result = s.str.get("name") + expected = Series(["Hello", "Goodbye", None]) + tm.assert_series_equal(result, expected) + result = s.str.get("value") + expected = Series(["World", "Planet", "Sea"]) + tm.assert_series_equal(result, expected)