Skip to content
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

feat: add str.replace and str.replace_all #750

Merged
merged 16 commits into from
Aug 12, 2024
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
2 changes: 2 additions & 0 deletions docs/api-reference/expr_str.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
- ends_with
- head
- slice
- replace
- replace_all
- starts_with
- strip_chars
- tail
Expand Down
2 changes: 2 additions & 0 deletions docs/api-reference/series_str.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
- contains
- ends_with
- head
- replace
- replace_all
- slice
- starts_with
- strip_chars
Expand Down
34 changes: 34 additions & 0 deletions narwhals/_arrow/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,40 @@ class ArrowExprStringNamespace:
def __init__(self, expr: ArrowExpr) -> None:
self._expr = expr

def replace(
self,
pattern: str,
value: str,
*,
literal: bool = False,
n: int = 1,
) -> ArrowExpr:
return reuse_series_namespace_implementation(
self._expr,
"str",
"replace",
pattern,
value,
literal=literal,
n=n,
)

def replace_all(
self,
pattern: str,
value: str,
*,
literal: bool = False,
) -> ArrowExpr:
return reuse_series_namespace_implementation(
self._expr,
"str",
"replace_all",
pattern,
value,
literal=literal,
)

def strip_chars(self, characters: str | None = None) -> ArrowExpr:
return reuse_series_namespace_implementation(
self._expr,
Expand Down
19 changes: 19 additions & 0 deletions narwhals/_arrow/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,25 @@ class ArrowSeriesStringNamespace:
def __init__(self: Self, series: ArrowSeries) -> None:
self._arrow_series = series

def replace(
self, pattern: str, value: str, *, literal: bool = False, n: int = 1
) -> ArrowSeries:
pc = get_pyarrow_compute()
method = "replace_substring" if literal else "replace_substring_regex"
return self._arrow_series._from_native_series(
getattr(pc, method)(
self._arrow_series._native_series,
pattern=pattern,
replacement=value,
max_replacements=n,
)
)

def replace_all(
self, pattern: str, value: str, *, literal: bool = False
) -> ArrowSeries:
return self.replace(pattern, value, literal=literal, n=-1)

def strip_chars(self: Self, characters: str | None = None) -> ArrowSeries:
pc = get_pyarrow_compute()
whitespace = " \t\n\r\v\f"
Expand Down
38 changes: 38 additions & 0 deletions narwhals/_dask/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,44 @@ class DaskExprStringNamespace:
def __init__(self, expr: DaskExpr) -> None:
self._expr = expr

def replace(
self,
pattern: str,
value: str,
*,
literal: bool = False,
n: int = 1,
) -> DaskExpr:
return self._expr._from_call(
lambda _input, _pattern, _value, _literal, _n: _input.str.replace(
_pattern, _value, regex=not _literal, n=_n
),
"replace",
pattern,
value,
literal,
n,
returns_scalar=False,
)

def replace_all(
self,
pattern: str,
value: str,
*,
literal: bool = False,
) -> DaskExpr:
return self._expr._from_call(
lambda _input, _pattern, _value, _literal: _input.str.replace(
_pattern, _value, n=-1, regex=not _literal
),
"replace",
pattern,
value,
literal,
returns_scalar=False,
)

def strip_chars(self, characters: str | None = None) -> DaskExpr:
return self._expr._from_call(
lambda _input, characters: _input.str.strip(characters),
Expand Down
23 changes: 23 additions & 0 deletions narwhals/_pandas_like/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,29 @@ class PandasLikeExprStringNamespace:
def __init__(self, expr: PandasLikeExpr) -> None:
self._expr = expr

def replace(
self,
pattern: str,
value: str,
*,
literal: bool = False,
n: int = 1,
) -> PandasLikeExpr:
return reuse_series_namespace_implementation(
self._expr, "str", "replace", pattern, value, literal=literal, n=n
)

def replace_all(
self,
pattern: str,
value: str,
*,
literal: bool = False,
) -> PandasLikeExpr:
return reuse_series_namespace_implementation(
self._expr, "str", "replace_all", pattern, value, literal=literal
)

def strip_chars(self, characters: str | None = None) -> PandasLikeExpr:
return reuse_series_namespace_implementation(
self._expr,
Expand Down
14 changes: 14 additions & 0 deletions narwhals/_pandas_like/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,20 @@ class PandasLikeSeriesStringNamespace:
def __init__(self, series: PandasLikeSeries) -> None:
self._pandas_series = series

def replace(
self, pattern: str, value: str, *, literal: bool = False, n: int = 1
) -> PandasLikeSeries:
return self._pandas_series._from_native_series(
self._pandas_series._native_series.str.replace(
pat=pattern, repl=value, n=n, regex=not literal
),
)

def replace_all(
self, pattern: str, value: str, *, literal: bool = False
) -> PandasLikeSeries:
return self.replace(pattern, value, literal=literal, n=-1)

def strip_chars(self, characters: str | None) -> PandasLikeSeries:
return self._pandas_series._from_native_series(
self._pandas_series._native_series.str.strip(characters),
Expand Down
81 changes: 81 additions & 0 deletions narwhals/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -1949,6 +1949,87 @@ class ExprStringNamespace:
def __init__(self, expr: Expr) -> None:
self._expr = expr

def replace(
self, pattern: str, value: str, *, literal: bool = False, n: int = 1
) -> Expr:
r"""
Replace first matching regex/literal substring with a new string value.

Arguments:
pattern: A valid regular expression pattern.
value: String that will replace the matched substring.
literal: Treat `pattern` as a literal string.
n: Number of matches to replace.

Examples:
>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> data = {"foo": ["123abc", "abc abc123"]}
>>> df_pd = pd.DataFrame(data)
>>> df_pl = pl.DataFrame(data)

We define a dataframe-agnostic function:

>>> @nw.narwhalify
... def func(df):
... df = df.with_columns(replaced=nw.col("foo").str.replace("abc", ""))
... return df.to_dict(as_series=False)

We can then pass either pandas or Polars to `func`:

>>> func(df_pd)
{'foo': ['123abc', 'abc abc123'], 'replaced': ['123', ' abc123']}

>>> func(df_pl)
{'foo': ['123abc', 'abc abc123'], 'replaced': ['123', ' abc123']}

"""
return self._expr.__class__(
lambda plx: self._expr._call(plx).str.replace(
pattern, value, literal=literal, n=n
)
)

def replace_all(self, pattern: str, value: str, *, literal: bool = False) -> Expr:
r"""
Replace all matching regex/literal substring with a new string value.

Arguments:
pattern: A valid regular expression pattern.
value: String that will replace the matched substring.
literal: Treat `pattern` as a literal string.

Examples:
>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> data = {"foo": ["123abc", "abc abc123"]}
>>> df_pd = pd.DataFrame(data)
>>> df_pl = pl.DataFrame(data)

We define a dataframe-agnostic function:

>>> @nw.narwhalify
... def func(df):
... df = df.with_columns(replaced=nw.col("foo").str.replace_all("abc", ""))
... return df.to_dict(as_series=False)

We can then pass either pandas or Polars to `func`:

>>> func(df_pd)
{'foo': ['123abc', 'abc abc123'], 'replaced': ['123', ' 123']}

>>> func(df_pl)
{'foo': ['123abc', 'abc abc123'], 'replaced': ['123', ' 123']}

"""
return self._expr.__class__(
lambda plx: self._expr._call(plx).str.replace_all(
pattern, value, literal=literal
)
)

def strip_chars(self, characters: str | None = None) -> Expr:
r"""
Remove leading and trailing characters.
Expand Down
79 changes: 79 additions & 0 deletions narwhals/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -2249,6 +2249,85 @@ class SeriesStringNamespace:
def __init__(self, series: Series) -> None:
self._narwhals_series = series

def replace(
self, pattern: str, value: str, *, literal: bool = False, n: int = 1
) -> Series:
r"""
Replace first matching regex/literal substring with a new string value.

Arguments:
pattern: A valid regular expression pattern.
value: String that will replace the matched substring.
literal: Treat `pattern` as a literal string.
n: Number of matches to replace.

Examples:
>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> data = ["123abc", "abc abc123"]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> @nw.narwhalify
... def func(s):
... s = s.str.replace("abc", "")
... return s.to_list()

We can then pass either pandas or Polars to `func`:

>>> func(s_pd)
['123', ' abc123']

>>> func(s_pl)
['123', ' abc123']
"""
return self._narwhals_series._from_compliant_series(
self._narwhals_series._compliant_series.str.replace(
pattern, value, literal=literal, n=n
)
)

def replace_all(self, pattern: str, value: str, *, literal: bool = False) -> Series:
r"""
Replace all matching regex/literal substring with a new string value.

Arguments:
pattern: A valid regular expression pattern.
value: String that will replace the matched substring.
literal: Treat `pattern` as a literal string.

Examples:
>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> data = ["123abc", "abc abc123"]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> @nw.narwhalify
... def func(s):
... s = s.str.replace_all("abc", "")
... return s.to_list()

We can then pass either pandas or Polars to `func`:

>>> func(s_pd)
['123', ' 123']

>>> func(s_pl)
['123', ' 123']
"""
return self._narwhals_series._from_compliant_series(
self._narwhals_series._compliant_series.str.replace_all(
pattern, value, literal=literal
)
)

def strip_chars(self, characters: str | None = None) -> Series:
r"""
Remove leading and trailing characters.
Expand Down
Loading
Loading