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 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
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 @@ -59,6 +59,7 @@ Other enhancements
- :meth:`Series.loc.__getitem__` and :meth:`Series.loc.__setitem__` with :class:`MultiIndex` now raising helpful error message when indexer has too many dimensions (:issue:`35349`)
- :meth:`pandas.read_stata` and :class:`StataReader` support reading data from compressed files.
- Add support for parsing ``ISO 8601``-like timestamps with negative signs to :meth:`pandas.Timedelta` (:issue:`37172`)
- 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
38 changes: 38 additions & 0 deletions pandas/core/strings/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2881,6 +2881,44 @@ def casefold(self):
"isdecimal", docstring=_shared_docs["ismethods"] % _doc_args["isdecimal"]
)

@forbid_nonstring_types(["bytes"])
def removeprefix(self, prefix: str = None):
"""
Remove a defined prefix from an object series. If the prefix is not present,
the original string will be returned.

Parameters
----------
prefix: str, default None
Prefix to remove.

Returns
-------
Series/Index: object
The Series or Index with given prefix removed.

See also
--------
Series.str.strip : Remove leading and trailing characters.

Examples
--------
>>> s = pd.Series(["str_string1", "str_string2", "no_prefix"])
>>> s
0 str_string1
1 str_string2
2 no_prefix
dtype: object

>>> s.str.removeprefix("str_")
0 string1
1 string2
2 no_prefix
dtype: object
"""
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
8 changes: 8 additions & 0 deletions pandas/core/strings/object_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,3 +430,11 @@ 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):
f_startswith = lambda x: x.startswith(prefix)
f_slice = lambda x: x[len(prefix) :]
has_prefix = self._str_map(f_startswith, dtype="object")
sliced = self._str_map(f_slice, dtype="object")

return np.where(has_prefix, sliced, self)
1 change: 1 addition & 0 deletions pandas/tests/strings/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
("translate", ({97: 100},), {}),
("wrap", (2,), {}),
("zfill", (10,), {}),
("removeprefix", ("a ",), {}),
] + list(
zip(
[
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/strings/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -767,3 +767,15 @@ 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)


def test_str_removeprefix():
# https://github.com/pandas-dev/pandas/issues/36944

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

tm.assert_frame_equal(df, result)