/
string.py
2092 lines (1798 loc) · 60.5 KB
/
string.py
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from typing import TYPE_CHECKING
from polars._utils.deprecation import (
deprecate_renamed_function,
deprecate_renamed_parameter,
)
from polars.datatypes.constants import N_INFER_DEFAULT
from polars.series.utils import expr_dispatch
if TYPE_CHECKING:
from polars import Expr, Series
from polars.polars import PySeries
from polars.type_aliases import (
Ambiguous,
IntoExpr,
IntoExprColumn,
PolarsDataType,
PolarsTemporalType,
TimeUnit,
TransferEncoding,
)
@expr_dispatch
class StringNameSpace:
"""Series.str namespace."""
_accessor = "str"
def __init__(self, series: Series):
self._s: PySeries = series._s
def to_date(
self,
format: str | None = None,
*,
strict: bool = True,
exact: bool = True,
cache: bool = True,
) -> Series:
"""
Convert a String column into a Date column.
Parameters
----------
format
Format to use for conversion. Refer to the `chrono crate documentation
<https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
for the full specification. Example: `"%Y-%m-%d"`.
If set to None (default), the format is inferred from the data.
strict
Raise an error if any conversion fails.
exact
Require an exact format match. If False, allow the format to match anywhere
in the target string.
.. note::
Using `exact=False` introduces a performance penalty - cleaning your
data beforehand will almost certainly be more performant.
cache
Use a cache of unique, converted dates to apply the conversion.
Examples
--------
>>> s = pl.Series(["2020/01/01", "2020/02/01", "2020/03/01"])
>>> s.str.to_date()
shape: (3,)
Series: '' [date]
[
2020-01-01
2020-02-01
2020-03-01
]
"""
def to_datetime(
self,
format: str | None = None,
*,
time_unit: TimeUnit | None = None,
time_zone: str | None = None,
strict: bool = True,
exact: bool = True,
cache: bool = True,
utc: bool | None = None,
use_earliest: bool | None = None,
ambiguous: Ambiguous | Series = "raise",
) -> Series:
"""
Convert a String column into a Datetime column.
Parameters
----------
format
Format to use for conversion. Refer to the `chrono crate documentation
<https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
for the full specification. Example: `"%Y-%m-%d %H:%M:%S"`.
If set to None (default), the format is inferred from the data.
time_unit : {None, 'us', 'ns', 'ms'}
Unit of time for the resulting Datetime column. If set to None (default),
the time unit is inferred from the format string if given, eg:
`"%F %T%.3f"` => `Datetime("ms")`. If no fractional second component is
found, the default is `"us"`.
time_zone
Time zone for the resulting Datetime column.
strict
Raise an error if any conversion fails.
exact
Require an exact format match. If False, allow the format to match anywhere
in the target string.
.. note::
Using `exact=False` introduces a performance penalty - cleaning your
data beforehand will almost certainly be more performant.
cache
Use a cache of unique, converted datetimes to apply the conversion.
utc
Parse time zone aware datetimes as UTC. This may be useful if you have data
with mixed offsets.
.. deprecated:: 0.18.0
This is now a no-op, you can safely remove it.
Offset-naive strings are parsed as `pl.Datetime(time_unit)`,
and offset-aware strings are converted to
`pl.Datetime(time_unit, "UTC")`.
use_earliest
Determine how to deal with ambiguous datetimes:
- `None` (default): raise
- `True`: use the earliest datetime
- `False`: use the latest datetime
.. deprecated:: 0.19.0
Use `ambiguous` instead
ambiguous
Determine how to deal with ambiguous datetimes:
- `'raise'` (default): raise
- `'earliest'`: use the earliest datetime
- `'latest'`: use the latest datetime
- `'null'`: set to null
Examples
--------
>>> s = pl.Series(["2020-01-01 01:00Z", "2020-01-01 02:00Z"])
>>> s.str.to_datetime("%Y-%m-%d %H:%M%#z")
shape: (2,)
Series: '' [datetime[μs, UTC]]
[
2020-01-01 01:00:00 UTC
2020-01-01 02:00:00 UTC
]
"""
def to_time(
self,
format: str | None = None,
*,
strict: bool = True,
cache: bool = True,
) -> Series:
"""
Convert a String column into a Time column.
Parameters
----------
format
Format to use for conversion. Refer to the `chrono crate documentation
<https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
for the full specification. Example: `"%H:%M:%S"`.
If set to None (default), the format is inferred from the data.
strict
Raise an error if any conversion fails.
cache
Use a cache of unique, converted times to apply the conversion.
Examples
--------
>>> s = pl.Series(["01:00", "02:00", "03:00"])
>>> s.str.to_time("%H:%M")
shape: (3,)
Series: '' [time]
[
01:00:00
02:00:00
03:00:00
]
"""
def strptime(
self,
dtype: PolarsTemporalType,
format: str | None = None,
*,
strict: bool = True,
exact: bool = True,
cache: bool = True,
use_earliest: bool | None = None,
ambiguous: Ambiguous | Series = "raise",
) -> Series:
"""
Convert a String column into a Date/Datetime/Time column.
Parameters
----------
dtype
The data type to convert to. Can be either Date, Datetime, or Time.
format
Format to use for conversion. Refer to the `chrono crate documentation
<https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
for the full specification. Example: `"%Y-%m-%d %H:%M:%S"`.
If set to None (default), the format is inferred from the data.
strict
Raise an error if any conversion fails.
exact
Require an exact format match. If False, allow the format to match anywhere
in the target string. Conversion to the Time type is always exact.
.. note::
Using `exact=False` introduces a performance penalty - cleaning your
data beforehand will almost certainly be more performant.
cache
Use a cache of unique, converted dates to apply the datetime conversion.
use_earliest
Determine how to deal with ambiguous datetimes:
- `None` (default): raise
- `True`: use the earliest datetime
- `False`: use the latest datetime
.. deprecated:: 0.19.0
Use `ambiguous` instead
ambiguous
Determine how to deal with ambiguous datetimes:
- `'raise'` (default): raise
- `'earliest'`: use the earliest datetime
- `'latest'`: use the latest datetime
- `'null'`: set to null
Notes
-----
When converting to a Datetime type, the time unit is inferred from the format
string if given, eg: `"%F %T%.3f"` => `Datetime("ms")`. If no fractional
second component is found, the default is `"us"`.
Examples
--------
Dealing with a consistent format:
>>> s = pl.Series(["2020-01-01 01:00Z", "2020-01-01 02:00Z"])
>>> s.str.strptime(pl.Datetime, "%Y-%m-%d %H:%M%#z")
shape: (2,)
Series: '' [datetime[μs, UTC]]
[
2020-01-01 01:00:00 UTC
2020-01-01 02:00:00 UTC
]
Dealing with different formats.
>>> s = pl.Series(
... "date",
... [
... "2021-04-22",
... "2022-01-04 00:00:00",
... "01/31/22",
... "Sun Jul 8 00:34:60 2001",
... ],
... )
>>> s.to_frame().select(
... pl.coalesce(
... pl.col("date").str.strptime(pl.Date, "%F", strict=False),
... pl.col("date").str.strptime(pl.Date, "%F %T", strict=False),
... pl.col("date").str.strptime(pl.Date, "%D", strict=False),
... pl.col("date").str.strptime(pl.Date, "%c", strict=False),
... )
... ).to_series()
shape: (4,)
Series: 'date' [date]
[
2021-04-22
2022-01-04
2022-01-31
2001-07-08
]
"""
def to_decimal(
self,
inference_length: int = 100,
) -> Series:
"""
Convert a String column into a Decimal column.
This method infers the needed parameters `precision` and `scale`.
Parameters
----------
inference_length
Number of elements to parse to determine the `precision` and `scale`
Examples
--------
>>> s = pl.Series(
... ["40.12", "3420.13", "120134.19", "3212.98", "12.90", "143.09", "143.9"]
... )
>>> s.str.to_decimal()
shape: (7,)
Series: '' [decimal[*,2]]
[
40.12
3420.13
120134.19
3212.98
12.90
143.09
143.90
]
"""
def len_bytes(self) -> Series:
"""
Return the length of each string as the number of bytes.
Returns
-------
Series
Series of data type :class:`UInt32`.
See Also
--------
len_chars
Notes
-----
When working with non-ASCII text, the length in bytes is not the same as the
length in characters. You may want to use :func:`len_chars` instead.
Note that :func:`len_bytes` is much more performant (_O(1)_) than
:func:`len_chars` (_O(n)_).
Examples
--------
>>> s = pl.Series(["Café", "345", "東京", None])
>>> s.str.len_bytes()
shape: (4,)
Series: '' [u32]
[
5
3
6
null
]
"""
def len_chars(self) -> Series:
"""
Return the length of each string as the number of characters.
Returns
-------
Series
Series of data type :class:`UInt32`.
See Also
--------
len_bytes
Notes
-----
When working with ASCII text, use :func:`len_bytes` instead to achieve
equivalent output with much better performance:
:func:`len_bytes` runs in _O(1)_, while :func:`len_chars` runs in (_O(n)_).
A character is defined as a `Unicode scalar value`_. A single character is
represented by a single byte when working with ASCII text, and a maximum of
4 bytes otherwise.
.. _Unicode scalar value: https://www.unicode.org/glossary/#unicode_scalar_value
Examples
--------
>>> s = pl.Series(["Café", "345", "東京", None])
>>> s.str.len_chars()
shape: (4,)
Series: '' [u32]
[
4
3
2
null
]
"""
def concat(
self, delimiter: str | None = None, *, ignore_nulls: bool = True
) -> Series:
"""
Vertically concatenate the string values in the column to a single string value.
Parameters
----------
delimiter
The delimiter to insert between consecutive string values.
ignore_nulls
Ignore null values (default).
If set to `False`, null values will be propagated. This means that
if the column contains any null values, the output is null.
Returns
-------
Series
Series of data type :class:`String`.
Examples
--------
>>> pl.Series([1, None, 2]).str.concat("-")
shape: (1,)
Series: '' [str]
[
"1-2"
]
>>> pl.Series([1, None, 2]).str.concat("-", ignore_nulls=False)
shape: (1,)
Series: '' [str]
[
null
]
"""
def contains(
self, pattern: str | Expr, *, literal: bool = False, strict: bool = True
) -> Series:
"""
Check if strings in Series contain a substring that matches a regex.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
literal
Treat `pattern` as a literal string, not as a regular expression.
strict
Raise an error if the underlying pattern is not a valid regex,
otherwise mask out with a null value.
Notes
-----
To modify regular expression behaviour (such as case-sensitivity) with
flags, use the inline `(?iLmsuxU)` syntax. For example:
Default (case-sensitive) match:
>>> s = pl.Series("s", ["AAA", "aAa", "aaa"])
>>> s.str.contains("AA").to_list()
[True, False, False]
Case-insensitive match, using an inline flag:
>>> s = pl.Series("s", ["AAA", "aAa", "aaa"])
>>> s.str.contains("(?i)AA").to_list()
[True, True, True]
See the regex crate's section on `grouping and flags
<https://docs.rs/regex/latest/regex/#grouping-and-flags>`_ for
additional information about the use of inline expression modifiers.
Returns
-------
Series
Series of data type :class:`Boolean`.
Examples
--------
>>> s = pl.Series(["Crab", "cat and dog", "rab$bit", None])
>>> s.str.contains("cat|bit")
shape: (4,)
Series: '' [bool]
[
false
true
true
null
]
>>> s.str.contains("rab$", literal=True)
shape: (4,)
Series: '' [bool]
[
false
false
true
null
]
"""
def find(
self, pattern: str | Expr, *, literal: bool = False, strict: bool = True
) -> Expr:
"""
Return the index of the first substring in Series strings matching a pattern.
If the pattern is not found, returns None.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
literal
Treat `pattern` as a literal string, not as a regular expression.
strict
Raise an error if the underlying pattern is not a valid regex,
otherwise mask out with a null value.
Notes
-----
To modify regular expression behaviour (such as case-sensitivity) with
flags, use the inline `(?iLmsuxU)` syntax. For example:
>>> s = pl.Series("s", ["AAA", "aAa", "aaa"])
Default (case-sensitive) match:
>>> s.str.find("Aa").to_list()
[None, 1, None]
Case-insensitive match, using an inline flag:
>>> s.str.find("(?i)Aa").to_list()
[0, 0, 0]
See the regex crate's section on `grouping and flags
<https://docs.rs/regex/latest/regex/#grouping-and-flags>`_ for
additional information about the use of inline expression modifiers.
See Also
--------
contains : Check if string contains a substring that matches a regex.
Examples
--------
>>> s = pl.Series("txt", ["Crab", "Lobster", None, "Crustaceon"])
Find the index of the first substring matching a regex pattern:
>>> s.str.find("a|e").rename("idx_rx")
shape: (4,)
Series: 'idx_rx' [u32]
[
2
5
null
5
]
Find the index of the first substring matching a literal pattern:
>>> s.str.find("e", literal=True).rename("idx_lit")
shape: (4,)
Series: 'idx_lit' [u32]
[
null
5
null
7
]
Match against a pattern found in another column or (expression):
>>> p = pl.Series("pat", ["a[bc]", "b.t", "[aeiuo]", "(?i)A[BC]"])
>>> s.str.find(p).rename("idx")
shape: (4,)
Series: 'idx' [u32]
[
2
2
null
5
]
"""
def ends_with(self, suffix: str | Expr) -> Series:
"""
Check if string values end with a substring.
Parameters
----------
suffix
Suffix substring.
See Also
--------
contains : Check if string contains a substring that matches a regex.
starts_with : Check if string values start with a substring.
Examples
--------
>>> s = pl.Series("fruits", ["apple", "mango", None])
>>> s.str.ends_with("go")
shape: (3,)
Series: 'fruits' [bool]
[
false
true
null
]
"""
def starts_with(self, prefix: str | Expr) -> Series:
"""
Check if string values start with a substring.
Parameters
----------
prefix
Prefix substring.
See Also
--------
contains : Check if string contains a substring that matches a regex.
ends_with : Check if string values end with a substring.
Examples
--------
>>> s = pl.Series("fruits", ["apple", "mango", None])
>>> s.str.starts_with("app")
shape: (3,)
Series: 'fruits' [bool]
[
true
false
null
]
"""
def decode(self, encoding: TransferEncoding, *, strict: bool = True) -> Series:
r"""
Decode values using the provided encoding.
Parameters
----------
encoding : {'hex', 'base64'}
The encoding to use.
strict
Raise an error if the underlying value cannot be decoded,
otherwise mask out with a null value.
Returns
-------
Series
Series of data type :class:`Binary`.
Examples
--------
>>> s = pl.Series("color", ["000000", "ffff00", "0000ff"])
>>> s.str.decode("hex")
shape: (3,)
Series: 'color' [binary]
[
b"\x00\x00\x00"
b"\xff\xff\x00"
b"\x00\x00\xff"
]
"""
def encode(self, encoding: TransferEncoding) -> Series:
"""
Encode a value using the provided encoding.
Parameters
----------
encoding : {'hex', 'base64'}
The encoding to use.
Returns
-------
Series
Series of data type :class:`String`.
Examples
--------
>>> s = pl.Series(["foo", "bar", None])
>>> s.str.encode("hex")
shape: (3,)
Series: '' [str]
[
"666f6f"
"626172"
null
]
"""
def json_decode(
self,
dtype: PolarsDataType | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
) -> Series:
"""
Parse string values as JSON.
Throws an error if invalid JSON strings are encountered.
Parameters
----------
dtype
The dtype to cast the extracted value to. If None, the dtype will be
inferred from the JSON value.
infer_schema_length
The maximum number of rows to scan for schema inference.
If set to `None`, the full data may be scanned *(this is slow)*.
See Also
--------
json_path_match : Extract the first match of json string with provided JSONPath
expression.
Examples
--------
>>> s = pl.Series("json", ['{"a":1, "b": true}', None, '{"a":2, "b": false}'])
>>> s.str.json_decode()
shape: (3,)
Series: 'json' [struct[2]]
[
{1,true}
{null,null}
{2,false}
]
"""
def json_path_match(self, json_path: IntoExprColumn) -> Series:
"""
Extract the first match of json string with provided JSONPath expression.
Throw errors if encounter invalid json strings.
All return value will be casted to String regardless of the original value.
Documentation on JSONPath standard can be found
`here <https://goessner.net/articles/JsonPath/>`_.
Parameters
----------
json_path
A valid JSON path query string.
Returns
-------
Series
Series of data type :class:`String`. Contains null values if the original
value is null or the json_path returns nothing.
Examples
--------
>>> df = pl.DataFrame(
... {"json_val": ['{"a":"1"}', None, '{"a":2}', '{"a":2.1}', '{"a":true}']}
... )
>>> df.select(pl.col("json_val").str.json_path_match("$.a"))[:, 0]
shape: (5,)
Series: 'json_val' [str]
[
"1"
null
"2"
"2.1"
"true"
]
"""
def extract(self, pattern: IntoExprColumn, group_index: int = 1) -> Series:
r"""
Extract the target capture group from provided patterns.
Parameters
----------
pattern
A valid regular expression pattern containing at least one capture group,
compatible with the `regex crate <https://docs.rs/regex/latest/regex/>`_.
group_index
Index of the targeted capture group.
Group 0 means the whole pattern, the first group begins at index 1.
Defaults to the first capture group.
Returns
-------
Series
Series of data type :class:`String`. Contains null values if the original
value is null or regex captures nothing.
Notes
-----
To modify regular expression behaviour (such as multi-line matching)
with flags, use the inline `(?iLmsuxU)` syntax. For example:
>>> s = pl.Series(
... name="lines",
... values=[
... "I Like\nThose\nOdds",
... "This is\nThe Way",
... ],
... )
>>> s.str.extract(r"(?m)^(T\w+)", 1).alias("matches")
shape: (2,)
Series: 'matches' [str]
[
"Those"
"This"
]
See the regex crate's section on `grouping and flags
<https://docs.rs/regex/latest/regex/#grouping-and-flags>`_ for
additional information about the use of inline expression modifiers.
Examples
--------
>>> s = pl.Series(
... name="url",
... values=[
... "http://vote.com/ballon_dor?ref=polars&candidate=messi",
... "http://vote.com/ballon_dor?candidate=ronaldo&ref=polars",
... "http://vote.com/ballon_dor?error=404&ref=unknown",
... ],
... )
>>> s.str.extract(r"candidate=(\w+)", 1).alias("candidate")
shape: (3,)
Series: 'candidate' [str]
[
"messi"
"ronaldo"
null
]
"""
def extract_all(self, pattern: str | Series) -> Series:
r'''
Extract all matches for the given regex pattern.
Extract each successive non-overlapping regex match in an individual string
as a list. If the haystack string is `null`, `null` is returned.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
Notes
-----
To modify regular expression behaviour (such as "verbose" mode and/or
case-sensitive matching) with flags, use the inline `(?iLmsuxU)` syntax.
For example:
>>> s = pl.Series(
... name="email",
... values=[
... "real.email@spam.com",
... "some_account@somewhere.net",
... "abc.def.ghi.jkl@uvw.xyz.co.uk",
... ],
... )
>>> # extract name/domain parts from email, using verbose regex
>>> s.str.extract_all(
... r"""(?xi) # activate 'verbose' and 'case-insensitive' flags
... [ # (start character group)
... A-Z # letters
... 0-9 # digits
... ._%+\- # special chars
... ] # (end character group)
... + # 'one or more' quantifier
... """
... ).alias("email_parts")
shape: (3,)
Series: 'email_parts' [list[str]]
[
["real.email", "spam.com"]
["some_account", "somewhere.net"]
["abc.def.ghi.jkl", "uvw.xyz.co.uk"]
]
See the regex crate's section on `grouping and flags
<https://docs.rs/regex/latest/regex/#grouping-and-flags>`_ for
additional information about the use of inline expression modifiers.
Returns
-------
Series
Series of data type `List(String)`.
Examples
--------
>>> s = pl.Series("foo", ["123 bla 45 asd", "xyz 678 910t", "bar", None])
>>> s.str.extract_all(r"\d+")
shape: (4,)
Series: 'foo' [list[str]]
[
["123", "45"]
["678", "910"]
[]
null
]
'''
def extract_groups(self, pattern: str) -> Series:
r"""
Extract all capture groups for the given regex pattern.
Parameters
----------
pattern
A valid regular expression pattern containing at least one capture group,
compatible with the `regex crate <https://docs.rs/regex/latest/regex/>`_.
Notes
-----
All group names are **strings**.
If your pattern contains unnamed groups, their numerical position is converted
to a string.
For example, we can access the first group via the string `"1"`::
>>> (
... pl.Series(["foo bar baz"])
... .str.extract_groups(r"(\w+) (.+) (\w+)")
... .struct["1"]
... )
shape: (1,)
Series: '1' [str]
[
"foo"
]
Returns
-------
Series
Series of data type :class:`Struct` with fields of data type
:class:`String`.
Examples
--------
>>> s = pl.Series(
... name="url",
... values=[
... "http://vote.com/ballon_dor?candidate=messi&ref=python",
... "http://vote.com/ballon_dor?candidate=weghorst&ref=polars",
... "http://vote.com/ballon_dor?error=404&ref=rust",
... ],
... )
>>> s.str.extract_groups(r"candidate=(?<candidate>\w+)&ref=(?<ref>\w+)")
shape: (3,)
Series: 'url' [struct[2]]
[
{"messi","python"}
{"weghorst","polars"}
{null,null}
]
"""
def count_matches(self, pattern: str | Series, *, literal: bool = False) -> Series:
r"""
Count all successive non-overlapping regex matches.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_. Can also be a :class:`Series` of
regular expressions.
literal
Treat `pattern` as a literal string, not as a regular expression.
Returns
-------
Series
Series of data type :class:`UInt32`. Returns null if the original
value is null.
Examples
--------
>>> s = pl.Series("foo", ["123 bla 45 asd", "xyz 678 910t", "bar", None])
>>> # count digits
>>> s.str.count_matches(r"\d")
shape: (4,)
Series: 'foo' [u32]
[
5
6
0
null
]
>>> s = pl.Series("bar", ["12 dbc 3xy", "cat\\w", "1zy3\\d\\d", None])
>>> s.str.count_matches(r"\d", literal=True)
shape: (4,)
Series: 'bar' [u32]
[
0
0