forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_strings.py
3596 lines (2988 loc) · 129 KB
/
test_strings.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 datetime import datetime, timedelta
import re
import numpy as np
from numpy.random import randint
import pytest
from pandas._libs import lib
from pandas import DataFrame, Index, MultiIndex, Series, concat, isna, notna
import pandas._testing as tm
import pandas.core.strings as strings
def assert_series_or_index_equal(left, right):
if isinstance(left, Series):
tm.assert_series_equal(left, right)
else: # Index
tm.assert_index_equal(left, right)
_any_string_method = [
("cat", (), {"sep": ","}),
("cat", (Series(list("zyx")),), {"sep": ",", "join": "left"}),
("center", (10,), {}),
("contains", ("a",), {}),
("count", ("a",), {}),
("decode", ("UTF-8",), {}),
("encode", ("UTF-8",), {}),
("endswith", ("a",), {}),
("extract", ("([a-z]*)",), {"expand": False}),
("extract", ("([a-z]*)",), {"expand": True}),
("extractall", ("([a-z]*)",), {}),
("find", ("a",), {}),
("findall", ("a",), {}),
("get", (0,), {}),
# because "index" (and "rindex") fail intentionally
# if the string is not found, search only for empty string
("index", ("",), {}),
("join", (",",), {}),
("ljust", (10,), {}),
("match", ("a",), {}),
("normalize", ("NFC",), {}),
("pad", (10,), {}),
("partition", (" ",), {"expand": False}),
("partition", (" ",), {"expand": True}),
("repeat", (3,), {}),
("replace", ("a", "z"), {}),
("rfind", ("a",), {}),
("rindex", ("",), {}),
("rjust", (10,), {}),
("rpartition", (" ",), {"expand": False}),
("rpartition", (" ",), {"expand": True}),
("slice", (0, 1), {}),
("slice_replace", (0, 1, "z"), {}),
("split", (" ",), {"expand": False}),
("split", (" ",), {"expand": True}),
("startswith", ("a",), {}),
# translating unicode points of "a" to "d"
("translate", ({97: 100},), {}),
("wrap", (2,), {}),
("zfill", (10,), {}),
] + list(
zip(
[
# methods without positional arguments: zip with empty tuple and empty dict
"capitalize",
"cat",
"get_dummies",
"isalnum",
"isalpha",
"isdecimal",
"isdigit",
"islower",
"isnumeric",
"isspace",
"istitle",
"isupper",
"len",
"lower",
"lstrip",
"partition",
"rpartition",
"rsplit",
"rstrip",
"slice",
"slice_replace",
"split",
"strip",
"swapcase",
"title",
"upper",
"casefold",
],
[()] * 100,
[{}] * 100,
)
)
ids, _, _ = zip(*_any_string_method) # use method name as fixture-id
# test that the above list captures all methods of StringMethods
missing_methods = {
f for f in dir(strings.StringMethods) if not f.startswith("_")
} - set(ids)
assert not missing_methods
@pytest.fixture(params=_any_string_method, ids=ids)
def any_string_method(request):
"""
Fixture for all public methods of `StringMethods`
This fixture returns a tuple of the method name and sample arguments
necessary to call the method.
Returns
-------
method_name : str
The name of the method in `StringMethods`
args : tuple
Sample values for the positional arguments
kwargs : dict
Sample values for the keyword arguments
Examples
--------
>>> def test_something(any_string_method):
... s = pd.Series(['a', 'b', np.nan, 'd'])
...
... method_name, args, kwargs = any_string_method
... method = getattr(s.str, method_name)
... # will not raise
... method(*args, **kwargs)
"""
return request.param
# subset of the full set from pandas/conftest.py
_any_allowed_skipna_inferred_dtype = [
("string", ["a", np.nan, "c"]),
("bytes", [b"a", np.nan, b"c"]),
("empty", [np.nan, np.nan, np.nan]),
("empty", []),
("mixed-integer", ["a", np.nan, 2]),
]
ids, _ = zip(*_any_allowed_skipna_inferred_dtype) # use inferred type as id
@pytest.fixture(params=_any_allowed_skipna_inferred_dtype, ids=ids)
def any_allowed_skipna_inferred_dtype(request):
"""
Fixture for all (inferred) dtypes allowed in StringMethods.__init__
The covered (inferred) types are:
* 'string'
* 'empty'
* 'bytes'
* 'mixed'
* 'mixed-integer'
Returns
-------
inferred_dtype : str
The string for the inferred dtype from _libs.lib.infer_dtype
values : np.ndarray
An array of object dtype that will be inferred to have
`inferred_dtype`
Examples
--------
>>> import pandas._libs.lib as lib
>>>
>>> def test_something(any_allowed_skipna_inferred_dtype):
... inferred_dtype, values = any_allowed_skipna_inferred_dtype
... # will pass
... assert lib.infer_dtype(values, skipna=True) == inferred_dtype
...
... # constructor for .str-accessor will also pass
... pd.Series(values).str
"""
inferred_dtype, values = request.param
values = np.array(values, dtype=object) # object dtype to avoid casting
# correctness of inference tested in tests/dtypes/test_inference.py
return inferred_dtype, values
class TestStringMethods:
def test_api(self):
# GH 6106, GH 9322
assert Series.str is strings.StringMethods
assert isinstance(Series([""]).str, strings.StringMethods)
def test_api_mi_raises(self):
# GH 23679
mi = MultiIndex.from_arrays([["a", "b", "c"]])
msg = "Can only use .str accessor with Index, not MultiIndex"
with pytest.raises(AttributeError, match=msg):
mi.str
assert not hasattr(mi, "str")
@pytest.mark.parametrize("dtype", [object, "category"])
def test_api_per_dtype(self, index_or_series, dtype, any_skipna_inferred_dtype):
# one instance of parametrized fixture
box = index_or_series
inferred_dtype, values = any_skipna_inferred_dtype
t = box(values, dtype=dtype) # explicit dtype to avoid casting
# TODO: get rid of these xfails
if dtype == "category" and inferred_dtype in ["period", "interval"]:
pytest.xfail(
reason="Conversion to numpy array fails because "
"the ._values-attribute is not a numpy array for "
"PeriodArray/IntervalArray; see GH 23553"
)
types_passing_constructor = [
"string",
"unicode",
"empty",
"bytes",
"mixed",
"mixed-integer",
]
if inferred_dtype in types_passing_constructor:
# GH 6106
assert isinstance(t.str, strings.StringMethods)
else:
# GH 9184, GH 23011, GH 23163
msg = "Can only use .str accessor with string values.*"
with pytest.raises(AttributeError, match=msg):
t.str
assert not hasattr(t, "str")
@pytest.mark.parametrize("dtype", [object, "category"])
def test_api_per_method(
self,
index_or_series,
dtype,
any_allowed_skipna_inferred_dtype,
any_string_method,
):
# this test does not check correctness of the different methods,
# just that the methods work on the specified (inferred) dtypes,
# and raise on all others
box = index_or_series
# one instance of each parametrized fixture
inferred_dtype, values = any_allowed_skipna_inferred_dtype
method_name, args, kwargs = any_string_method
# TODO: get rid of these xfails
if (
method_name in ["partition", "rpartition"]
and box == Index
and inferred_dtype == "empty"
):
pytest.xfail(reason="Method cannot deal with empty Index")
if (
method_name == "split"
and box == Index
and values.size == 0
and kwargs.get("expand", None) is not None
):
pytest.xfail(reason="Split fails on empty Series when expand=True")
if (
method_name == "get_dummies"
and box == Index
and inferred_dtype == "empty"
and (dtype == object or values.size == 0)
):
pytest.xfail(reason="Need to fortify get_dummies corner cases")
t = box(values, dtype=dtype) # explicit dtype to avoid casting
method = getattr(t.str, method_name)
bytes_allowed = method_name in ["decode", "get", "len", "slice"]
# as of v0.23.4, all methods except 'cat' are very lenient with the
# allowed data types, just returning NaN for entries that error.
# This could be changed with an 'errors'-kwarg to the `str`-accessor,
# see discussion in GH 13877
mixed_allowed = method_name not in ["cat"]
allowed_types = (
["string", "unicode", "empty"]
+ ["bytes"] * bytes_allowed
+ ["mixed", "mixed-integer"] * mixed_allowed
)
if inferred_dtype in allowed_types:
# xref GH 23555, GH 23556
method(*args, **kwargs) # works!
else:
# GH 23011, GH 23163
msg = (
f"Cannot use .str.{method_name} with values of "
f"inferred dtype {repr(inferred_dtype)}."
)
with pytest.raises(TypeError, match=msg):
method(*args, **kwargs)
def test_api_for_categorical(self, any_string_method):
# https://github.com/pandas-dev/pandas/issues/10661
s = Series(list("aabb"))
s = s + " " + s
c = s.astype("category")
assert isinstance(c.str, strings.StringMethods)
method_name, args, kwargs = any_string_method
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)
elif isinstance(result, Series):
tm.assert_series_equal(result, expected)
else:
# str.cat(others=None) returns string, for example
assert result == expected
def test_iter(self):
# GH3638
strs = "google", "wikimedia", "wikipedia", "wikitravel"
ds = Series(strs)
with tm.assert_produces_warning(FutureWarning):
for s in ds.str:
# iter must yield a Series
assert isinstance(s, Series)
# indices of each yielded Series should be equal to the index of
# the original Series
tm.assert_index_equal(s.index, ds.index)
for el in s:
# each element of the series is either a basestring/str or nan
assert isinstance(el, str) or isna(el)
# desired behavior is to iterate until everything would be nan on the
# next iter so make sure the last element of the iterator was 'l' in
# this case since 'wikitravel' is the longest string
assert s.dropna().values.item() == "l"
def test_iter_empty(self):
ds = Series([], dtype=object)
i, s = 100, 1
with tm.assert_produces_warning(FutureWarning):
for i, s in enumerate(ds.str):
pass
# nothing to iterate over so nothing defined values should remain
# unchanged
assert i == 100
assert s == 1
def test_iter_single_element(self):
ds = Series(["a"])
with tm.assert_produces_warning(FutureWarning):
for i, s in enumerate(ds.str):
pass
assert not i
tm.assert_series_equal(ds, s)
def test_iter_object_try_string(self):
ds = Series([slice(None, randint(10), randint(10, 20)) for _ in range(4)])
i, s = 100, "h"
with tm.assert_produces_warning(FutureWarning):
for i, s in enumerate(ds.str):
pass
assert i == 100
assert s == "h"
@pytest.mark.parametrize("other", [None, Series, Index])
def test_str_cat_name(self, index_or_series, other):
# GH 21053
box = index_or_series
values = ["a", "b"]
if other:
other = other(values)
else:
other = values
result = box(values, name="name").str.cat(other, sep=",")
assert result.name == "name"
def test_str_cat(self, index_or_series):
box = index_or_series
# test_cat above tests "str_cat" from ndarray;
# here testing "str.cat" from Series/Indext to ndarray/list
s = box(["a", "a", "b", "b", "c", np.nan])
# single array
result = s.str.cat()
expected = "aabbc"
assert result == expected
result = s.str.cat(na_rep="-")
expected = "aabbc-"
assert result == expected
result = s.str.cat(sep="_", na_rep="NA")
expected = "a_a_b_b_c_NA"
assert result == expected
t = np.array(["a", np.nan, "b", "d", "foo", np.nan], dtype=object)
expected = box(["aa", "a-", "bb", "bd", "cfoo", "--"])
# Series/Index with array
result = s.str.cat(t, na_rep="-")
assert_series_or_index_equal(result, expected)
# Series/Index with list
result = s.str.cat(list(t), na_rep="-")
assert_series_or_index_equal(result, expected)
# errors for incorrect lengths
rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
z = Series(["1", "2", "3"])
with pytest.raises(ValueError, match=rgx):
s.str.cat(z.values)
with pytest.raises(ValueError, match=rgx):
s.str.cat(list(z))
def test_str_cat_raises_intuitive_error(self, index_or_series):
# GH 11334
box = index_or_series
s = box(["a", "b", "c", "d"])
message = "Did you mean to supply a `sep` keyword?"
with pytest.raises(ValueError, match=message):
s.str.cat("|")
with pytest.raises(ValueError, match=message):
s.str.cat(" ")
@pytest.mark.parametrize("sep", ["", None])
@pytest.mark.parametrize("dtype_target", ["object", "category"])
@pytest.mark.parametrize("dtype_caller", ["object", "category"])
def test_str_cat_categorical(
self, index_or_series, dtype_caller, dtype_target, sep
):
box = index_or_series
s = Index(["a", "a", "b", "a"], dtype=dtype_caller)
s = s if box == Index else Series(s, index=s)
t = Index(["b", "a", "b", "c"], dtype=dtype_target)
expected = Index(["ab", "aa", "bb", "ac"])
expected = expected if box == Index else Series(expected, index=s)
# Series/Index with unaligned Index -> t.values
result = s.str.cat(t.values, sep=sep)
assert_series_or_index_equal(result, expected)
# Series/Index with Series having matching Index
t = Series(t.values, index=s)
result = s.str.cat(t, sep=sep)
assert_series_or_index_equal(result, expected)
# Series/Index with Series.values
result = s.str.cat(t.values, sep=sep)
assert_series_or_index_equal(result, expected)
# Series/Index with Series having different Index
t = Series(t.values, index=t.values)
expected = Index(["aa", "aa", "aa", "bb", "bb"])
expected = (
expected if box == Index else Series(expected, index=expected.str[:1])
)
result = s.str.cat(t, sep=sep)
assert_series_or_index_equal(result, expected)
# test integer/float dtypes (inferred by constructor) and mixed
@pytest.mark.parametrize(
"data",
[[1, 2, 3], [0.1, 0.2, 0.3], [1, 2, "b"]],
ids=["integers", "floats", "mixed"],
)
# without dtype=object, np.array would cast [1, 2, 'b'] to ['1', '2', 'b']
@pytest.mark.parametrize(
"box",
[Series, Index, list, lambda x: np.array(x, dtype=object)],
ids=["Series", "Index", "list", "np.array"],
)
def test_str_cat_wrong_dtype_raises(self, box, data):
# GH 22722
s = Series(["a", "b", "c"])
t = box(data)
msg = "Concatenation requires list-likes containing only strings.*"
with pytest.raises(TypeError, match=msg):
# need to use outer and na_rep, as otherwise Index would not raise
s.str.cat(t, join="outer", na_rep="-")
def test_str_cat_mixed_inputs(self, index_or_series):
box = index_or_series
s = Index(["a", "b", "c", "d"])
s = s if box == Index else Series(s, index=s)
t = Series(["A", "B", "C", "D"], index=s.values)
d = concat([t, Series(s, index=s)], axis=1)
expected = Index(["aAa", "bBb", "cCc", "dDd"])
expected = expected if box == Index else Series(expected.values, index=s.values)
# Series/Index with DataFrame
result = s.str.cat(d)
assert_series_or_index_equal(result, expected)
# Series/Index with two-dimensional ndarray
result = s.str.cat(d.values)
assert_series_or_index_equal(result, expected)
# Series/Index with list of Series
result = s.str.cat([t, s])
assert_series_or_index_equal(result, expected)
# Series/Index with mixed list of Series/array
result = s.str.cat([t, s.values])
assert_series_or_index_equal(result, expected)
# Series/Index with list of Series; different indexes
t.index = ["b", "c", "d", "a"]
expected = box(["aDa", "bAb", "cBc", "dCd"])
expected = expected if box == Index else Series(expected.values, index=s.values)
result = s.str.cat([t, s])
assert_series_or_index_equal(result, expected)
# Series/Index with mixed list; different index
result = s.str.cat([t, s.values])
assert_series_or_index_equal(result, expected)
# Series/Index with DataFrame; different indexes
d.index = ["b", "c", "d", "a"]
expected = box(["aDd", "bAa", "cBb", "dCc"])
expected = expected if box == Index else Series(expected.values, index=s.values)
result = s.str.cat(d)
assert_series_or_index_equal(result, expected)
# errors for incorrect lengths
rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
z = Series(["1", "2", "3"])
e = concat([z, z], axis=1)
# two-dimensional ndarray
with pytest.raises(ValueError, match=rgx):
s.str.cat(e.values)
# list of list-likes
with pytest.raises(ValueError, match=rgx):
s.str.cat([z.values, s.values])
# mixed list of Series/list-like
with pytest.raises(ValueError, match=rgx):
s.str.cat([z.values, s])
# errors for incorrect arguments in list-like
rgx = "others must be Series, Index, DataFrame,.*"
# make sure None/NaN do not crash checks in _get_series_list
u = Series(["a", np.nan, "c", None])
# mix of string and Series
with pytest.raises(TypeError, match=rgx):
s.str.cat([u, "u"])
# DataFrame in list
with pytest.raises(TypeError, match=rgx):
s.str.cat([u, d])
# 2-dim ndarray in list
with pytest.raises(TypeError, match=rgx):
s.str.cat([u, d.values])
# nested lists
with pytest.raises(TypeError, match=rgx):
s.str.cat([u, [u, d]])
# forbidden input type: set
# GH 23009
with pytest.raises(TypeError, match=rgx):
s.str.cat(set(u))
# forbidden input type: set in list
# GH 23009
with pytest.raises(TypeError, match=rgx):
s.str.cat([u, set(u)])
# other forbidden input type, e.g. int
with pytest.raises(TypeError, match=rgx):
s.str.cat(1)
# nested list-likes
with pytest.raises(TypeError, match=rgx):
s.str.cat(iter([t.values, list(s)]))
@pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
def test_str_cat_align_indexed(self, index_or_series, join):
# https://github.com/pandas-dev/pandas/issues/18657
box = index_or_series
s = Series(["a", "b", "c", "d"], index=["a", "b", "c", "d"])
t = Series(["D", "A", "E", "B"], index=["d", "a", "e", "b"])
sa, ta = s.align(t, join=join)
# result after manual alignment of inputs
expected = sa.str.cat(ta, na_rep="-")
if box == Index:
s = Index(s)
sa = Index(sa)
expected = Index(expected)
result = s.str.cat(t, join=join, na_rep="-")
assert_series_or_index_equal(result, expected)
@pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
def test_str_cat_align_mixed_inputs(self, join):
s = Series(["a", "b", "c", "d"])
t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
d = concat([t, t], axis=1)
expected_outer = Series(["aaa", "bbb", "c--", "ddd", "-ee"])
expected = expected_outer.loc[s.index.join(t.index, how=join)]
# list of Series
result = s.str.cat([t, t], join=join, na_rep="-")
tm.assert_series_equal(result, expected)
# DataFrame
result = s.str.cat(d, join=join, na_rep="-")
tm.assert_series_equal(result, expected)
# mixed list of indexed/unindexed
u = np.array(["A", "B", "C", "D"])
expected_outer = Series(["aaA", "bbB", "c-C", "ddD", "-e-"])
# joint index of rhs [t, u]; u will be forced have index of s
rhs_idx = t.index & s.index if join == "inner" else t.index | s.index
expected = expected_outer.loc[s.index.join(rhs_idx, how=join)]
result = s.str.cat([t, u], join=join, na_rep="-")
tm.assert_series_equal(result, expected)
with pytest.raises(TypeError, match="others must be Series,.*"):
# nested lists are forbidden
s.str.cat([t, list(u)], join=join)
# errors for incorrect lengths
rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
z = Series(["1", "2", "3"]).values
# unindexed object of wrong length
with pytest.raises(ValueError, match=rgx):
s.str.cat(z, join=join)
# unindexed object of wrong length in list
with pytest.raises(ValueError, match=rgx):
s.str.cat([t, z], join=join)
index_or_series2 = [Series, Index] # type: ignore
# List item 0 has incompatible type "Type[Series]"; expected "Type[PandasObject]"
# See GH#29725
@pytest.mark.parametrize("other", index_or_series2)
def test_str_cat_all_na(self, index_or_series, other):
# GH 24044
box = index_or_series
# check that all NaNs in caller / target work
s = Index(["a", "b", "c", "d"])
s = s if box == Index else Series(s, index=s)
t = other([np.nan] * 4, dtype=object)
# add index of s for alignment
t = t if other == Index else Series(t, index=s)
# all-NA target
if box == Series:
expected = Series([np.nan] * 4, index=s.index, dtype=object)
else: # box == Index
expected = Index([np.nan] * 4, dtype=object)
result = s.str.cat(t, join="left")
assert_series_or_index_equal(result, expected)
# all-NA caller (only for Series)
if other == Series:
expected = Series([np.nan] * 4, dtype=object, index=t.index)
result = t.str.cat(s, join="left")
tm.assert_series_equal(result, expected)
def test_str_cat_special_cases(self):
s = Series(["a", "b", "c", "d"])
t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
# iterator of elements with different types
expected = Series(["aaa", "bbb", "c-c", "ddd", "-e-"])
result = s.str.cat(iter([t, s.values]), join="outer", na_rep="-")
tm.assert_series_equal(result, expected)
# right-align with different indexes in others
expected = Series(["aa-", "d-d"], index=[0, 3])
result = s.str.cat([t.loc[[0]], t.loc[[3]]], join="right", na_rep="-")
tm.assert_series_equal(result, expected)
def test_cat_on_filtered_index(self):
df = DataFrame(
index=MultiIndex.from_product(
[[2011, 2012], [1, 2, 3]], names=["year", "month"]
)
)
df = df.reset_index()
df = df[df.month > 1]
str_year = df.year.astype("str")
str_month = df.month.astype("str")
str_both = str_year.str.cat(str_month, sep=" ")
assert str_both.loc[1] == "2011 2"
str_multiple = str_year.str.cat([str_month, str_month], sep=" ")
assert str_multiple.loc[1] == "2011 2 2"
def test_count(self):
values = np.array(
["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=np.object_
)
result = strings.str_count(values, "f[o]+")
exp = np.array([1, 2, np.nan, 4])
tm.assert_numpy_array_equal(result, exp)
result = Series(values).str.count("f[o]+")
exp = Series([1, 2, np.nan, 4])
assert isinstance(result, Series)
tm.assert_series_equal(result, exp)
# mixed
mixed = np.array(
["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
dtype=object,
)
rs = strings.str_count(mixed, "a")
xp = np.array([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan])
tm.assert_numpy_array_equal(rs, xp)
rs = Series(mixed).str.count("a")
xp = Series([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan])
assert isinstance(rs, Series)
tm.assert_series_equal(rs, xp)
def test_contains(self):
values = np.array(
["foo", np.nan, "fooommm__foo", "mmm_", "foommm[_]+bar"], dtype=np.object_
)
pat = "mmm[_]+"
result = strings.str_contains(values, pat)
expected = np.array([False, np.nan, True, True, False], dtype=np.object_)
tm.assert_numpy_array_equal(result, expected)
result = strings.str_contains(values, pat, regex=False)
expected = np.array([False, np.nan, False, False, True], dtype=np.object_)
tm.assert_numpy_array_equal(result, expected)
values = np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=object)
result = strings.str_contains(values, pat)
expected = np.array([False, False, True, True])
assert result.dtype == np.bool_
tm.assert_numpy_array_equal(result, expected)
# case insensitive using regex
values = np.array(["Foo", "xYz", "fOOomMm__fOo", "MMM_"], dtype=object)
result = strings.str_contains(values, "FOO|mmm", case=False)
expected = np.array([True, False, True, True])
tm.assert_numpy_array_equal(result, expected)
# case insensitive without regex
result = strings.str_contains(values, "foo", regex=False, case=False)
expected = np.array([True, False, True, False])
tm.assert_numpy_array_equal(result, expected)
# mixed
mixed = np.array(
["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
dtype=object,
)
rs = strings.str_contains(mixed, "o")
xp = np.array(
[False, np.nan, False, np.nan, np.nan, True, np.nan, np.nan, np.nan],
dtype=np.object_,
)
tm.assert_numpy_array_equal(rs, xp)
rs = Series(mixed).str.contains("o")
xp = Series(
[False, np.nan, False, np.nan, np.nan, True, np.nan, np.nan, np.nan]
)
assert isinstance(rs, Series)
tm.assert_series_equal(rs, xp)
# unicode
values = np.array(["foo", np.nan, "fooommm__foo", "mmm_"], dtype=np.object_)
pat = "mmm[_]+"
result = strings.str_contains(values, pat)
expected = np.array([False, np.nan, True, True], dtype=np.object_)
tm.assert_numpy_array_equal(result, expected)
result = strings.str_contains(values, pat, na=False)
expected = np.array([False, False, True, True])
tm.assert_numpy_array_equal(result, expected)
values = np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=np.object_)
result = strings.str_contains(values, pat)
expected = np.array([False, False, True, True])
assert result.dtype == np.bool_
tm.assert_numpy_array_equal(result, expected)
def test_contains_for_object_category(self):
# gh 22158
# na for category
values = Series(["a", "b", "c", "a", np.nan], dtype="category")
result = values.str.contains("a", na=True)
expected = Series([True, False, False, True, True])
tm.assert_series_equal(result, expected)
result = values.str.contains("a", na=False)
expected = Series([True, False, False, True, False])
tm.assert_series_equal(result, expected)
# na for objects
values = Series(["a", "b", "c", "a", np.nan])
result = values.str.contains("a", na=True)
expected = Series([True, False, False, True, True])
tm.assert_series_equal(result, expected)
result = values.str.contains("a", na=False)
expected = Series([True, False, False, True, False])
tm.assert_series_equal(result, expected)
def test_startswith(self):
values = Series(["om", np.nan, "foo_nom", "nom", "bar_foo", np.nan, "foo"])
result = values.str.startswith("foo")
exp = Series([False, np.nan, True, False, False, np.nan, True])
tm.assert_series_equal(result, exp)
result = values.str.startswith("foo", na=True)
tm.assert_series_equal(result, exp.fillna(True).astype(bool))
# mixed
mixed = np.array(
["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
dtype=np.object_,
)
rs = strings.str_startswith(mixed, "f")
xp = np.array(
[False, np.nan, False, np.nan, np.nan, True, np.nan, np.nan, np.nan],
dtype=np.object_,
)
tm.assert_numpy_array_equal(rs, xp)
rs = Series(mixed).str.startswith("f")
assert isinstance(rs, Series)
xp = Series(
[False, np.nan, False, np.nan, np.nan, True, np.nan, np.nan, np.nan]
)
tm.assert_series_equal(rs, xp)
def test_endswith(self):
values = Series(["om", np.nan, "foo_nom", "nom", "bar_foo", np.nan, "foo"])
result = values.str.endswith("foo")
exp = Series([False, np.nan, False, False, True, np.nan, True])
tm.assert_series_equal(result, exp)
result = values.str.endswith("foo", na=False)
tm.assert_series_equal(result, exp.fillna(False).astype(bool))
# mixed
mixed = np.array(
["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
dtype=object,
)
rs = strings.str_endswith(mixed, "f")
xp = np.array(
[False, np.nan, False, np.nan, np.nan, False, np.nan, np.nan, np.nan],
dtype=np.object_,
)
tm.assert_numpy_array_equal(rs, xp)
rs = Series(mixed).str.endswith("f")
xp = Series(
[False, np.nan, False, np.nan, np.nan, False, np.nan, np.nan, np.nan]
)
assert isinstance(rs, Series)
tm.assert_series_equal(rs, xp)
def test_title(self):
values = Series(["FOO", "BAR", np.nan, "Blah", "blurg"])
result = values.str.title()
exp = Series(["Foo", "Bar", np.nan, "Blah", "Blurg"])
tm.assert_series_equal(result, exp)
# mixed
mixed = Series(
["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0]
)
mixed = mixed.str.title()
exp = Series(
["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", np.nan, np.nan, np.nan]
)
tm.assert_almost_equal(mixed, exp)
def test_lower_upper(self):
values = Series(["om", np.nan, "nom", "nom"])
result = values.str.upper()
exp = Series(["OM", np.nan, "NOM", "NOM"])
tm.assert_series_equal(result, exp)
result = result.str.lower()
tm.assert_series_equal(result, values)
# mixed
mixed = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0])
mixed = mixed.str.upper()
rs = Series(mixed).str.lower()
xp = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan])
assert isinstance(rs, Series)
tm.assert_series_equal(rs, xp)
def test_capitalize(self):
values = Series(["FOO", "BAR", np.nan, "Blah", "blurg"])
result = values.str.capitalize()
exp = Series(["Foo", "Bar", np.nan, "Blah", "Blurg"])
tm.assert_series_equal(result, exp)
# mixed
mixed = Series(
["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0]
)
mixed = mixed.str.capitalize()
exp = Series(
["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", np.nan, np.nan, np.nan]
)
tm.assert_almost_equal(mixed, exp)
def test_swapcase(self):
values = Series(["FOO", "BAR", np.nan, "Blah", "blurg"])
result = values.str.swapcase()
exp = Series(["foo", "bar", np.nan, "bLAH", "BLURG"])
tm.assert_series_equal(result, exp)
# mixed
mixed = Series(
["FOO", np.nan, "bar", True, datetime.today(), "Blah", None, 1, 2.0]
)
mixed = mixed.str.swapcase()
exp = Series(
["foo", np.nan, "BAR", np.nan, np.nan, "bLAH", np.nan, np.nan, np.nan]
)
tm.assert_almost_equal(mixed, exp)
def test_casemethods(self):
values = ["aaa", "bbb", "CCC", "Dddd", "eEEE"]
s = Series(values)
assert s.str.lower().tolist() == [v.lower() for v in values]
assert s.str.upper().tolist() == [v.upper() for v in values]
assert s.str.title().tolist() == [v.title() for v in values]
assert s.str.capitalize().tolist() == [v.capitalize() for v in values]
assert s.str.swapcase().tolist() == [v.swapcase() for v in values]
def test_replace(self):
values = Series(["fooBAD__barBAD", np.nan])
result = values.str.replace("BAD[_]*", "")
exp = Series(["foobar", np.nan])
tm.assert_series_equal(result, exp)
result = values.str.replace("BAD[_]*", "", n=1)
exp = Series(["foobarBAD", np.nan])
tm.assert_series_equal(result, exp)
# mixed
mixed = Series(
["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0]
)