1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
|
from __future__ import annotations
from typing import Generic
from narwhals.typing import SeriesT
class SeriesStringNamespace(Generic[SeriesT]):
def __init__(self, series: SeriesT) -> None:
self._narwhals_series = series
def len_chars(self) -> SeriesT:
r"""Return the length of each string as the number of characters.
Returns:
A new Series containing the length of each string in characters.
Examples:
>>> import polars as pl
>>> import narwhals as nw
>>> s_native = pl.Series(["foo", "345", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.len_chars().to_native() # doctest: +NORMALIZE_WHITESPACE
shape: (3,)
Series: '' [u32]
[
3
3
null
]
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.len_chars()
)
def replace(
self, pattern: str, value: str, *, literal: bool = False, n: int = 1
) -> SeriesT:
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.
Returns:
A new Series with the regex/literal pattern replaced with the specified value.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["123abc", "abc abc123"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.replace("abc", "").to_native()
0 123
1 abc123
dtype: object
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.replace(
pattern, value, literal=literal, n=n
)
)
def replace_all(self, pattern: str, value: str, *, literal: bool = False) -> SeriesT:
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.
Returns:
A new Series with all occurrences of pattern replaced with the specified value.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["123abc", "abc abc123"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.replace_all("abc", "").to_native()
0 123
1 123
dtype: object
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.replace_all(
pattern, value, literal=literal
)
)
def strip_chars(self, characters: str | None = None) -> SeriesT:
r"""Remove leading and trailing characters.
Arguments:
characters: The set of characters to be removed. All combinations of this set of characters will be stripped from the start and end of the string. If set to None (default), all leading and trailing whitespace is removed instead.
Returns:
A new Series with leading and trailing characters removed.
Examples:
>>> import polars as pl
>>> import narwhals as nw
>>> s_native = pl.Series(["apple", "\nmango"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.strip_chars().to_native() # doctest: +NORMALIZE_WHITESPACE
shape: (2,)
Series: '' [str]
[
"apple"
"mango"
]
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.strip_chars(characters)
)
def starts_with(self, prefix: str) -> SeriesT:
r"""Check if string values start with a substring.
Arguments:
prefix: prefix substring
Returns:
A new Series with boolean values indicating if each string starts with the prefix.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["apple", "mango", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.starts_with("app").to_native()
0 True
1 False
2 None
dtype: object
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.starts_with(prefix)
)
def ends_with(self, suffix: str) -> SeriesT:
r"""Check if string values end with a substring.
Arguments:
suffix: suffix substring
Returns:
A new Series with boolean values indicating if each string ends with the suffix.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["apple", "mango", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.ends_with("ngo").to_native()
0 False
1 True
2 None
dtype: object
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.ends_with(suffix)
)
def contains(self, pattern: str, *, literal: bool = False) -> SeriesT:
r"""Check if string contains a substring that matches a pattern.
Arguments:
pattern: A Character sequence or valid regular expression pattern.
literal: If True, treats the pattern as a literal string.
If False, assumes the pattern is a regular expression.
Returns:
A new Series with boolean values indicating if each string contains the pattern.
Examples:
>>> import pyarrow as pa
>>> import narwhals as nw
>>> s_native = pa.chunked_array([["cat", "dog", "rabbit and parrot"]])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.contains("cat|parrot").to_native() # doctest: +ELLIPSIS
<pyarrow.lib.ChunkedArray object at ...>
[
[
true,
false,
true
]
]
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.contains(pattern, literal=literal)
)
def slice(self, offset: int, length: int | None = None) -> SeriesT:
r"""Create subslices of the string values of a Series.
Arguments:
offset: Start index. Negative indexing is supported.
length: Length of the slice. If set to `None` (default), the slice is taken to the
end of the string.
Returns:
A new Series containing subslices of each string.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["pear", None, "papaya"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.slice(4, 3).to_native() # doctest: +NORMALIZE_WHITESPACE
0
1 None
2 ya
dtype: object
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.slice(
offset=offset, length=length
)
)
def split(self, by: str) -> SeriesT:
r"""Split the string values of a Series by a substring.
Arguments:
by: Substring to split by.
Returns:
A new Series containing lists of strings.
Examples:
>>> import polars as pl
>>> import narwhals as nw
>>> s_native = pl.Series(["foo bar", "foo_bar"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.split("_").to_native() # doctest: +NORMALIZE_WHITESPACE
shape: (2,)
Series: '' [list[str]]
[
["foo bar"]
["foo", "bar"]
]
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.split(by=by)
)
def head(self, n: int = 5) -> SeriesT:
r"""Take the first n elements of each string.
Arguments:
n: Number of elements to take. Negative indexing is supported (see note (1.))
Returns:
A new Series containing the first n characters of each string.
Notes:
1. When the `n` input is negative, `head` returns characters up to the n-th from the end of the string.
For example, if `n = -3`, then all characters except the last three are returned.
2. If the length of the string has fewer than `n` characters, the full string is returned.
Examples:
>>> import pyarrow as pa
>>> import narwhals as nw
>>> s_native = pa.chunked_array([["taata", "taatatata", "zukkyun"]])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.head().to_native() # doctest: +ELLIPSIS
<pyarrow.lib.ChunkedArray object at ...>
[
[
"taata",
"taata",
"zukky"
]
]
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.slice(offset=0, length=n)
)
def tail(self, n: int = 5) -> SeriesT:
r"""Take the last n elements of each string.
Arguments:
n: Number of elements to take. Negative indexing is supported (see note (1.))
Returns:
A new Series containing the last n characters of each string.
Notes:
1. When the `n` input is negative, `tail` returns characters starting from the n-th from the beginning of
the string. For example, if `n = -3`, then all characters except the first three are returned.
2. If the length of the string has fewer than `n` characters, the full string is returned.
Examples:
>>> import pyarrow as pa
>>> import narwhals as nw
>>> s_native = pa.chunked_array([["taata", "taatatata", "zukkyun"]])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.tail().to_native() # doctest: +ELLIPSIS
<pyarrow.lib.ChunkedArray object at ...>
[
[
"taata",
"atata",
"kkyun"
]
]
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.slice(offset=-n, length=None)
)
def to_uppercase(self) -> SeriesT:
r"""Transform string to uppercase variant.
Returns:
A new Series with values converted to uppercase.
Notes:
The PyArrow backend will convert 'ß' to 'ẞ' instead of 'SS'.
For more info see: https://github.com/apache/arrow/issues/34599
There may be other unicode-edge-case-related variations across implementations.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["apple", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.to_uppercase().to_native()
0 APPLE
1 None
dtype: object
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.to_uppercase()
)
def to_lowercase(self) -> SeriesT:
r"""Transform string to lowercase variant.
Returns:
A new Series with values converted to lowercase.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["APPLE", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.to_lowercase().to_native()
0 apple
1 None
dtype: object
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.to_lowercase()
)
def to_datetime(self, format: str | None = None) -> SeriesT:
"""Parse Series with strings to a Series with Datetime dtype.
Notes:
- pandas defaults to nanosecond time unit, Polars to microsecond.
Prior to pandas 2.0, nanoseconds were the only time unit supported
in pandas, with no ability to set any other one. The ability to
set the time unit in pandas, if the version permits, will arrive.
- timezone-aware strings are all converted to and parsed as UTC.
Warning:
As different backends auto-infer format in different ways, if `format=None`
there is no guarantee that the result will be equal.
Arguments:
format: Format to use for conversion. If set to None (default), the format is
inferred from the data.
Returns:
A new Series with datetime dtype.
Examples:
>>> import polars as pl
>>> import narwhals as nw
>>> s_native = pl.Series(["2020-01-01", "2020-01-02"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.to_datetime(
... format="%Y-%m-%d"
... ).to_native() # doctest: +NORMALIZE_WHITESPACE
shape: (2,)
Series: '' [datetime[μs]]
[
2020-01-01 00:00:00
2020-01-02 00:00:00
]
"""
return self._narwhals_series._with_compliant(
self._narwhals_series._compliant_series.str.to_datetime(format=format)
)
|