Skip to content

ENH: add str.removeprefix #39226

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

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from 15 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ Other enhancements
- :meth:`DataFrame.apply` can now accept non-callable DataFrame properties as strings, e.g. ``df.apply("size")``, which was already the case for :meth:`Series.apply` (:issue:`39116`)
- :meth:`Series.apply` can now accept list-like or dictionary-like arguments that aren't lists or dictionaries, e.g. ``ser.apply(np.array(["sum", "mean"]))``, which was already the case for :meth:`DataFrame.apply` (:issue:`39140`)
- :meth:`.Styler.set_tooltips` allows on hover tooltips to be added to styled HTML dataframes.
- Added :meth:`Series.str.removeprefix` to remove prefixes from string type Series, which has the same functionality as ``str.removeprefix`` from the Python standard library.

.. ---------------------------------------------------------------------------

Expand Down
8 changes: 8 additions & 0 deletions pandas/core/strings/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2885,6 +2885,14 @@ def casefold(self):
"isdecimal", docstring=_shared_docs["ismethods"] % _doc_args["isdecimal"]
)

@forbid_nonstring_types(["bytes"])
def removeprefix(self, prefix=None):
if not prefix:
return self._data
else:
result = self._data.array._str_removeprefix(prefix)
return self._wrap_result(result)


def cat_safe(list_of_columns: List, sep: str):
"""
Expand Down
4 changes: 4 additions & 0 deletions pandas/core/strings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,7 @@ def _str_split(self, pat=None, n=-1, expand=False):
@abc.abstractmethod
def _str_rsplit(self, pat=None, n=-1):
pass

@abc.abstractmethod
def _str_removeprefix(self, prefix=None):
pass
3 changes: 3 additions & 0 deletions pandas/core/strings/object_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,3 +430,6 @@ def _str_lstrip(self, to_strip=None):

def _str_rstrip(self, to_strip=None):
return self._str_map(lambda x: x.rstrip(to_strip))

def _str_removeprefix(self, prefix=None):
return self._str_map(lambda x: x.removeprefix(prefix))
30 changes: 28 additions & 2 deletions pandas/tests/test_strings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime, timedelta
import re
import sys

import numpy as np
import pytest
Expand Down Expand Up @@ -65,6 +66,7 @@ def assert_series_or_index_equal(left, right):
("translate", ({97: 100},), {}),
("wrap", (2,), {}),
("zfill", (10,), {}),
("removeprefix", ("a ",), {}),
] + list(
zip(
[
Expand Down Expand Up @@ -307,8 +309,18 @@ def test_api_for_categorical(self, any_string_method):

method_name, args, kwargs = any_string_method

result = getattr(c.str, method_name)(*args, **kwargs)
expected = getattr(s.str, method_name)(*args, **kwargs)
# we expect an AttributeError when str.removeprefix is tested on <= 3.9
if (
sys.version_info[0] <= 3
and sys.version_info[1] < 9
and method_name == "removeprefix"
):
with pytest.raises(AttributeError):
result = getattr(c.str, method_name)(*args, **kwargs)
expected = getattr(s.str, method_name)(*args, **kwargs)
else:
result = getattr(c.str, method_name)(*args, **kwargs)
expected = getattr(s.str, method_name)(*args, **kwargs)

if isinstance(result, DataFrame):
tm.assert_frame_equal(result, expected)
Expand Down Expand Up @@ -3678,3 +3690,17 @@ def test_str_accessor_in_apply_func():
expected = Series(["A/D", "B/E", "C/F"])
result = df.apply(lambda f: "/".join(f.str.upper()), axis=1)
tm.assert_series_equal(result, expected)


@pytest.mark.skipif(
sys.version_info[0] <= 3 and sys.version_info[1] < 9,
reason="Requires python 3.9 or greater",
)
def test_str_removeprefix():
# https://github.com/pandas-dev/pandas/issues/36944

df = DataFrame({"A": ["str_string1", "str_string2", "str_string3"]})
df["A"] = df["A"].str.removeprefix("str_")
result = DataFrame({"A": ["string1", "string2", "string3"]})

tm.assert_frame_equal(df, result)