applied-ai-018 commited on
Commit
39d7954
·
verified ·
1 Parent(s): 4d8282d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/__init__.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_astype.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_comparison.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_construction.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_function.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_indexing.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_logical.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_ops.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_repr.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/__init__.py +0 -0
  12. env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/__init__.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/test_compat.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/test_eval.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/test_compat.py +32 -0
  16. env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/test_eval.py +1991 -0
  17. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__init__.py +15 -0
  18. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/__init__.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/conftest.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_cat.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_extract.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_find_replace.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_get_dummies.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_string_array.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/conftest.py +132 -0
  26. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_api.py +198 -0
  27. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_case_justify.py +427 -0
  28. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_cat.py +427 -0
  29. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_extract.py +724 -0
  30. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_find_replace.py +972 -0
  31. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_get_dummies.py +53 -0
  32. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_split_partition.py +734 -0
  33. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_string_array.py +112 -0
  34. env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_strings.py +720 -0
  35. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__init__.py +0 -0
  36. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/__init__.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_api.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_array_to_datetime.cpython-310.pyc +0 -0
  39. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_ccalendar.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_conversion.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_fields.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_libfrequencies.cpython-310.pyc +0 -0
  43. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_liboffsets.cpython-310.pyc +0 -0
  44. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_np_datetime.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_npy_units.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_parse_iso8601.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_parsing.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_period.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_resolution.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_strptime.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_arithmetic.cpython-310.pyc ADDED
Binary file (3.59 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_astype.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_comparison.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_construction.cpython-310.pyc ADDED
Binary file (8.29 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_function.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (639 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_logical.cpython-310.pyc ADDED
Binary file (6.79 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_ops.cpython-310.pyc ADDED
Binary file (1.18 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_repr.cpython-310.pyc ADDED
Binary file (650 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (189 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/test_compat.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/test_eval.cpython-310.pyc ADDED
Binary file (58.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/test_compat.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas.compat._optional import VERSIONS
4
+
5
+ import pandas as pd
6
+ from pandas.core.computation import expr
7
+ from pandas.core.computation.engines import ENGINES
8
+ from pandas.util.version import Version
9
+
10
+
11
+ def test_compat():
12
+ # test we have compat with our version of numexpr
13
+
14
+ from pandas.core.computation.check import NUMEXPR_INSTALLED
15
+
16
+ ne = pytest.importorskip("numexpr")
17
+
18
+ ver = ne.__version__
19
+ if Version(ver) < Version(VERSIONS["numexpr"]):
20
+ assert not NUMEXPR_INSTALLED
21
+ else:
22
+ assert NUMEXPR_INSTALLED
23
+
24
+
25
+ @pytest.mark.parametrize("engine", ENGINES)
26
+ @pytest.mark.parametrize("parser", expr.PARSERS)
27
+ def test_invalid_numexpr_version(engine, parser):
28
+ if engine == "numexpr":
29
+ pytest.importorskip("numexpr")
30
+ a, b = 1, 2 # noqa: F841
31
+ res = pd.eval("a + b", engine=engine, parser=parser)
32
+ assert res == 3
env-llmeval/lib/python3.10/site-packages/pandas/tests/computation/test_eval.py ADDED
@@ -0,0 +1,1991 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from functools import reduce
4
+ from itertools import product
5
+ import operator
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from pandas.compat import PY312
11
+ from pandas.errors import (
12
+ NumExprClobberingError,
13
+ PerformanceWarning,
14
+ UndefinedVariableError,
15
+ )
16
+ import pandas.util._test_decorators as td
17
+
18
+ from pandas.core.dtypes.common import (
19
+ is_bool,
20
+ is_float,
21
+ is_list_like,
22
+ is_scalar,
23
+ )
24
+
25
+ import pandas as pd
26
+ from pandas import (
27
+ DataFrame,
28
+ Index,
29
+ Series,
30
+ date_range,
31
+ period_range,
32
+ timedelta_range,
33
+ )
34
+ import pandas._testing as tm
35
+ from pandas.core.computation import (
36
+ expr,
37
+ pytables,
38
+ )
39
+ from pandas.core.computation.engines import ENGINES
40
+ from pandas.core.computation.expr import (
41
+ BaseExprVisitor,
42
+ PandasExprVisitor,
43
+ PythonExprVisitor,
44
+ )
45
+ from pandas.core.computation.expressions import (
46
+ NUMEXPR_INSTALLED,
47
+ USE_NUMEXPR,
48
+ )
49
+ from pandas.core.computation.ops import (
50
+ ARITH_OPS_SYMS,
51
+ SPECIAL_CASE_ARITH_OPS_SYMS,
52
+ _binary_math_ops,
53
+ _binary_ops_dict,
54
+ _unary_math_ops,
55
+ )
56
+ from pandas.core.computation.scope import DEFAULT_GLOBALS
57
+
58
+
59
+ @pytest.fixture(
60
+ params=(
61
+ pytest.param(
62
+ engine,
63
+ marks=[
64
+ pytest.mark.skipif(
65
+ engine == "numexpr" and not USE_NUMEXPR,
66
+ reason=f"numexpr enabled->{USE_NUMEXPR}, "
67
+ f"installed->{NUMEXPR_INSTALLED}",
68
+ ),
69
+ td.skip_if_no("numexpr"),
70
+ ],
71
+ )
72
+ for engine in ENGINES
73
+ )
74
+ )
75
+ def engine(request):
76
+ return request.param
77
+
78
+
79
+ @pytest.fixture(params=expr.PARSERS)
80
+ def parser(request):
81
+ return request.param
82
+
83
+
84
+ def _eval_single_bin(lhs, cmp1, rhs, engine):
85
+ c = _binary_ops_dict[cmp1]
86
+ if ENGINES[engine].has_neg_frac:
87
+ try:
88
+ return c(lhs, rhs)
89
+ except ValueError as e:
90
+ if str(e).startswith(
91
+ "negative number cannot be raised to a fractional power"
92
+ ):
93
+ return np.nan
94
+ raise
95
+ return c(lhs, rhs)
96
+
97
+
98
+ # TODO: using range(5) here is a kludge
99
+ @pytest.fixture(
100
+ params=list(range(5)),
101
+ ids=["DataFrame", "Series", "SeriesNaN", "DataFrameNaN", "float"],
102
+ )
103
+ def lhs(request):
104
+ nan_df1 = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
105
+ nan_df1[nan_df1 > 0.5] = np.nan
106
+
107
+ opts = (
108
+ DataFrame(np.random.default_rng(2).standard_normal((10, 5))),
109
+ Series(np.random.default_rng(2).standard_normal(5)),
110
+ Series([1, 2, np.nan, np.nan, 5]),
111
+ nan_df1,
112
+ np.random.default_rng(2).standard_normal(),
113
+ )
114
+ return opts[request.param]
115
+
116
+
117
+ rhs = lhs
118
+ midhs = lhs
119
+
120
+
121
+ @pytest.fixture
122
+ def idx_func_dict():
123
+ return {
124
+ "i": lambda n: Index(np.arange(n), dtype=np.int64),
125
+ "f": lambda n: Index(np.arange(n), dtype=np.float64),
126
+ "s": lambda n: Index([f"{i}_{chr(i)}" for i in range(97, 97 + n)]),
127
+ "dt": lambda n: date_range("2020-01-01", periods=n),
128
+ "td": lambda n: timedelta_range("1 day", periods=n),
129
+ "p": lambda n: period_range("2020-01-01", periods=n, freq="D"),
130
+ }
131
+
132
+
133
+ class TestEval:
134
+ @pytest.mark.parametrize(
135
+ "cmp1",
136
+ ["!=", "==", "<=", ">=", "<", ">"],
137
+ ids=["ne", "eq", "le", "ge", "lt", "gt"],
138
+ )
139
+ @pytest.mark.parametrize("cmp2", [">", "<"], ids=["gt", "lt"])
140
+ @pytest.mark.parametrize("binop", expr.BOOL_OPS_SYMS)
141
+ def test_complex_cmp_ops(self, cmp1, cmp2, binop, lhs, rhs, engine, parser):
142
+ if parser == "python" and binop in ["and", "or"]:
143
+ msg = "'BoolOp' nodes are not implemented"
144
+ with pytest.raises(NotImplementedError, match=msg):
145
+ ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)"
146
+ pd.eval(ex, engine=engine, parser=parser)
147
+ return
148
+
149
+ lhs_new = _eval_single_bin(lhs, cmp1, rhs, engine)
150
+ rhs_new = _eval_single_bin(lhs, cmp2, rhs, engine)
151
+ expected = _eval_single_bin(lhs_new, binop, rhs_new, engine)
152
+
153
+ ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)"
154
+ result = pd.eval(ex, engine=engine, parser=parser)
155
+ tm.assert_equal(result, expected)
156
+
157
+ @pytest.mark.parametrize("cmp_op", expr.CMP_OPS_SYMS)
158
+ def test_simple_cmp_ops(self, cmp_op, lhs, rhs, engine, parser):
159
+ lhs = lhs < 0
160
+ rhs = rhs < 0
161
+
162
+ if parser == "python" and cmp_op in ["in", "not in"]:
163
+ msg = "'(In|NotIn)' nodes are not implemented"
164
+
165
+ with pytest.raises(NotImplementedError, match=msg):
166
+ ex = f"lhs {cmp_op} rhs"
167
+ pd.eval(ex, engine=engine, parser=parser)
168
+ return
169
+
170
+ ex = f"lhs {cmp_op} rhs"
171
+ msg = "|".join(
172
+ [
173
+ r"only list-like( or dict-like)? objects are allowed to be "
174
+ r"passed to (DataFrame\.)?isin\(\), you passed a "
175
+ r"(`|')bool(`|')",
176
+ "argument of type 'bool' is not iterable",
177
+ ]
178
+ )
179
+ if cmp_op in ("in", "not in") and not is_list_like(rhs):
180
+ with pytest.raises(TypeError, match=msg):
181
+ pd.eval(
182
+ ex,
183
+ engine=engine,
184
+ parser=parser,
185
+ local_dict={"lhs": lhs, "rhs": rhs},
186
+ )
187
+ else:
188
+ expected = _eval_single_bin(lhs, cmp_op, rhs, engine)
189
+ result = pd.eval(ex, engine=engine, parser=parser)
190
+ tm.assert_equal(result, expected)
191
+
192
+ @pytest.mark.parametrize("op", expr.CMP_OPS_SYMS)
193
+ def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser):
194
+ if parser == "python" and op in ["in", "not in"]:
195
+ msg = "'(In|NotIn)' nodes are not implemented"
196
+ with pytest.raises(NotImplementedError, match=msg):
197
+ ex = f"~(lhs {op} rhs)"
198
+ pd.eval(ex, engine=engine, parser=parser)
199
+ return
200
+
201
+ if (
202
+ is_float(lhs)
203
+ and not is_float(rhs)
204
+ and op in ["in", "not in"]
205
+ and engine == "python"
206
+ and parser == "pandas"
207
+ ):
208
+ mark = pytest.mark.xfail(
209
+ reason="Looks like expected is negative, unclear whether "
210
+ "expected is incorrect or result is incorrect"
211
+ )
212
+ request.applymarker(mark)
213
+ skip_these = ["in", "not in"]
214
+ ex = f"~(lhs {op} rhs)"
215
+
216
+ msg = "|".join(
217
+ [
218
+ r"only list-like( or dict-like)? objects are allowed to be "
219
+ r"passed to (DataFrame\.)?isin\(\), you passed a "
220
+ r"(`|')float(`|')",
221
+ "argument of type 'float' is not iterable",
222
+ ]
223
+ )
224
+ if is_scalar(rhs) and op in skip_these:
225
+ with pytest.raises(TypeError, match=msg):
226
+ pd.eval(
227
+ ex,
228
+ engine=engine,
229
+ parser=parser,
230
+ local_dict={"lhs": lhs, "rhs": rhs},
231
+ )
232
+ else:
233
+ # compound
234
+ if is_scalar(lhs) and is_scalar(rhs):
235
+ lhs, rhs = (np.array([x]) for x in (lhs, rhs))
236
+ expected = _eval_single_bin(lhs, op, rhs, engine)
237
+ if is_scalar(expected):
238
+ expected = not expected
239
+ else:
240
+ expected = ~expected
241
+ result = pd.eval(ex, engine=engine, parser=parser)
242
+ tm.assert_almost_equal(expected, result)
243
+
244
+ @pytest.mark.parametrize("cmp1", ["<", ">"])
245
+ @pytest.mark.parametrize("cmp2", ["<", ">"])
246
+ def test_chained_cmp_op(self, cmp1, cmp2, lhs, midhs, rhs, engine, parser):
247
+ mid = midhs
248
+ if parser == "python":
249
+ ex1 = f"lhs {cmp1} mid {cmp2} rhs"
250
+ msg = "'BoolOp' nodes are not implemented"
251
+ with pytest.raises(NotImplementedError, match=msg):
252
+ pd.eval(ex1, engine=engine, parser=parser)
253
+ return
254
+
255
+ lhs_new = _eval_single_bin(lhs, cmp1, mid, engine)
256
+ rhs_new = _eval_single_bin(mid, cmp2, rhs, engine)
257
+
258
+ if lhs_new is not None and rhs_new is not None:
259
+ ex1 = f"lhs {cmp1} mid {cmp2} rhs"
260
+ ex2 = f"lhs {cmp1} mid and mid {cmp2} rhs"
261
+ ex3 = f"(lhs {cmp1} mid) & (mid {cmp2} rhs)"
262
+ expected = _eval_single_bin(lhs_new, "&", rhs_new, engine)
263
+
264
+ for ex in (ex1, ex2, ex3):
265
+ result = pd.eval(ex, engine=engine, parser=parser)
266
+
267
+ tm.assert_almost_equal(result, expected)
268
+
269
+ @pytest.mark.parametrize(
270
+ "arith1", sorted(set(ARITH_OPS_SYMS).difference(SPECIAL_CASE_ARITH_OPS_SYMS))
271
+ )
272
+ def test_binary_arith_ops(self, arith1, lhs, rhs, engine, parser):
273
+ ex = f"lhs {arith1} rhs"
274
+ result = pd.eval(ex, engine=engine, parser=parser)
275
+ expected = _eval_single_bin(lhs, arith1, rhs, engine)
276
+
277
+ tm.assert_almost_equal(result, expected)
278
+ ex = f"lhs {arith1} rhs {arith1} rhs"
279
+ result = pd.eval(ex, engine=engine, parser=parser)
280
+ nlhs = _eval_single_bin(lhs, arith1, rhs, engine)
281
+ try:
282
+ nlhs, ghs = nlhs.align(rhs)
283
+ except (ValueError, TypeError, AttributeError):
284
+ # ValueError: series frame or frame series align
285
+ # TypeError, AttributeError: series or frame with scalar align
286
+ return
287
+ else:
288
+ if engine == "numexpr":
289
+ import numexpr as ne
290
+
291
+ # direct numpy comparison
292
+ expected = ne.evaluate(f"nlhs {arith1} ghs")
293
+ # Update assert statement due to unreliable numerical
294
+ # precision component (GH37328)
295
+ # TODO: update testing code so that assert_almost_equal statement
296
+ # can be replaced again by the assert_numpy_array_equal statement
297
+ tm.assert_almost_equal(result.values, expected)
298
+ else:
299
+ expected = eval(f"nlhs {arith1} ghs")
300
+ tm.assert_almost_equal(result, expected)
301
+
302
+ # modulus, pow, and floor division require special casing
303
+
304
+ def test_modulus(self, lhs, rhs, engine, parser):
305
+ ex = r"lhs % rhs"
306
+ result = pd.eval(ex, engine=engine, parser=parser)
307
+ expected = lhs % rhs
308
+ tm.assert_almost_equal(result, expected)
309
+
310
+ if engine == "numexpr":
311
+ import numexpr as ne
312
+
313
+ expected = ne.evaluate(r"expected % rhs")
314
+ if isinstance(result, (DataFrame, Series)):
315
+ tm.assert_almost_equal(result.values, expected)
316
+ else:
317
+ tm.assert_almost_equal(result, expected.item())
318
+ else:
319
+ expected = _eval_single_bin(expected, "%", rhs, engine)
320
+ tm.assert_almost_equal(result, expected)
321
+
322
+ def test_floor_division(self, lhs, rhs, engine, parser):
323
+ ex = "lhs // rhs"
324
+
325
+ if engine == "python":
326
+ res = pd.eval(ex, engine=engine, parser=parser)
327
+ expected = lhs // rhs
328
+ tm.assert_equal(res, expected)
329
+ else:
330
+ msg = (
331
+ r"unsupported operand type\(s\) for //: 'VariableNode' and "
332
+ "'VariableNode'"
333
+ )
334
+ with pytest.raises(TypeError, match=msg):
335
+ pd.eval(
336
+ ex,
337
+ local_dict={"lhs": lhs, "rhs": rhs},
338
+ engine=engine,
339
+ parser=parser,
340
+ )
341
+
342
+ @td.skip_if_windows
343
+ def test_pow(self, lhs, rhs, engine, parser):
344
+ # odd failure on win32 platform, so skip
345
+ ex = "lhs ** rhs"
346
+ expected = _eval_single_bin(lhs, "**", rhs, engine)
347
+ result = pd.eval(ex, engine=engine, parser=parser)
348
+
349
+ if (
350
+ is_scalar(lhs)
351
+ and is_scalar(rhs)
352
+ and isinstance(expected, (complex, np.complexfloating))
353
+ and np.isnan(result)
354
+ ):
355
+ msg = "(DataFrame.columns|numpy array) are different"
356
+ with pytest.raises(AssertionError, match=msg):
357
+ tm.assert_numpy_array_equal(result, expected)
358
+ else:
359
+ tm.assert_almost_equal(result, expected)
360
+
361
+ ex = "(lhs ** rhs) ** rhs"
362
+ result = pd.eval(ex, engine=engine, parser=parser)
363
+
364
+ middle = _eval_single_bin(lhs, "**", rhs, engine)
365
+ expected = _eval_single_bin(middle, "**", rhs, engine)
366
+ tm.assert_almost_equal(result, expected)
367
+
368
+ def test_check_single_invert_op(self, lhs, engine, parser):
369
+ # simple
370
+ try:
371
+ elb = lhs.astype(bool)
372
+ except AttributeError:
373
+ elb = np.array([bool(lhs)])
374
+ expected = ~elb
375
+ result = pd.eval("~elb", engine=engine, parser=parser)
376
+ tm.assert_almost_equal(expected, result)
377
+
378
+ def test_frame_invert(self, engine, parser):
379
+ expr = "~lhs"
380
+
381
+ # ~ ##
382
+ # frame
383
+ # float always raises
384
+ lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)))
385
+ if engine == "numexpr":
386
+ msg = "couldn't find matching opcode for 'invert_dd'"
387
+ with pytest.raises(NotImplementedError, match=msg):
388
+ pd.eval(expr, engine=engine, parser=parser)
389
+ else:
390
+ msg = "ufunc 'invert' not supported for the input types"
391
+ with pytest.raises(TypeError, match=msg):
392
+ pd.eval(expr, engine=engine, parser=parser)
393
+
394
+ # int raises on numexpr
395
+ lhs = DataFrame(np.random.default_rng(2).integers(5, size=(5, 2)))
396
+ if engine == "numexpr":
397
+ msg = "couldn't find matching opcode for 'invert"
398
+ with pytest.raises(NotImplementedError, match=msg):
399
+ pd.eval(expr, engine=engine, parser=parser)
400
+ else:
401
+ expect = ~lhs
402
+ result = pd.eval(expr, engine=engine, parser=parser)
403
+ tm.assert_frame_equal(expect, result)
404
+
405
+ # bool always works
406
+ lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5)
407
+ expect = ~lhs
408
+ result = pd.eval(expr, engine=engine, parser=parser)
409
+ tm.assert_frame_equal(expect, result)
410
+
411
+ # object raises
412
+ lhs = DataFrame(
413
+ {"b": ["a", 1, 2.0], "c": np.random.default_rng(2).standard_normal(3) > 0.5}
414
+ )
415
+ if engine == "numexpr":
416
+ with pytest.raises(ValueError, match="unknown type object"):
417
+ pd.eval(expr, engine=engine, parser=parser)
418
+ else:
419
+ msg = "bad operand type for unary ~: 'str'"
420
+ with pytest.raises(TypeError, match=msg):
421
+ pd.eval(expr, engine=engine, parser=parser)
422
+
423
+ def test_series_invert(self, engine, parser):
424
+ # ~ ####
425
+ expr = "~lhs"
426
+
427
+ # series
428
+ # float raises
429
+ lhs = Series(np.random.default_rng(2).standard_normal(5))
430
+ if engine == "numexpr":
431
+ msg = "couldn't find matching opcode for 'invert_dd'"
432
+ with pytest.raises(NotImplementedError, match=msg):
433
+ result = pd.eval(expr, engine=engine, parser=parser)
434
+ else:
435
+ msg = "ufunc 'invert' not supported for the input types"
436
+ with pytest.raises(TypeError, match=msg):
437
+ pd.eval(expr, engine=engine, parser=parser)
438
+
439
+ # int raises on numexpr
440
+ lhs = Series(np.random.default_rng(2).integers(5, size=5))
441
+ if engine == "numexpr":
442
+ msg = "couldn't find matching opcode for 'invert"
443
+ with pytest.raises(NotImplementedError, match=msg):
444
+ pd.eval(expr, engine=engine, parser=parser)
445
+ else:
446
+ expect = ~lhs
447
+ result = pd.eval(expr, engine=engine, parser=parser)
448
+ tm.assert_series_equal(expect, result)
449
+
450
+ # bool
451
+ lhs = Series(np.random.default_rng(2).standard_normal(5) > 0.5)
452
+ expect = ~lhs
453
+ result = pd.eval(expr, engine=engine, parser=parser)
454
+ tm.assert_series_equal(expect, result)
455
+
456
+ # float
457
+ # int
458
+ # bool
459
+
460
+ # object
461
+ lhs = Series(["a", 1, 2.0])
462
+ if engine == "numexpr":
463
+ with pytest.raises(ValueError, match="unknown type object"):
464
+ pd.eval(expr, engine=engine, parser=parser)
465
+ else:
466
+ msg = "bad operand type for unary ~: 'str'"
467
+ with pytest.raises(TypeError, match=msg):
468
+ pd.eval(expr, engine=engine, parser=parser)
469
+
470
+ def test_frame_negate(self, engine, parser):
471
+ expr = "-lhs"
472
+
473
+ # float
474
+ lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)))
475
+ expect = -lhs
476
+ result = pd.eval(expr, engine=engine, parser=parser)
477
+ tm.assert_frame_equal(expect, result)
478
+
479
+ # int
480
+ lhs = DataFrame(np.random.default_rng(2).integers(5, size=(5, 2)))
481
+ expect = -lhs
482
+ result = pd.eval(expr, engine=engine, parser=parser)
483
+ tm.assert_frame_equal(expect, result)
484
+
485
+ # bool doesn't work with numexpr but works elsewhere
486
+ lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5)
487
+ if engine == "numexpr":
488
+ msg = "couldn't find matching opcode for 'neg_bb'"
489
+ with pytest.raises(NotImplementedError, match=msg):
490
+ pd.eval(expr, engine=engine, parser=parser)
491
+ else:
492
+ expect = -lhs
493
+ result = pd.eval(expr, engine=engine, parser=parser)
494
+ tm.assert_frame_equal(expect, result)
495
+
496
+ def test_series_negate(self, engine, parser):
497
+ expr = "-lhs"
498
+
499
+ # float
500
+ lhs = Series(np.random.default_rng(2).standard_normal(5))
501
+ expect = -lhs
502
+ result = pd.eval(expr, engine=engine, parser=parser)
503
+ tm.assert_series_equal(expect, result)
504
+
505
+ # int
506
+ lhs = Series(np.random.default_rng(2).integers(5, size=5))
507
+ expect = -lhs
508
+ result = pd.eval(expr, engine=engine, parser=parser)
509
+ tm.assert_series_equal(expect, result)
510
+
511
+ # bool doesn't work with numexpr but works elsewhere
512
+ lhs = Series(np.random.default_rng(2).standard_normal(5) > 0.5)
513
+ if engine == "numexpr":
514
+ msg = "couldn't find matching opcode for 'neg_bb'"
515
+ with pytest.raises(NotImplementedError, match=msg):
516
+ pd.eval(expr, engine=engine, parser=parser)
517
+ else:
518
+ expect = -lhs
519
+ result = pd.eval(expr, engine=engine, parser=parser)
520
+ tm.assert_series_equal(expect, result)
521
+
522
+ @pytest.mark.parametrize(
523
+ "lhs",
524
+ [
525
+ # Float
526
+ DataFrame(np.random.default_rng(2).standard_normal((5, 2))),
527
+ # Int
528
+ DataFrame(np.random.default_rng(2).integers(5, size=(5, 2))),
529
+ # bool doesn't work with numexpr but works elsewhere
530
+ DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5),
531
+ ],
532
+ )
533
+ def test_frame_pos(self, lhs, engine, parser):
534
+ expr = "+lhs"
535
+ expect = lhs
536
+
537
+ result = pd.eval(expr, engine=engine, parser=parser)
538
+ tm.assert_frame_equal(expect, result)
539
+
540
+ @pytest.mark.parametrize(
541
+ "lhs",
542
+ [
543
+ # Float
544
+ Series(np.random.default_rng(2).standard_normal(5)),
545
+ # Int
546
+ Series(np.random.default_rng(2).integers(5, size=5)),
547
+ # bool doesn't work with numexpr but works elsewhere
548
+ Series(np.random.default_rng(2).standard_normal(5) > 0.5),
549
+ ],
550
+ )
551
+ def test_series_pos(self, lhs, engine, parser):
552
+ expr = "+lhs"
553
+ expect = lhs
554
+
555
+ result = pd.eval(expr, engine=engine, parser=parser)
556
+ tm.assert_series_equal(expect, result)
557
+
558
+ def test_scalar_unary(self, engine, parser):
559
+ msg = "bad operand type for unary ~: 'float'"
560
+ warn = None
561
+ if PY312 and not (engine == "numexpr" and parser == "pandas"):
562
+ warn = DeprecationWarning
563
+ with pytest.raises(TypeError, match=msg):
564
+ pd.eval("~1.0", engine=engine, parser=parser)
565
+
566
+ assert pd.eval("-1.0", parser=parser, engine=engine) == -1.0
567
+ assert pd.eval("+1.0", parser=parser, engine=engine) == +1.0
568
+ assert pd.eval("~1", parser=parser, engine=engine) == ~1
569
+ assert pd.eval("-1", parser=parser, engine=engine) == -1
570
+ assert pd.eval("+1", parser=parser, engine=engine) == +1
571
+ with tm.assert_produces_warning(
572
+ warn, match="Bitwise inversion", check_stacklevel=False
573
+ ):
574
+ assert pd.eval("~True", parser=parser, engine=engine) == ~True
575
+ with tm.assert_produces_warning(
576
+ warn, match="Bitwise inversion", check_stacklevel=False
577
+ ):
578
+ assert pd.eval("~False", parser=parser, engine=engine) == ~False
579
+ assert pd.eval("-True", parser=parser, engine=engine) == -True
580
+ assert pd.eval("-False", parser=parser, engine=engine) == -False
581
+ assert pd.eval("+True", parser=parser, engine=engine) == +True
582
+ assert pd.eval("+False", parser=parser, engine=engine) == +False
583
+
584
+ def test_unary_in_array(self):
585
+ # GH 11235
586
+ # TODO: 2022-01-29: result return list with numexpr 2.7.3 in CI
587
+ # but cannot reproduce locally
588
+ result = np.array(
589
+ pd.eval("[-True, True, +True, -False, False, +False, -37, 37, ~37, +37]"),
590
+ dtype=np.object_,
591
+ )
592
+ expected = np.array(
593
+ [
594
+ -True,
595
+ True,
596
+ +True,
597
+ -False,
598
+ False,
599
+ +False,
600
+ -37,
601
+ 37,
602
+ ~37,
603
+ +37,
604
+ ],
605
+ dtype=np.object_,
606
+ )
607
+ tm.assert_numpy_array_equal(result, expected)
608
+
609
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64])
610
+ @pytest.mark.parametrize("expr", ["x < -0.1", "-5 > x"])
611
+ def test_float_comparison_bin_op(self, dtype, expr):
612
+ # GH 16363
613
+ df = DataFrame({"x": np.array([0], dtype=dtype)})
614
+ res = df.eval(expr)
615
+ assert res.values == np.array([False])
616
+
617
+ def test_unary_in_function(self):
618
+ # GH 46471
619
+ df = DataFrame({"x": [0, 1, np.nan]})
620
+
621
+ result = df.eval("x.fillna(-1)")
622
+ expected = df.x.fillna(-1)
623
+ # column name becomes None if using numexpr
624
+ # only check names when the engine is not numexpr
625
+ tm.assert_series_equal(result, expected, check_names=not USE_NUMEXPR)
626
+
627
+ result = df.eval("x.shift(1, fill_value=-1)")
628
+ expected = df.x.shift(1, fill_value=-1)
629
+ tm.assert_series_equal(result, expected, check_names=not USE_NUMEXPR)
630
+
631
+ @pytest.mark.parametrize(
632
+ "ex",
633
+ (
634
+ "1 or 2",
635
+ "1 and 2",
636
+ "a and b",
637
+ "a or b",
638
+ "1 or 2 and (3 + 2) > 3",
639
+ "2 * x > 2 or 1 and 2",
640
+ "2 * df > 3 and 1 or a",
641
+ ),
642
+ )
643
+ def test_disallow_scalar_bool_ops(self, ex, engine, parser):
644
+ x, a, b = np.random.default_rng(2).standard_normal(3), 1, 2 # noqa: F841
645
+ df = DataFrame(np.random.default_rng(2).standard_normal((3, 2))) # noqa: F841
646
+
647
+ msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not"
648
+ with pytest.raises(NotImplementedError, match=msg):
649
+ pd.eval(ex, engine=engine, parser=parser)
650
+
651
+ def test_identical(self, engine, parser):
652
+ # see gh-10546
653
+ x = 1
654
+ result = pd.eval("x", engine=engine, parser=parser)
655
+ assert result == 1
656
+ assert is_scalar(result)
657
+
658
+ x = 1.5
659
+ result = pd.eval("x", engine=engine, parser=parser)
660
+ assert result == 1.5
661
+ assert is_scalar(result)
662
+
663
+ x = False
664
+ result = pd.eval("x", engine=engine, parser=parser)
665
+ assert not result
666
+ assert is_bool(result)
667
+ assert is_scalar(result)
668
+
669
+ x = np.array([1])
670
+ result = pd.eval("x", engine=engine, parser=parser)
671
+ tm.assert_numpy_array_equal(result, np.array([1]))
672
+ assert result.shape == (1,)
673
+
674
+ x = np.array([1.5])
675
+ result = pd.eval("x", engine=engine, parser=parser)
676
+ tm.assert_numpy_array_equal(result, np.array([1.5]))
677
+ assert result.shape == (1,)
678
+
679
+ x = np.array([False]) # noqa: F841
680
+ result = pd.eval("x", engine=engine, parser=parser)
681
+ tm.assert_numpy_array_equal(result, np.array([False]))
682
+ assert result.shape == (1,)
683
+
684
+ def test_line_continuation(self, engine, parser):
685
+ # GH 11149
686
+ exp = """1 + 2 * \
687
+ 5 - 1 + 2 """
688
+ result = pd.eval(exp, engine=engine, parser=parser)
689
+ assert result == 12
690
+
691
+ def test_float_truncation(self, engine, parser):
692
+ # GH 14241
693
+ exp = "1000000000.006"
694
+ result = pd.eval(exp, engine=engine, parser=parser)
695
+ expected = np.float64(exp)
696
+ assert result == expected
697
+
698
+ df = DataFrame({"A": [1000000000.0009, 1000000000.0011, 1000000000.0015]})
699
+ cutoff = 1000000000.0006
700
+ result = df.query(f"A < {cutoff:.4f}")
701
+ assert result.empty
702
+
703
+ cutoff = 1000000000.0010
704
+ result = df.query(f"A > {cutoff:.4f}")
705
+ expected = df.loc[[1, 2], :]
706
+ tm.assert_frame_equal(expected, result)
707
+
708
+ exact = 1000000000.0011
709
+ result = df.query(f"A == {exact:.4f}")
710
+ expected = df.loc[[1], :]
711
+ tm.assert_frame_equal(expected, result)
712
+
713
+ def test_disallow_python_keywords(self):
714
+ # GH 18221
715
+ df = DataFrame([[0, 0, 0]], columns=["foo", "bar", "class"])
716
+ msg = "Python keyword not valid identifier in numexpr query"
717
+ with pytest.raises(SyntaxError, match=msg):
718
+ df.query("class == 0")
719
+
720
+ df = DataFrame()
721
+ df.index.name = "lambda"
722
+ with pytest.raises(SyntaxError, match=msg):
723
+ df.query("lambda == 0")
724
+
725
+ def test_true_false_logic(self):
726
+ # GH 25823
727
+ # This behavior is deprecated in Python 3.12
728
+ with tm.maybe_produces_warning(
729
+ DeprecationWarning, PY312, check_stacklevel=False
730
+ ):
731
+ assert pd.eval("not True") == -2
732
+ assert pd.eval("not False") == -1
733
+ assert pd.eval("True and not True") == 0
734
+
735
+ def test_and_logic_string_match(self):
736
+ # GH 25823
737
+ event = Series({"a": "hello"})
738
+ assert pd.eval(f"{event.str.match('hello').a}")
739
+ assert pd.eval(f"{event.str.match('hello').a and event.str.match('hello').a}")
740
+
741
+
742
+ # -------------------------------------
743
+ # gh-12388: Typecasting rules consistency with python
744
+
745
+
746
+ class TestTypeCasting:
747
+ @pytest.mark.parametrize("op", ["+", "-", "*", "**", "/"])
748
+ # maybe someday... numexpr has too many upcasting rules now
749
+ # chain(*(np.core.sctypes[x] for x in ['uint', 'int', 'float']))
750
+ @pytest.mark.parametrize("dt", [np.float32, np.float64])
751
+ @pytest.mark.parametrize("left_right", [("df", "3"), ("3", "df")])
752
+ def test_binop_typecasting(self, engine, parser, op, dt, left_right):
753
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), dtype=dt)
754
+ left, right = left_right
755
+ s = f"{left} {op} {right}"
756
+ res = pd.eval(s, engine=engine, parser=parser)
757
+ assert df.values.dtype == dt
758
+ assert res.values.dtype == dt
759
+ tm.assert_frame_equal(res, eval(s))
760
+
761
+
762
+ # -------------------------------------
763
+ # Basic and complex alignment
764
+
765
+
766
+ def should_warn(*args):
767
+ not_mono = not any(map(operator.attrgetter("is_monotonic_increasing"), args))
768
+ only_one_dt = reduce(
769
+ operator.xor, (issubclass(x.dtype.type, np.datetime64) for x in args)
770
+ )
771
+ return not_mono and only_one_dt
772
+
773
+
774
+ class TestAlignment:
775
+ index_types = ["i", "s", "dt"]
776
+ lhs_index_types = index_types + ["s"] # 'p'
777
+
778
+ def test_align_nested_unary_op(self, engine, parser):
779
+ s = "df * ~2"
780
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
781
+ res = pd.eval(s, engine=engine, parser=parser)
782
+ tm.assert_frame_equal(res, df * ~2)
783
+
784
+ @pytest.mark.filterwarnings("always::RuntimeWarning")
785
+ @pytest.mark.parametrize("lr_idx_type", lhs_index_types)
786
+ @pytest.mark.parametrize("rr_idx_type", index_types)
787
+ @pytest.mark.parametrize("c_idx_type", index_types)
788
+ def test_basic_frame_alignment(
789
+ self, engine, parser, lr_idx_type, rr_idx_type, c_idx_type, idx_func_dict
790
+ ):
791
+ df = DataFrame(
792
+ np.random.default_rng(2).standard_normal((10, 10)),
793
+ index=idx_func_dict[lr_idx_type](10),
794
+ columns=idx_func_dict[c_idx_type](10),
795
+ )
796
+ df2 = DataFrame(
797
+ np.random.default_rng(2).standard_normal((20, 10)),
798
+ index=idx_func_dict[rr_idx_type](20),
799
+ columns=idx_func_dict[c_idx_type](10),
800
+ )
801
+ # only warns if not monotonic and not sortable
802
+ if should_warn(df.index, df2.index):
803
+ with tm.assert_produces_warning(RuntimeWarning):
804
+ res = pd.eval("df + df2", engine=engine, parser=parser)
805
+ else:
806
+ res = pd.eval("df + df2", engine=engine, parser=parser)
807
+ tm.assert_frame_equal(res, df + df2)
808
+
809
+ @pytest.mark.parametrize("r_idx_type", lhs_index_types)
810
+ @pytest.mark.parametrize("c_idx_type", lhs_index_types)
811
+ def test_frame_comparison(
812
+ self, engine, parser, r_idx_type, c_idx_type, idx_func_dict
813
+ ):
814
+ df = DataFrame(
815
+ np.random.default_rng(2).standard_normal((10, 10)),
816
+ index=idx_func_dict[r_idx_type](10),
817
+ columns=idx_func_dict[c_idx_type](10),
818
+ )
819
+ res = pd.eval("df < 2", engine=engine, parser=parser)
820
+ tm.assert_frame_equal(res, df < 2)
821
+
822
+ df3 = DataFrame(
823
+ np.random.default_rng(2).standard_normal(df.shape),
824
+ index=df.index,
825
+ columns=df.columns,
826
+ )
827
+ res = pd.eval("df < df3", engine=engine, parser=parser)
828
+ tm.assert_frame_equal(res, df < df3)
829
+
830
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
831
+ @pytest.mark.parametrize("r1", lhs_index_types)
832
+ @pytest.mark.parametrize("c1", index_types)
833
+ @pytest.mark.parametrize("r2", index_types)
834
+ @pytest.mark.parametrize("c2", index_types)
835
+ def test_medium_complex_frame_alignment(
836
+ self, engine, parser, r1, c1, r2, c2, idx_func_dict
837
+ ):
838
+ df = DataFrame(
839
+ np.random.default_rng(2).standard_normal((3, 2)),
840
+ index=idx_func_dict[r1](3),
841
+ columns=idx_func_dict[c1](2),
842
+ )
843
+ df2 = DataFrame(
844
+ np.random.default_rng(2).standard_normal((4, 2)),
845
+ index=idx_func_dict[r2](4),
846
+ columns=idx_func_dict[c2](2),
847
+ )
848
+ df3 = DataFrame(
849
+ np.random.default_rng(2).standard_normal((5, 2)),
850
+ index=idx_func_dict[r2](5),
851
+ columns=idx_func_dict[c2](2),
852
+ )
853
+ if should_warn(df.index, df2.index, df3.index):
854
+ with tm.assert_produces_warning(RuntimeWarning):
855
+ res = pd.eval("df + df2 + df3", engine=engine, parser=parser)
856
+ else:
857
+ res = pd.eval("df + df2 + df3", engine=engine, parser=parser)
858
+ tm.assert_frame_equal(res, df + df2 + df3)
859
+
860
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
861
+ @pytest.mark.parametrize("index_name", ["index", "columns"])
862
+ @pytest.mark.parametrize("c_idx_type", index_types)
863
+ @pytest.mark.parametrize("r_idx_type", lhs_index_types)
864
+ def test_basic_frame_series_alignment(
865
+ self, engine, parser, index_name, r_idx_type, c_idx_type, idx_func_dict
866
+ ):
867
+ df = DataFrame(
868
+ np.random.default_rng(2).standard_normal((10, 10)),
869
+ index=idx_func_dict[r_idx_type](10),
870
+ columns=idx_func_dict[c_idx_type](10),
871
+ )
872
+ index = getattr(df, index_name)
873
+ s = Series(np.random.default_rng(2).standard_normal(5), index[:5])
874
+
875
+ if should_warn(df.index, s.index):
876
+ with tm.assert_produces_warning(RuntimeWarning):
877
+ res = pd.eval("df + s", engine=engine, parser=parser)
878
+ else:
879
+ res = pd.eval("df + s", engine=engine, parser=parser)
880
+
881
+ if r_idx_type == "dt" or c_idx_type == "dt":
882
+ expected = df.add(s) if engine == "numexpr" else df + s
883
+ else:
884
+ expected = df + s
885
+ tm.assert_frame_equal(res, expected)
886
+
887
+ @pytest.mark.parametrize("index_name", ["index", "columns"])
888
+ @pytest.mark.parametrize(
889
+ "r_idx_type, c_idx_type",
890
+ list(product(["i", "s"], ["i", "s"])) + [("dt", "dt")],
891
+ )
892
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
893
+ def test_basic_series_frame_alignment(
894
+ self, request, engine, parser, index_name, r_idx_type, c_idx_type, idx_func_dict
895
+ ):
896
+ if (
897
+ engine == "numexpr"
898
+ and parser in ("pandas", "python")
899
+ and index_name == "index"
900
+ and r_idx_type == "i"
901
+ and c_idx_type == "s"
902
+ ):
903
+ reason = (
904
+ f"Flaky column ordering when engine={engine}, "
905
+ f"parser={parser}, index_name={index_name}, "
906
+ f"r_idx_type={r_idx_type}, c_idx_type={c_idx_type}"
907
+ )
908
+ request.applymarker(pytest.mark.xfail(reason=reason, strict=False))
909
+ df = DataFrame(
910
+ np.random.default_rng(2).standard_normal((10, 7)),
911
+ index=idx_func_dict[r_idx_type](10),
912
+ columns=idx_func_dict[c_idx_type](7),
913
+ )
914
+ index = getattr(df, index_name)
915
+ s = Series(np.random.default_rng(2).standard_normal(5), index[:5])
916
+ if should_warn(s.index, df.index):
917
+ with tm.assert_produces_warning(RuntimeWarning):
918
+ res = pd.eval("s + df", engine=engine, parser=parser)
919
+ else:
920
+ res = pd.eval("s + df", engine=engine, parser=parser)
921
+
922
+ if r_idx_type == "dt" or c_idx_type == "dt":
923
+ expected = df.add(s) if engine == "numexpr" else s + df
924
+ else:
925
+ expected = s + df
926
+ tm.assert_frame_equal(res, expected)
927
+
928
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
929
+ @pytest.mark.parametrize("c_idx_type", index_types)
930
+ @pytest.mark.parametrize("r_idx_type", lhs_index_types)
931
+ @pytest.mark.parametrize("index_name", ["index", "columns"])
932
+ @pytest.mark.parametrize("op", ["+", "*"])
933
+ def test_series_frame_commutativity(
934
+ self, engine, parser, index_name, op, r_idx_type, c_idx_type, idx_func_dict
935
+ ):
936
+ df = DataFrame(
937
+ np.random.default_rng(2).standard_normal((10, 10)),
938
+ index=idx_func_dict[r_idx_type](10),
939
+ columns=idx_func_dict[c_idx_type](10),
940
+ )
941
+ index = getattr(df, index_name)
942
+ s = Series(np.random.default_rng(2).standard_normal(5), index[:5])
943
+
944
+ lhs = f"s {op} df"
945
+ rhs = f"df {op} s"
946
+ if should_warn(df.index, s.index):
947
+ with tm.assert_produces_warning(RuntimeWarning):
948
+ a = pd.eval(lhs, engine=engine, parser=parser)
949
+ with tm.assert_produces_warning(RuntimeWarning):
950
+ b = pd.eval(rhs, engine=engine, parser=parser)
951
+ else:
952
+ a = pd.eval(lhs, engine=engine, parser=parser)
953
+ b = pd.eval(rhs, engine=engine, parser=parser)
954
+
955
+ if r_idx_type != "dt" and c_idx_type != "dt":
956
+ if engine == "numexpr":
957
+ tm.assert_frame_equal(a, b)
958
+
959
+ @pytest.mark.filterwarnings("always::RuntimeWarning")
960
+ @pytest.mark.parametrize("r1", lhs_index_types)
961
+ @pytest.mark.parametrize("c1", index_types)
962
+ @pytest.mark.parametrize("r2", index_types)
963
+ @pytest.mark.parametrize("c2", index_types)
964
+ def test_complex_series_frame_alignment(
965
+ self, engine, parser, r1, c1, r2, c2, idx_func_dict
966
+ ):
967
+ n = 3
968
+ m1 = 5
969
+ m2 = 2 * m1
970
+ df = DataFrame(
971
+ np.random.default_rng(2).standard_normal((m1, n)),
972
+ index=idx_func_dict[r1](m1),
973
+ columns=idx_func_dict[c1](n),
974
+ )
975
+ df2 = DataFrame(
976
+ np.random.default_rng(2).standard_normal((m2, n)),
977
+ index=idx_func_dict[r2](m2),
978
+ columns=idx_func_dict[c2](n),
979
+ )
980
+ index = df2.columns
981
+ ser = Series(np.random.default_rng(2).standard_normal(n), index[:n])
982
+
983
+ if r2 == "dt" or c2 == "dt":
984
+ if engine == "numexpr":
985
+ expected2 = df2.add(ser)
986
+ else:
987
+ expected2 = df2 + ser
988
+ else:
989
+ expected2 = df2 + ser
990
+
991
+ if r1 == "dt" or c1 == "dt":
992
+ if engine == "numexpr":
993
+ expected = expected2.add(df)
994
+ else:
995
+ expected = expected2 + df
996
+ else:
997
+ expected = expected2 + df
998
+
999
+ if should_warn(df2.index, ser.index, df.index):
1000
+ with tm.assert_produces_warning(RuntimeWarning):
1001
+ res = pd.eval("df2 + ser + df", engine=engine, parser=parser)
1002
+ else:
1003
+ res = pd.eval("df2 + ser + df", engine=engine, parser=parser)
1004
+ assert res.shape == expected.shape
1005
+ tm.assert_frame_equal(res, expected)
1006
+
1007
+ def test_performance_warning_for_poor_alignment(self, engine, parser):
1008
+ df = DataFrame(np.random.default_rng(2).standard_normal((1000, 10)))
1009
+ s = Series(np.random.default_rng(2).standard_normal(10000))
1010
+ if engine == "numexpr":
1011
+ seen = PerformanceWarning
1012
+ else:
1013
+ seen = False
1014
+
1015
+ with tm.assert_produces_warning(seen):
1016
+ pd.eval("df + s", engine=engine, parser=parser)
1017
+
1018
+ s = Series(np.random.default_rng(2).standard_normal(1000))
1019
+ with tm.assert_produces_warning(False):
1020
+ pd.eval("df + s", engine=engine, parser=parser)
1021
+
1022
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 10000)))
1023
+ s = Series(np.random.default_rng(2).standard_normal(10000))
1024
+ with tm.assert_produces_warning(False):
1025
+ pd.eval("df + s", engine=engine, parser=parser)
1026
+
1027
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 10)))
1028
+ s = Series(np.random.default_rng(2).standard_normal(10000))
1029
+
1030
+ is_python_engine = engine == "python"
1031
+
1032
+ if not is_python_engine:
1033
+ wrn = PerformanceWarning
1034
+ else:
1035
+ wrn = False
1036
+
1037
+ with tm.assert_produces_warning(wrn) as w:
1038
+ pd.eval("df + s", engine=engine, parser=parser)
1039
+
1040
+ if not is_python_engine:
1041
+ assert len(w) == 1
1042
+ msg = str(w[0].message)
1043
+ logged = np.log10(s.size - df.shape[1])
1044
+ expected = (
1045
+ f"Alignment difference on axis 1 is larger "
1046
+ f"than an order of magnitude on term 'df', "
1047
+ f"by more than {logged:.4g}; performance may suffer."
1048
+ )
1049
+ assert msg == expected
1050
+
1051
+
1052
+ # ------------------------------------
1053
+ # Slightly more complex ops
1054
+
1055
+
1056
+ class TestOperations:
1057
+ def eval(self, *args, **kwargs):
1058
+ kwargs["level"] = kwargs.pop("level", 0) + 1
1059
+ return pd.eval(*args, **kwargs)
1060
+
1061
+ def test_simple_arith_ops(self, engine, parser):
1062
+ exclude_arith = []
1063
+ if parser == "python":
1064
+ exclude_arith = ["in", "not in"]
1065
+
1066
+ arith_ops = [
1067
+ op
1068
+ for op in expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS
1069
+ if op not in exclude_arith
1070
+ ]
1071
+
1072
+ ops = (op for op in arith_ops if op != "//")
1073
+
1074
+ for op in ops:
1075
+ ex = f"1 {op} 1"
1076
+ ex2 = f"x {op} 1"
1077
+ ex3 = f"1 {op} (x + 1)"
1078
+
1079
+ if op in ("in", "not in"):
1080
+ msg = "argument of type 'int' is not iterable"
1081
+ with pytest.raises(TypeError, match=msg):
1082
+ pd.eval(ex, engine=engine, parser=parser)
1083
+ else:
1084
+ expec = _eval_single_bin(1, op, 1, engine)
1085
+ x = self.eval(ex, engine=engine, parser=parser)
1086
+ assert x == expec
1087
+
1088
+ expec = _eval_single_bin(x, op, 1, engine)
1089
+ y = self.eval(ex2, local_dict={"x": x}, engine=engine, parser=parser)
1090
+ assert y == expec
1091
+
1092
+ expec = _eval_single_bin(1, op, x + 1, engine)
1093
+ y = self.eval(ex3, local_dict={"x": x}, engine=engine, parser=parser)
1094
+ assert y == expec
1095
+
1096
+ @pytest.mark.parametrize("rhs", [True, False])
1097
+ @pytest.mark.parametrize("lhs", [True, False])
1098
+ @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS)
1099
+ def test_simple_bool_ops(self, rhs, lhs, op):
1100
+ ex = f"{lhs} {op} {rhs}"
1101
+
1102
+ if parser == "python" and op in ["and", "or"]:
1103
+ msg = "'BoolOp' nodes are not implemented"
1104
+ with pytest.raises(NotImplementedError, match=msg):
1105
+ self.eval(ex)
1106
+ return
1107
+
1108
+ res = self.eval(ex)
1109
+ exp = eval(ex)
1110
+ assert res == exp
1111
+
1112
+ @pytest.mark.parametrize("rhs", [True, False])
1113
+ @pytest.mark.parametrize("lhs", [True, False])
1114
+ @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS)
1115
+ def test_bool_ops_with_constants(self, rhs, lhs, op):
1116
+ ex = f"{lhs} {op} {rhs}"
1117
+
1118
+ if parser == "python" and op in ["and", "or"]:
1119
+ msg = "'BoolOp' nodes are not implemented"
1120
+ with pytest.raises(NotImplementedError, match=msg):
1121
+ self.eval(ex)
1122
+ return
1123
+
1124
+ res = self.eval(ex)
1125
+ exp = eval(ex)
1126
+ assert res == exp
1127
+
1128
+ def test_4d_ndarray_fails(self):
1129
+ x = np.random.default_rng(2).standard_normal((3, 4, 5, 6))
1130
+ y = Series(np.random.default_rng(2).standard_normal(10))
1131
+ msg = "N-dimensional objects, where N > 2, are not supported with eval"
1132
+ with pytest.raises(NotImplementedError, match=msg):
1133
+ self.eval("x + y", local_dict={"x": x, "y": y})
1134
+
1135
+ def test_constant(self):
1136
+ x = self.eval("1")
1137
+ assert x == 1
1138
+
1139
+ def test_single_variable(self):
1140
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
1141
+ df2 = self.eval("df", local_dict={"df": df})
1142
+ tm.assert_frame_equal(df, df2)
1143
+
1144
+ def test_failing_subscript_with_name_error(self):
1145
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # noqa: F841
1146
+ with pytest.raises(NameError, match="name 'x' is not defined"):
1147
+ self.eval("df[x > 2] > 2")
1148
+
1149
+ def test_lhs_expression_subscript(self):
1150
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
1151
+ result = self.eval("(df + 1)[df > 2]", local_dict={"df": df})
1152
+ expected = (df + 1)[df > 2]
1153
+ tm.assert_frame_equal(result, expected)
1154
+
1155
+ def test_attr_expression(self):
1156
+ df = DataFrame(
1157
+ np.random.default_rng(2).standard_normal((5, 3)), columns=list("abc")
1158
+ )
1159
+ expr1 = "df.a < df.b"
1160
+ expec1 = df.a < df.b
1161
+ expr2 = "df.a + df.b + df.c"
1162
+ expec2 = df.a + df.b + df.c
1163
+ expr3 = "df.a + df.b + df.c[df.b < 0]"
1164
+ expec3 = df.a + df.b + df.c[df.b < 0]
1165
+ exprs = expr1, expr2, expr3
1166
+ expecs = expec1, expec2, expec3
1167
+ for e, expec in zip(exprs, expecs):
1168
+ tm.assert_series_equal(expec, self.eval(e, local_dict={"df": df}))
1169
+
1170
+ def test_assignment_fails(self):
1171
+ df = DataFrame(
1172
+ np.random.default_rng(2).standard_normal((5, 3)), columns=list("abc")
1173
+ )
1174
+ df2 = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
1175
+ expr1 = "df = df2"
1176
+ msg = "cannot assign without a target object"
1177
+ with pytest.raises(ValueError, match=msg):
1178
+ self.eval(expr1, local_dict={"df": df, "df2": df2})
1179
+
1180
+ def test_assignment_column_multiple_raise(self):
1181
+ df = DataFrame(
1182
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1183
+ )
1184
+ # multiple assignees
1185
+ with pytest.raises(SyntaxError, match="invalid syntax"):
1186
+ df.eval("d c = a + b")
1187
+
1188
+ def test_assignment_column_invalid_assign(self):
1189
+ df = DataFrame(
1190
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1191
+ )
1192
+ # invalid assignees
1193
+ msg = "left hand side of an assignment must be a single name"
1194
+ with pytest.raises(SyntaxError, match=msg):
1195
+ df.eval("d,c = a + b")
1196
+
1197
+ def test_assignment_column_invalid_assign_function_call(self):
1198
+ df = DataFrame(
1199
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1200
+ )
1201
+ msg = "cannot assign to function call"
1202
+ with pytest.raises(SyntaxError, match=msg):
1203
+ df.eval('Timestamp("20131001") = a + b')
1204
+
1205
+ def test_assignment_single_assign_existing(self):
1206
+ df = DataFrame(
1207
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1208
+ )
1209
+ # single assignment - existing variable
1210
+ expected = df.copy()
1211
+ expected["a"] = expected["a"] + expected["b"]
1212
+ df.eval("a = a + b", inplace=True)
1213
+ tm.assert_frame_equal(df, expected)
1214
+
1215
+ def test_assignment_single_assign_new(self):
1216
+ df = DataFrame(
1217
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1218
+ )
1219
+ # single assignment - new variable
1220
+ expected = df.copy()
1221
+ expected["c"] = expected["a"] + expected["b"]
1222
+ df.eval("c = a + b", inplace=True)
1223
+ tm.assert_frame_equal(df, expected)
1224
+
1225
+ def test_assignment_single_assign_local_overlap(self):
1226
+ df = DataFrame(
1227
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1228
+ )
1229
+ df = df.copy()
1230
+ a = 1 # noqa: F841
1231
+ df.eval("a = 1 + b", inplace=True)
1232
+
1233
+ expected = df.copy()
1234
+ expected["a"] = 1 + expected["b"]
1235
+ tm.assert_frame_equal(df, expected)
1236
+
1237
+ def test_assignment_single_assign_name(self):
1238
+ df = DataFrame(
1239
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1240
+ )
1241
+
1242
+ a = 1 # noqa: F841
1243
+ old_a = df.a.copy()
1244
+ df.eval("a = a + b", inplace=True)
1245
+ result = old_a + df.b
1246
+ tm.assert_series_equal(result, df.a, check_names=False)
1247
+ assert result.name is None
1248
+
1249
+ def test_assignment_multiple_raises(self):
1250
+ df = DataFrame(
1251
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1252
+ )
1253
+ # multiple assignment
1254
+ df.eval("c = a + b", inplace=True)
1255
+ msg = "can only assign a single expression"
1256
+ with pytest.raises(SyntaxError, match=msg):
1257
+ df.eval("c = a = b")
1258
+
1259
+ def test_assignment_explicit(self):
1260
+ df = DataFrame(
1261
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1262
+ )
1263
+ # explicit targets
1264
+ self.eval("c = df.a + df.b", local_dict={"df": df}, target=df, inplace=True)
1265
+ expected = df.copy()
1266
+ expected["c"] = expected["a"] + expected["b"]
1267
+ tm.assert_frame_equal(df, expected)
1268
+
1269
+ def test_column_in(self):
1270
+ # GH 11235
1271
+ df = DataFrame({"a": [11], "b": [-32]})
1272
+ result = df.eval("a in [11, -32]")
1273
+ expected = Series([True])
1274
+ # TODO: 2022-01-29: Name check failed with numexpr 2.7.3 in CI
1275
+ # but cannot reproduce locally
1276
+ tm.assert_series_equal(result, expected, check_names=False)
1277
+
1278
+ @pytest.mark.xfail(reason="Unknown: Omitted test_ in name prior.")
1279
+ def test_assignment_not_inplace(self):
1280
+ # see gh-9297
1281
+ df = DataFrame(
1282
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
1283
+ )
1284
+
1285
+ actual = df.eval("c = a + b", inplace=False)
1286
+ assert actual is not None
1287
+
1288
+ expected = df.copy()
1289
+ expected["c"] = expected["a"] + expected["b"]
1290
+ tm.assert_frame_equal(df, expected)
1291
+
1292
+ def test_multi_line_expression(self, warn_copy_on_write):
1293
+ # GH 11149
1294
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
1295
+ expected = df.copy()
1296
+
1297
+ expected["c"] = expected["a"] + expected["b"]
1298
+ expected["d"] = expected["c"] + expected["b"]
1299
+ answer = df.eval(
1300
+ """
1301
+ c = a + b
1302
+ d = c + b""",
1303
+ inplace=True,
1304
+ )
1305
+ tm.assert_frame_equal(expected, df)
1306
+ assert answer is None
1307
+
1308
+ expected["a"] = expected["a"] - 1
1309
+ expected["e"] = expected["a"] + 2
1310
+ answer = df.eval(
1311
+ """
1312
+ a = a - 1
1313
+ e = a + 2""",
1314
+ inplace=True,
1315
+ )
1316
+ tm.assert_frame_equal(expected, df)
1317
+ assert answer is None
1318
+
1319
+ # multi-line not valid if not all assignments
1320
+ msg = "Multi-line expressions are only valid if all expressions contain"
1321
+ with pytest.raises(ValueError, match=msg):
1322
+ df.eval(
1323
+ """
1324
+ a = b + 2
1325
+ b - 2""",
1326
+ inplace=False,
1327
+ )
1328
+
1329
+ def test_multi_line_expression_not_inplace(self):
1330
+ # GH 11149
1331
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
1332
+ expected = df.copy()
1333
+
1334
+ expected["c"] = expected["a"] + expected["b"]
1335
+ expected["d"] = expected["c"] + expected["b"]
1336
+ df = df.eval(
1337
+ """
1338
+ c = a + b
1339
+ d = c + b""",
1340
+ inplace=False,
1341
+ )
1342
+ tm.assert_frame_equal(expected, df)
1343
+
1344
+ expected["a"] = expected["a"] - 1
1345
+ expected["e"] = expected["a"] + 2
1346
+ df = df.eval(
1347
+ """
1348
+ a = a - 1
1349
+ e = a + 2""",
1350
+ inplace=False,
1351
+ )
1352
+ tm.assert_frame_equal(expected, df)
1353
+
1354
+ def test_multi_line_expression_local_variable(self):
1355
+ # GH 15342
1356
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
1357
+ expected = df.copy()
1358
+
1359
+ local_var = 7
1360
+ expected["c"] = expected["a"] * local_var
1361
+ expected["d"] = expected["c"] + local_var
1362
+ answer = df.eval(
1363
+ """
1364
+ c = a * @local_var
1365
+ d = c + @local_var
1366
+ """,
1367
+ inplace=True,
1368
+ )
1369
+ tm.assert_frame_equal(expected, df)
1370
+ assert answer is None
1371
+
1372
+ def test_multi_line_expression_callable_local_variable(self):
1373
+ # 26426
1374
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
1375
+
1376
+ def local_func(a, b):
1377
+ return b
1378
+
1379
+ expected = df.copy()
1380
+ expected["c"] = expected["a"] * local_func(1, 7)
1381
+ expected["d"] = expected["c"] + local_func(1, 7)
1382
+ answer = df.eval(
1383
+ """
1384
+ c = a * @local_func(1, 7)
1385
+ d = c + @local_func(1, 7)
1386
+ """,
1387
+ inplace=True,
1388
+ )
1389
+ tm.assert_frame_equal(expected, df)
1390
+ assert answer is None
1391
+
1392
+ def test_multi_line_expression_callable_local_variable_with_kwargs(self):
1393
+ # 26426
1394
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
1395
+
1396
+ def local_func(a, b):
1397
+ return b
1398
+
1399
+ expected = df.copy()
1400
+ expected["c"] = expected["a"] * local_func(b=7, a=1)
1401
+ expected["d"] = expected["c"] + local_func(b=7, a=1)
1402
+ answer = df.eval(
1403
+ """
1404
+ c = a * @local_func(b=7, a=1)
1405
+ d = c + @local_func(b=7, a=1)
1406
+ """,
1407
+ inplace=True,
1408
+ )
1409
+ tm.assert_frame_equal(expected, df)
1410
+ assert answer is None
1411
+
1412
+ def test_assignment_in_query(self):
1413
+ # GH 8664
1414
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
1415
+ df_orig = df.copy()
1416
+ msg = "cannot assign without a target object"
1417
+ with pytest.raises(ValueError, match=msg):
1418
+ df.query("a = 1")
1419
+ tm.assert_frame_equal(df, df_orig)
1420
+
1421
+ def test_query_inplace(self):
1422
+ # see gh-11149
1423
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
1424
+ expected = df.copy()
1425
+ expected = expected[expected["a"] == 2]
1426
+ df.query("a == 2", inplace=True)
1427
+ tm.assert_frame_equal(expected, df)
1428
+
1429
+ df = {}
1430
+ expected = {"a": 3}
1431
+
1432
+ self.eval("a = 1 + 2", target=df, inplace=True)
1433
+ tm.assert_dict_equal(df, expected)
1434
+
1435
+ @pytest.mark.parametrize("invalid_target", [1, "cat", [1, 2], np.array([]), (1, 3)])
1436
+ def test_cannot_item_assign(self, invalid_target):
1437
+ msg = "Cannot assign expression output to target"
1438
+ expression = "a = 1 + 2"
1439
+
1440
+ with pytest.raises(ValueError, match=msg):
1441
+ self.eval(expression, target=invalid_target, inplace=True)
1442
+
1443
+ if hasattr(invalid_target, "copy"):
1444
+ with pytest.raises(ValueError, match=msg):
1445
+ self.eval(expression, target=invalid_target, inplace=False)
1446
+
1447
+ @pytest.mark.parametrize("invalid_target", [1, "cat", (1, 3)])
1448
+ def test_cannot_copy_item(self, invalid_target):
1449
+ msg = "Cannot return a copy of the target"
1450
+ expression = "a = 1 + 2"
1451
+
1452
+ with pytest.raises(ValueError, match=msg):
1453
+ self.eval(expression, target=invalid_target, inplace=False)
1454
+
1455
+ @pytest.mark.parametrize("target", [1, "cat", [1, 2], np.array([]), (1, 3), {1: 2}])
1456
+ def test_inplace_no_assignment(self, target):
1457
+ expression = "1 + 2"
1458
+
1459
+ assert self.eval(expression, target=target, inplace=False) == 3
1460
+
1461
+ msg = "Cannot operate inplace if there is no assignment"
1462
+ with pytest.raises(ValueError, match=msg):
1463
+ self.eval(expression, target=target, inplace=True)
1464
+
1465
+ def test_basic_period_index_boolean_expression(self):
1466
+ df = DataFrame(
1467
+ np.random.default_rng(2).standard_normal((2, 2)),
1468
+ columns=period_range("2020-01-01", freq="D", periods=2),
1469
+ )
1470
+ e = df < 2
1471
+ r = self.eval("df < 2", local_dict={"df": df})
1472
+ x = df < 2
1473
+
1474
+ tm.assert_frame_equal(r, e)
1475
+ tm.assert_frame_equal(x, e)
1476
+
1477
+ def test_basic_period_index_subscript_expression(self):
1478
+ df = DataFrame(
1479
+ np.random.default_rng(2).standard_normal((2, 2)),
1480
+ columns=period_range("2020-01-01", freq="D", periods=2),
1481
+ )
1482
+ r = self.eval("df[df < 2 + 3]", local_dict={"df": df})
1483
+ e = df[df < 2 + 3]
1484
+ tm.assert_frame_equal(r, e)
1485
+
1486
+ def test_nested_period_index_subscript_expression(self):
1487
+ df = DataFrame(
1488
+ np.random.default_rng(2).standard_normal((2, 2)),
1489
+ columns=period_range("2020-01-01", freq="D", periods=2),
1490
+ )
1491
+ r = self.eval("df[df[df < 2] < 2] + df * 2", local_dict={"df": df})
1492
+ e = df[df[df < 2] < 2] + df * 2
1493
+ tm.assert_frame_equal(r, e)
1494
+
1495
+ def test_date_boolean(self, engine, parser):
1496
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
1497
+ df["dates1"] = date_range("1/1/2012", periods=5)
1498
+ res = self.eval(
1499
+ "df.dates1 < 20130101",
1500
+ local_dict={"df": df},
1501
+ engine=engine,
1502
+ parser=parser,
1503
+ )
1504
+ expec = df.dates1 < "20130101"
1505
+ tm.assert_series_equal(res, expec, check_names=False)
1506
+
1507
+ def test_simple_in_ops(self, engine, parser):
1508
+ if parser != "python":
1509
+ res = pd.eval("1 in [1, 2]", engine=engine, parser=parser)
1510
+ assert res
1511
+
1512
+ res = pd.eval("2 in (1, 2)", engine=engine, parser=parser)
1513
+ assert res
1514
+
1515
+ res = pd.eval("3 in (1, 2)", engine=engine, parser=parser)
1516
+ assert not res
1517
+
1518
+ res = pd.eval("3 not in (1, 2)", engine=engine, parser=parser)
1519
+ assert res
1520
+
1521
+ res = pd.eval("[3] not in (1, 2)", engine=engine, parser=parser)
1522
+ assert res
1523
+
1524
+ res = pd.eval("[3] in ([3], 2)", engine=engine, parser=parser)
1525
+ assert res
1526
+
1527
+ res = pd.eval("[[3]] in [[[3]], 2]", engine=engine, parser=parser)
1528
+ assert res
1529
+
1530
+ res = pd.eval("(3,) in [(3,), 2]", engine=engine, parser=parser)
1531
+ assert res
1532
+
1533
+ res = pd.eval("(3,) not in [(3,), 2]", engine=engine, parser=parser)
1534
+ assert not res
1535
+
1536
+ res = pd.eval("[(3,)] in [[(3,)], 2]", engine=engine, parser=parser)
1537
+ assert res
1538
+ else:
1539
+ msg = "'In' nodes are not implemented"
1540
+ with pytest.raises(NotImplementedError, match=msg):
1541
+ pd.eval("1 in [1, 2]", engine=engine, parser=parser)
1542
+ with pytest.raises(NotImplementedError, match=msg):
1543
+ pd.eval("2 in (1, 2)", engine=engine, parser=parser)
1544
+ with pytest.raises(NotImplementedError, match=msg):
1545
+ pd.eval("3 in (1, 2)", engine=engine, parser=parser)
1546
+ with pytest.raises(NotImplementedError, match=msg):
1547
+ pd.eval("[(3,)] in (1, 2, [(3,)])", engine=engine, parser=parser)
1548
+ msg = "'NotIn' nodes are not implemented"
1549
+ with pytest.raises(NotImplementedError, match=msg):
1550
+ pd.eval("3 not in (1, 2)", engine=engine, parser=parser)
1551
+ with pytest.raises(NotImplementedError, match=msg):
1552
+ pd.eval("[3] not in (1, 2, [[3]])", engine=engine, parser=parser)
1553
+
1554
+ def test_check_many_exprs(self, engine, parser):
1555
+ a = 1 # noqa: F841
1556
+ expr = " * ".join("a" * 33)
1557
+ expected = 1
1558
+ res = pd.eval(expr, engine=engine, parser=parser)
1559
+ assert res == expected
1560
+
1561
+ @pytest.mark.parametrize(
1562
+ "expr",
1563
+ [
1564
+ "df > 2 and df > 3",
1565
+ "df > 2 or df > 3",
1566
+ "not df > 2",
1567
+ ],
1568
+ )
1569
+ def test_fails_and_or_not(self, expr, engine, parser):
1570
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
1571
+ if parser == "python":
1572
+ msg = "'BoolOp' nodes are not implemented"
1573
+ if "not" in expr:
1574
+ msg = "'Not' nodes are not implemented"
1575
+
1576
+ with pytest.raises(NotImplementedError, match=msg):
1577
+ pd.eval(
1578
+ expr,
1579
+ local_dict={"df": df},
1580
+ parser=parser,
1581
+ engine=engine,
1582
+ )
1583
+ else:
1584
+ # smoke-test, should not raise
1585
+ pd.eval(
1586
+ expr,
1587
+ local_dict={"df": df},
1588
+ parser=parser,
1589
+ engine=engine,
1590
+ )
1591
+
1592
+ @pytest.mark.parametrize("char", ["|", "&"])
1593
+ def test_fails_ampersand_pipe(self, char, engine, parser):
1594
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # noqa: F841
1595
+ ex = f"(df + 2)[df > 1] > 0 {char} (df > 0)"
1596
+ if parser == "python":
1597
+ msg = "cannot evaluate scalar only bool ops"
1598
+ with pytest.raises(NotImplementedError, match=msg):
1599
+ pd.eval(ex, parser=parser, engine=engine)
1600
+ else:
1601
+ # smoke-test, should not raise
1602
+ pd.eval(ex, parser=parser, engine=engine)
1603
+
1604
+
1605
+ class TestMath:
1606
+ def eval(self, *args, **kwargs):
1607
+ kwargs["level"] = kwargs.pop("level", 0) + 1
1608
+ return pd.eval(*args, **kwargs)
1609
+
1610
+ @pytest.mark.skipif(
1611
+ not NUMEXPR_INSTALLED, reason="Unary ops only implemented for numexpr"
1612
+ )
1613
+ @pytest.mark.parametrize("fn", _unary_math_ops)
1614
+ def test_unary_functions(self, fn):
1615
+ df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})
1616
+ a = df.a
1617
+
1618
+ expr = f"{fn}(a)"
1619
+ got = self.eval(expr)
1620
+ with np.errstate(all="ignore"):
1621
+ expect = getattr(np, fn)(a)
1622
+ tm.assert_series_equal(got, expect, check_names=False)
1623
+
1624
+ @pytest.mark.parametrize("fn", _binary_math_ops)
1625
+ def test_binary_functions(self, fn):
1626
+ df = DataFrame(
1627
+ {
1628
+ "a": np.random.default_rng(2).standard_normal(10),
1629
+ "b": np.random.default_rng(2).standard_normal(10),
1630
+ }
1631
+ )
1632
+ a = df.a
1633
+ b = df.b
1634
+
1635
+ expr = f"{fn}(a, b)"
1636
+ got = self.eval(expr)
1637
+ with np.errstate(all="ignore"):
1638
+ expect = getattr(np, fn)(a, b)
1639
+ tm.assert_almost_equal(got, expect, check_names=False)
1640
+
1641
+ def test_df_use_case(self, engine, parser):
1642
+ df = DataFrame(
1643
+ {
1644
+ "a": np.random.default_rng(2).standard_normal(10),
1645
+ "b": np.random.default_rng(2).standard_normal(10),
1646
+ }
1647
+ )
1648
+ df.eval(
1649
+ "e = arctan2(sin(a), b)",
1650
+ engine=engine,
1651
+ parser=parser,
1652
+ inplace=True,
1653
+ )
1654
+ got = df.e
1655
+ expect = np.arctan2(np.sin(df.a), df.b)
1656
+ tm.assert_series_equal(got, expect, check_names=False)
1657
+
1658
+ def test_df_arithmetic_subexpression(self, engine, parser):
1659
+ df = DataFrame(
1660
+ {
1661
+ "a": np.random.default_rng(2).standard_normal(10),
1662
+ "b": np.random.default_rng(2).standard_normal(10),
1663
+ }
1664
+ )
1665
+ df.eval("e = sin(a + b)", engine=engine, parser=parser, inplace=True)
1666
+ got = df.e
1667
+ expect = np.sin(df.a + df.b)
1668
+ tm.assert_series_equal(got, expect, check_names=False)
1669
+
1670
+ @pytest.mark.parametrize(
1671
+ "dtype, expect_dtype",
1672
+ [
1673
+ (np.int32, np.float64),
1674
+ (np.int64, np.float64),
1675
+ (np.float32, np.float32),
1676
+ (np.float64, np.float64),
1677
+ pytest.param(np.complex128, np.complex128, marks=td.skip_if_windows),
1678
+ ],
1679
+ )
1680
+ def test_result_types(self, dtype, expect_dtype, engine, parser):
1681
+ # xref https://github.com/pandas-dev/pandas/issues/12293
1682
+ # this fails on Windows, apparently a floating point precision issue
1683
+
1684
+ # Did not test complex64 because DataFrame is converting it to
1685
+ # complex128. Due to https://github.com/pandas-dev/pandas/issues/10952
1686
+ df = DataFrame(
1687
+ {"a": np.random.default_rng(2).standard_normal(10).astype(dtype)}
1688
+ )
1689
+ assert df.a.dtype == dtype
1690
+ df.eval("b = sin(a)", engine=engine, parser=parser, inplace=True)
1691
+ got = df.b
1692
+ expect = np.sin(df.a)
1693
+ assert expect.dtype == got.dtype
1694
+ assert expect_dtype == got.dtype
1695
+ tm.assert_series_equal(got, expect, check_names=False)
1696
+
1697
+ def test_undefined_func(self, engine, parser):
1698
+ df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})
1699
+ msg = '"mysin" is not a supported function'
1700
+
1701
+ with pytest.raises(ValueError, match=msg):
1702
+ df.eval("mysin(a)", engine=engine, parser=parser)
1703
+
1704
+ def test_keyword_arg(self, engine, parser):
1705
+ df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})
1706
+ msg = 'Function "sin" does not support keyword arguments'
1707
+
1708
+ with pytest.raises(TypeError, match=msg):
1709
+ df.eval("sin(x=a)", engine=engine, parser=parser)
1710
+
1711
+
1712
+ _var_s = np.random.default_rng(2).standard_normal(10)
1713
+
1714
+
1715
+ class TestScope:
1716
+ def test_global_scope(self, engine, parser):
1717
+ e = "_var_s * 2"
1718
+ tm.assert_numpy_array_equal(
1719
+ _var_s * 2, pd.eval(e, engine=engine, parser=parser)
1720
+ )
1721
+
1722
+ def test_no_new_locals(self, engine, parser):
1723
+ x = 1
1724
+ lcls = locals().copy()
1725
+ pd.eval("x + 1", local_dict=lcls, engine=engine, parser=parser)
1726
+ lcls2 = locals().copy()
1727
+ lcls2.pop("lcls")
1728
+ assert lcls == lcls2
1729
+
1730
+ def test_no_new_globals(self, engine, parser):
1731
+ x = 1 # noqa: F841
1732
+ gbls = globals().copy()
1733
+ pd.eval("x + 1", engine=engine, parser=parser)
1734
+ gbls2 = globals().copy()
1735
+ assert gbls == gbls2
1736
+
1737
+ def test_empty_locals(self, engine, parser):
1738
+ # GH 47084
1739
+ x = 1 # noqa: F841
1740
+ msg = "name 'x' is not defined"
1741
+ with pytest.raises(UndefinedVariableError, match=msg):
1742
+ pd.eval("x + 1", engine=engine, parser=parser, local_dict={})
1743
+
1744
+ def test_empty_globals(self, engine, parser):
1745
+ # GH 47084
1746
+ msg = "name '_var_s' is not defined"
1747
+ e = "_var_s * 2"
1748
+ with pytest.raises(UndefinedVariableError, match=msg):
1749
+ pd.eval(e, engine=engine, parser=parser, global_dict={})
1750
+
1751
+
1752
+ @td.skip_if_no("numexpr")
1753
+ def test_invalid_engine():
1754
+ msg = "Invalid engine 'asdf' passed"
1755
+ with pytest.raises(KeyError, match=msg):
1756
+ pd.eval("x + y", local_dict={"x": 1, "y": 2}, engine="asdf")
1757
+
1758
+
1759
+ @td.skip_if_no("numexpr")
1760
+ @pytest.mark.parametrize(
1761
+ ("use_numexpr", "expected"),
1762
+ (
1763
+ (True, "numexpr"),
1764
+ (False, "python"),
1765
+ ),
1766
+ )
1767
+ def test_numexpr_option_respected(use_numexpr, expected):
1768
+ # GH 32556
1769
+ from pandas.core.computation.eval import _check_engine
1770
+
1771
+ with pd.option_context("compute.use_numexpr", use_numexpr):
1772
+ result = _check_engine(None)
1773
+ assert result == expected
1774
+
1775
+
1776
+ @td.skip_if_no("numexpr")
1777
+ def test_numexpr_option_incompatible_op():
1778
+ # GH 32556
1779
+ with pd.option_context("compute.use_numexpr", False):
1780
+ df = DataFrame(
1781
+ {"A": [True, False, True, False, None, None], "B": [1, 2, 3, 4, 5, 6]}
1782
+ )
1783
+ result = df.query("A.isnull()")
1784
+ expected = DataFrame({"A": [None, None], "B": [5, 6]}, index=[4, 5])
1785
+ tm.assert_frame_equal(result, expected)
1786
+
1787
+
1788
+ @td.skip_if_no("numexpr")
1789
+ def test_invalid_parser():
1790
+ msg = "Invalid parser 'asdf' passed"
1791
+ with pytest.raises(KeyError, match=msg):
1792
+ pd.eval("x + y", local_dict={"x": 1, "y": 2}, parser="asdf")
1793
+
1794
+
1795
+ _parsers: dict[str, type[BaseExprVisitor]] = {
1796
+ "python": PythonExprVisitor,
1797
+ "pytables": pytables.PyTablesExprVisitor,
1798
+ "pandas": PandasExprVisitor,
1799
+ }
1800
+
1801
+
1802
+ @pytest.mark.parametrize("engine", ENGINES)
1803
+ @pytest.mark.parametrize("parser", _parsers)
1804
+ def test_disallowed_nodes(engine, parser):
1805
+ VisitorClass = _parsers[parser]
1806
+ inst = VisitorClass("x + 1", engine, parser)
1807
+
1808
+ for ops in VisitorClass.unsupported_nodes:
1809
+ msg = "nodes are not implemented"
1810
+ with pytest.raises(NotImplementedError, match=msg):
1811
+ getattr(inst, ops)()
1812
+
1813
+
1814
+ def test_syntax_error_exprs(engine, parser):
1815
+ e = "s +"
1816
+ with pytest.raises(SyntaxError, match="invalid syntax"):
1817
+ pd.eval(e, engine=engine, parser=parser)
1818
+
1819
+
1820
+ def test_name_error_exprs(engine, parser):
1821
+ e = "s + t"
1822
+ msg = "name 's' is not defined"
1823
+ with pytest.raises(NameError, match=msg):
1824
+ pd.eval(e, engine=engine, parser=parser)
1825
+
1826
+
1827
+ @pytest.mark.parametrize("express", ["a + @b", "@a + b", "@a + @b"])
1828
+ def test_invalid_local_variable_reference(engine, parser, express):
1829
+ a, b = 1, 2 # noqa: F841
1830
+
1831
+ if parser != "pandas":
1832
+ with pytest.raises(SyntaxError, match="The '@' prefix is only"):
1833
+ pd.eval(express, engine=engine, parser=parser)
1834
+ else:
1835
+ with pytest.raises(SyntaxError, match="The '@' prefix is not"):
1836
+ pd.eval(express, engine=engine, parser=parser)
1837
+
1838
+
1839
+ def test_numexpr_builtin_raises(engine, parser):
1840
+ sin, dotted_line = 1, 2
1841
+ if engine == "numexpr":
1842
+ msg = "Variables in expression .+"
1843
+ with pytest.raises(NumExprClobberingError, match=msg):
1844
+ pd.eval("sin + dotted_line", engine=engine, parser=parser)
1845
+ else:
1846
+ res = pd.eval("sin + dotted_line", engine=engine, parser=parser)
1847
+ assert res == sin + dotted_line
1848
+
1849
+
1850
+ def test_bad_resolver_raises(engine, parser):
1851
+ cannot_resolve = 42, 3.0
1852
+ with pytest.raises(TypeError, match="Resolver of type .+"):
1853
+ pd.eval("1 + 2", resolvers=cannot_resolve, engine=engine, parser=parser)
1854
+
1855
+
1856
+ def test_empty_string_raises(engine, parser):
1857
+ # GH 13139
1858
+ with pytest.raises(ValueError, match="expr cannot be an empty string"):
1859
+ pd.eval("", engine=engine, parser=parser)
1860
+
1861
+
1862
+ def test_more_than_one_expression_raises(engine, parser):
1863
+ with pytest.raises(SyntaxError, match="only a single expression is allowed"):
1864
+ pd.eval("1 + 1; 2 + 2", engine=engine, parser=parser)
1865
+
1866
+
1867
+ @pytest.mark.parametrize("cmp", ("and", "or"))
1868
+ @pytest.mark.parametrize("lhs", (int, float))
1869
+ @pytest.mark.parametrize("rhs", (int, float))
1870
+ def test_bool_ops_fails_on_scalars(lhs, cmp, rhs, engine, parser):
1871
+ gen = {
1872
+ int: lambda: np.random.default_rng(2).integers(10),
1873
+ float: np.random.default_rng(2).standard_normal,
1874
+ }
1875
+
1876
+ mid = gen[lhs]() # noqa: F841
1877
+ lhs = gen[lhs]()
1878
+ rhs = gen[rhs]()
1879
+
1880
+ ex1 = f"lhs {cmp} mid {cmp} rhs"
1881
+ ex2 = f"lhs {cmp} mid and mid {cmp} rhs"
1882
+ ex3 = f"(lhs {cmp} mid) & (mid {cmp} rhs)"
1883
+ for ex in (ex1, ex2, ex3):
1884
+ msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not"
1885
+ with pytest.raises(NotImplementedError, match=msg):
1886
+ pd.eval(ex, engine=engine, parser=parser)
1887
+
1888
+
1889
+ @pytest.mark.parametrize(
1890
+ "other",
1891
+ [
1892
+ "'x'",
1893
+ "...",
1894
+ ],
1895
+ )
1896
+ def test_equals_various(other):
1897
+ df = DataFrame({"A": ["a", "b", "c"]}, dtype=object)
1898
+ result = df.eval(f"A == {other}")
1899
+ expected = Series([False, False, False], name="A")
1900
+ if USE_NUMEXPR:
1901
+ # https://github.com/pandas-dev/pandas/issues/10239
1902
+ # lose name with numexpr engine. Remove when that's fixed.
1903
+ expected.name = None
1904
+ tm.assert_series_equal(result, expected)
1905
+
1906
+
1907
+ def test_inf(engine, parser):
1908
+ s = "inf + 1"
1909
+ expected = np.inf
1910
+ result = pd.eval(s, engine=engine, parser=parser)
1911
+ assert result == expected
1912
+
1913
+
1914
+ @pytest.mark.parametrize("column", ["Temp(°C)", "Capacitance(μF)"])
1915
+ def test_query_token(engine, column):
1916
+ # See: https://github.com/pandas-dev/pandas/pull/42826
1917
+ df = DataFrame(
1918
+ np.random.default_rng(2).standard_normal((5, 2)), columns=[column, "b"]
1919
+ )
1920
+ expected = df[df[column] > 5]
1921
+ query_string = f"`{column}` > 5"
1922
+ result = df.query(query_string, engine=engine)
1923
+ tm.assert_frame_equal(result, expected)
1924
+
1925
+
1926
+ def test_negate_lt_eq_le(engine, parser):
1927
+ df = DataFrame([[0, 10], [1, 20]], columns=["cat", "count"])
1928
+ expected = df[~(df.cat > 0)]
1929
+
1930
+ result = df.query("~(cat > 0)", engine=engine, parser=parser)
1931
+ tm.assert_frame_equal(result, expected)
1932
+
1933
+ if parser == "python":
1934
+ msg = "'Not' nodes are not implemented"
1935
+ with pytest.raises(NotImplementedError, match=msg):
1936
+ df.query("not (cat > 0)", engine=engine, parser=parser)
1937
+ else:
1938
+ result = df.query("not (cat > 0)", engine=engine, parser=parser)
1939
+ tm.assert_frame_equal(result, expected)
1940
+
1941
+
1942
+ @pytest.mark.parametrize(
1943
+ "column",
1944
+ DEFAULT_GLOBALS.keys(),
1945
+ )
1946
+ def test_eval_no_support_column_name(request, column):
1947
+ # GH 44603
1948
+ if column in ["True", "False", "inf", "Inf"]:
1949
+ request.applymarker(
1950
+ pytest.mark.xfail(
1951
+ raises=KeyError,
1952
+ reason=f"GH 47859 DataFrame eval not supported with {column}",
1953
+ )
1954
+ )
1955
+
1956
+ df = DataFrame(
1957
+ np.random.default_rng(2).integers(0, 100, size=(10, 2)),
1958
+ columns=[column, "col1"],
1959
+ )
1960
+ expected = df[df[column] > 6]
1961
+ result = df.query(f"{column}>6")
1962
+
1963
+ tm.assert_frame_equal(result, expected)
1964
+
1965
+
1966
+ def test_set_inplace(using_copy_on_write, warn_copy_on_write):
1967
+ # https://github.com/pandas-dev/pandas/issues/47449
1968
+ # Ensure we don't only update the DataFrame inplace, but also the actual
1969
+ # column values, such that references to this column also get updated
1970
+ df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
1971
+ result_view = df[:]
1972
+ ser = df["A"]
1973
+ with tm.assert_cow_warning(warn_copy_on_write):
1974
+ df.eval("A = B + C", inplace=True)
1975
+ expected = DataFrame({"A": [11, 13, 15], "B": [4, 5, 6], "C": [7, 8, 9]})
1976
+ tm.assert_frame_equal(df, expected)
1977
+ if not using_copy_on_write:
1978
+ tm.assert_series_equal(ser, expected["A"])
1979
+ tm.assert_series_equal(result_view["A"], expected["A"])
1980
+ else:
1981
+ expected = Series([1, 2, 3], name="A")
1982
+ tm.assert_series_equal(ser, expected)
1983
+ tm.assert_series_equal(result_view["A"], expected)
1984
+
1985
+
1986
+ class TestValidate:
1987
+ @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
1988
+ def test_validate_bool_args(self, value):
1989
+ msg = 'For argument "inplace" expected type bool, received type'
1990
+ with pytest.raises(ValueError, match=msg):
1991
+ pd.eval("2+2", inplace=value)
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import pandas as pd
4
+
5
+ object_pyarrow_numpy = ("object", "string[pyarrow_numpy]")
6
+
7
+
8
+ def _convert_na_value(ser, expected):
9
+ if ser.dtype != object:
10
+ if ser.dtype.storage == "pyarrow_numpy":
11
+ expected = expected.fillna(np.nan)
12
+ else:
13
+ # GH#18463
14
+ expected = expected.fillna(pd.NA)
15
+ return expected
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (533 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (3.02 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_cat.cpython-310.pyc ADDED
Binary file (9.57 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_extract.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_find_replace.cpython-310.pyc ADDED
Binary file (23.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_get_dummies.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/__pycache__/test_string_array.cpython-310.pyc ADDED
Binary file (2.78 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/conftest.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import Series
4
+ from pandas.core.strings.accessor import StringMethods
5
+
6
+ _any_string_method = [
7
+ ("cat", (), {"sep": ","}),
8
+ ("cat", (Series(list("zyx")),), {"sep": ",", "join": "left"}),
9
+ ("center", (10,), {}),
10
+ ("contains", ("a",), {}),
11
+ ("count", ("a",), {}),
12
+ ("decode", ("UTF-8",), {}),
13
+ ("encode", ("UTF-8",), {}),
14
+ ("endswith", ("a",), {}),
15
+ ("endswith", ((),), {}),
16
+ ("endswith", (("a",),), {}),
17
+ ("endswith", (("a", "b"),), {}),
18
+ ("endswith", (("a", "MISSING"),), {}),
19
+ ("endswith", ("a",), {"na": True}),
20
+ ("endswith", ("a",), {"na": False}),
21
+ ("extract", ("([a-z]*)",), {"expand": False}),
22
+ ("extract", ("([a-z]*)",), {"expand": True}),
23
+ ("extractall", ("([a-z]*)",), {}),
24
+ ("find", ("a",), {}),
25
+ ("findall", ("a",), {}),
26
+ ("get", (0,), {}),
27
+ # because "index" (and "rindex") fail intentionally
28
+ # if the string is not found, search only for empty string
29
+ ("index", ("",), {}),
30
+ ("join", (",",), {}),
31
+ ("ljust", (10,), {}),
32
+ ("match", ("a",), {}),
33
+ ("fullmatch", ("a",), {}),
34
+ ("normalize", ("NFC",), {}),
35
+ ("pad", (10,), {}),
36
+ ("partition", (" ",), {"expand": False}),
37
+ ("partition", (" ",), {"expand": True}),
38
+ ("repeat", (3,), {}),
39
+ ("replace", ("a", "z"), {}),
40
+ ("rfind", ("a",), {}),
41
+ ("rindex", ("",), {}),
42
+ ("rjust", (10,), {}),
43
+ ("rpartition", (" ",), {"expand": False}),
44
+ ("rpartition", (" ",), {"expand": True}),
45
+ ("slice", (0, 1), {}),
46
+ ("slice_replace", (0, 1, "z"), {}),
47
+ ("split", (" ",), {"expand": False}),
48
+ ("split", (" ",), {"expand": True}),
49
+ ("startswith", ("a",), {}),
50
+ ("startswith", (("a",),), {}),
51
+ ("startswith", (("a", "b"),), {}),
52
+ ("startswith", (("a", "MISSING"),), {}),
53
+ ("startswith", ((),), {}),
54
+ ("startswith", ("a",), {"na": True}),
55
+ ("startswith", ("a",), {"na": False}),
56
+ ("removeprefix", ("a",), {}),
57
+ ("removesuffix", ("a",), {}),
58
+ # translating unicode points of "a" to "d"
59
+ ("translate", ({97: 100},), {}),
60
+ ("wrap", (2,), {}),
61
+ ("zfill", (10,), {}),
62
+ ] + list(
63
+ zip(
64
+ [
65
+ # methods without positional arguments: zip with empty tuple and empty dict
66
+ "capitalize",
67
+ "cat",
68
+ "get_dummies",
69
+ "isalnum",
70
+ "isalpha",
71
+ "isdecimal",
72
+ "isdigit",
73
+ "islower",
74
+ "isnumeric",
75
+ "isspace",
76
+ "istitle",
77
+ "isupper",
78
+ "len",
79
+ "lower",
80
+ "lstrip",
81
+ "partition",
82
+ "rpartition",
83
+ "rsplit",
84
+ "rstrip",
85
+ "slice",
86
+ "slice_replace",
87
+ "split",
88
+ "strip",
89
+ "swapcase",
90
+ "title",
91
+ "upper",
92
+ "casefold",
93
+ ],
94
+ [()] * 100,
95
+ [{}] * 100,
96
+ )
97
+ )
98
+ ids, _, _ = zip(*_any_string_method) # use method name as fixture-id
99
+ missing_methods = {f for f in dir(StringMethods) if not f.startswith("_")} - set(ids)
100
+
101
+ # test that the above list captures all methods of StringMethods
102
+ assert not missing_methods
103
+
104
+
105
+ @pytest.fixture(params=_any_string_method, ids=ids)
106
+ def any_string_method(request):
107
+ """
108
+ Fixture for all public methods of `StringMethods`
109
+
110
+ This fixture returns a tuple of the method name and sample arguments
111
+ necessary to call the method.
112
+
113
+ Returns
114
+ -------
115
+ method_name : str
116
+ The name of the method in `StringMethods`
117
+ args : tuple
118
+ Sample values for the positional arguments
119
+ kwargs : dict
120
+ Sample values for the keyword arguments
121
+
122
+ Examples
123
+ --------
124
+ >>> def test_something(any_string_method):
125
+ ... s = Series(['a', 'b', np.nan, 'd'])
126
+ ...
127
+ ... method_name, args, kwargs = any_string_method
128
+ ... method = getattr(s.str, method_name)
129
+ ... # will not raise
130
+ ... method(*args, **kwargs)
131
+ """
132
+ return request.param
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_api.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ CategoricalDtype,
6
+ DataFrame,
7
+ Index,
8
+ MultiIndex,
9
+ Series,
10
+ _testing as tm,
11
+ option_context,
12
+ )
13
+ from pandas.core.strings.accessor import StringMethods
14
+
15
+ # subset of the full set from pandas/conftest.py
16
+ _any_allowed_skipna_inferred_dtype = [
17
+ ("string", ["a", np.nan, "c"]),
18
+ ("bytes", [b"a", np.nan, b"c"]),
19
+ ("empty", [np.nan, np.nan, np.nan]),
20
+ ("empty", []),
21
+ ("mixed-integer", ["a", np.nan, 2]),
22
+ ]
23
+ ids, _ = zip(*_any_allowed_skipna_inferred_dtype) # use inferred type as id
24
+
25
+
26
+ @pytest.fixture(params=_any_allowed_skipna_inferred_dtype, ids=ids)
27
+ def any_allowed_skipna_inferred_dtype(request):
28
+ """
29
+ Fixture for all (inferred) dtypes allowed in StringMethods.__init__
30
+
31
+ The covered (inferred) types are:
32
+ * 'string'
33
+ * 'empty'
34
+ * 'bytes'
35
+ * 'mixed'
36
+ * 'mixed-integer'
37
+
38
+ Returns
39
+ -------
40
+ inferred_dtype : str
41
+ The string for the inferred dtype from _libs.lib.infer_dtype
42
+ values : np.ndarray
43
+ An array of object dtype that will be inferred to have
44
+ `inferred_dtype`
45
+
46
+ Examples
47
+ --------
48
+ >>> from pandas._libs import lib
49
+ >>>
50
+ >>> def test_something(any_allowed_skipna_inferred_dtype):
51
+ ... inferred_dtype, values = any_allowed_skipna_inferred_dtype
52
+ ... # will pass
53
+ ... assert lib.infer_dtype(values, skipna=True) == inferred_dtype
54
+ ...
55
+ ... # constructor for .str-accessor will also pass
56
+ ... Series(values).str
57
+ """
58
+ inferred_dtype, values = request.param
59
+ values = np.array(values, dtype=object) # object dtype to avoid casting
60
+
61
+ # correctness of inference tested in tests/dtypes/test_inference.py
62
+ return inferred_dtype, values
63
+
64
+
65
+ def test_api(any_string_dtype):
66
+ # GH 6106, GH 9322
67
+ assert Series.str is StringMethods
68
+ assert isinstance(Series([""], dtype=any_string_dtype).str, StringMethods)
69
+
70
+
71
+ def test_api_mi_raises():
72
+ # GH 23679
73
+ mi = MultiIndex.from_arrays([["a", "b", "c"]])
74
+ msg = "Can only use .str accessor with Index, not MultiIndex"
75
+ with pytest.raises(AttributeError, match=msg):
76
+ mi.str
77
+ assert not hasattr(mi, "str")
78
+
79
+
80
+ @pytest.mark.parametrize("dtype", [object, "category"])
81
+ def test_api_per_dtype(index_or_series, dtype, any_skipna_inferred_dtype):
82
+ # one instance of parametrized fixture
83
+ box = index_or_series
84
+ inferred_dtype, values = any_skipna_inferred_dtype
85
+
86
+ t = box(values, dtype=dtype) # explicit dtype to avoid casting
87
+
88
+ types_passing_constructor = [
89
+ "string",
90
+ "unicode",
91
+ "empty",
92
+ "bytes",
93
+ "mixed",
94
+ "mixed-integer",
95
+ ]
96
+ if inferred_dtype in types_passing_constructor:
97
+ # GH 6106
98
+ assert isinstance(t.str, StringMethods)
99
+ else:
100
+ # GH 9184, GH 23011, GH 23163
101
+ msg = "Can only use .str accessor with string values.*"
102
+ with pytest.raises(AttributeError, match=msg):
103
+ t.str
104
+ assert not hasattr(t, "str")
105
+
106
+
107
+ @pytest.mark.parametrize("dtype", [object, "category"])
108
+ def test_api_per_method(
109
+ index_or_series,
110
+ dtype,
111
+ any_allowed_skipna_inferred_dtype,
112
+ any_string_method,
113
+ request,
114
+ ):
115
+ # this test does not check correctness of the different methods,
116
+ # just that the methods work on the specified (inferred) dtypes,
117
+ # and raise on all others
118
+ box = index_or_series
119
+
120
+ # one instance of each parametrized fixture
121
+ inferred_dtype, values = any_allowed_skipna_inferred_dtype
122
+ method_name, args, kwargs = any_string_method
123
+
124
+ reason = None
125
+ if box is Index and values.size == 0:
126
+ if method_name in ["partition", "rpartition"] and kwargs.get("expand", True):
127
+ raises = TypeError
128
+ reason = "Method cannot deal with empty Index"
129
+ elif method_name == "split" and kwargs.get("expand", None):
130
+ raises = TypeError
131
+ reason = "Split fails on empty Series when expand=True"
132
+ elif method_name == "get_dummies":
133
+ raises = ValueError
134
+ reason = "Need to fortify get_dummies corner cases"
135
+
136
+ elif (
137
+ box is Index
138
+ and inferred_dtype == "empty"
139
+ and dtype == object
140
+ and method_name == "get_dummies"
141
+ ):
142
+ raises = ValueError
143
+ reason = "Need to fortify get_dummies corner cases"
144
+
145
+ if reason is not None:
146
+ mark = pytest.mark.xfail(raises=raises, reason=reason)
147
+ request.applymarker(mark)
148
+
149
+ t = box(values, dtype=dtype) # explicit dtype to avoid casting
150
+ method = getattr(t.str, method_name)
151
+
152
+ bytes_allowed = method_name in ["decode", "get", "len", "slice"]
153
+ # as of v0.23.4, all methods except 'cat' are very lenient with the
154
+ # allowed data types, just returning NaN for entries that error.
155
+ # This could be changed with an 'errors'-kwarg to the `str`-accessor,
156
+ # see discussion in GH 13877
157
+ mixed_allowed = method_name not in ["cat"]
158
+
159
+ allowed_types = (
160
+ ["string", "unicode", "empty"]
161
+ + ["bytes"] * bytes_allowed
162
+ + ["mixed", "mixed-integer"] * mixed_allowed
163
+ )
164
+
165
+ if inferred_dtype in allowed_types:
166
+ # xref GH 23555, GH 23556
167
+ with option_context("future.no_silent_downcasting", True):
168
+ method(*args, **kwargs) # works!
169
+ else:
170
+ # GH 23011, GH 23163
171
+ msg = (
172
+ f"Cannot use .str.{method_name} with values of "
173
+ f"inferred dtype {repr(inferred_dtype)}."
174
+ )
175
+ with pytest.raises(TypeError, match=msg):
176
+ method(*args, **kwargs)
177
+
178
+
179
+ def test_api_for_categorical(any_string_method, any_string_dtype):
180
+ # https://github.com/pandas-dev/pandas/issues/10661
181
+ s = Series(list("aabb"), dtype=any_string_dtype)
182
+ s = s + " " + s
183
+ c = s.astype("category")
184
+ c = c.astype(CategoricalDtype(c.dtype.categories.astype("object")))
185
+ assert isinstance(c.str, StringMethods)
186
+
187
+ method_name, args, kwargs = any_string_method
188
+
189
+ result = getattr(c.str, method_name)(*args, **kwargs)
190
+ expected = getattr(s.astype("object").str, method_name)(*args, **kwargs)
191
+
192
+ if isinstance(result, DataFrame):
193
+ tm.assert_frame_equal(result, expected)
194
+ elif isinstance(result, Series):
195
+ tm.assert_series_equal(result, expected)
196
+ else:
197
+ # str.cat(others=None) returns string, for example
198
+ assert result == expected
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_case_justify.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import operator
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas import (
8
+ Series,
9
+ _testing as tm,
10
+ )
11
+
12
+
13
+ def test_title(any_string_dtype):
14
+ s = Series(["FOO", "BAR", np.nan, "Blah", "blurg"], dtype=any_string_dtype)
15
+ result = s.str.title()
16
+ expected = Series(["Foo", "Bar", np.nan, "Blah", "Blurg"], dtype=any_string_dtype)
17
+ tm.assert_series_equal(result, expected)
18
+
19
+
20
+ def test_title_mixed_object():
21
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0])
22
+ result = s.str.title()
23
+ expected = Series(
24
+ ["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", None, np.nan, np.nan],
25
+ dtype=object,
26
+ )
27
+ tm.assert_almost_equal(result, expected)
28
+
29
+
30
+ def test_lower_upper(any_string_dtype):
31
+ s = Series(["om", np.nan, "nom", "nom"], dtype=any_string_dtype)
32
+
33
+ result = s.str.upper()
34
+ expected = Series(["OM", np.nan, "NOM", "NOM"], dtype=any_string_dtype)
35
+ tm.assert_series_equal(result, expected)
36
+
37
+ result = result.str.lower()
38
+ tm.assert_series_equal(result, s)
39
+
40
+
41
+ def test_lower_upper_mixed_object():
42
+ s = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0])
43
+
44
+ result = s.str.upper()
45
+ expected = Series(
46
+ ["A", np.nan, "B", np.nan, np.nan, "FOO", None, np.nan, np.nan], dtype=object
47
+ )
48
+ tm.assert_series_equal(result, expected)
49
+
50
+ result = s.str.lower()
51
+ expected = Series(
52
+ ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object
53
+ )
54
+ tm.assert_series_equal(result, expected)
55
+
56
+
57
+ @pytest.mark.parametrize(
58
+ "data, expected",
59
+ [
60
+ (
61
+ ["FOO", "BAR", np.nan, "Blah", "blurg"],
62
+ ["Foo", "Bar", np.nan, "Blah", "Blurg"],
63
+ ),
64
+ (["a", "b", "c"], ["A", "B", "C"]),
65
+ (["a b", "a bc. de"], ["A b", "A bc. de"]),
66
+ ],
67
+ )
68
+ def test_capitalize(data, expected, any_string_dtype):
69
+ s = Series(data, dtype=any_string_dtype)
70
+ result = s.str.capitalize()
71
+ expected = Series(expected, dtype=any_string_dtype)
72
+ tm.assert_series_equal(result, expected)
73
+
74
+
75
+ def test_capitalize_mixed_object():
76
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0])
77
+ result = s.str.capitalize()
78
+ expected = Series(
79
+ ["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", None, np.nan, np.nan],
80
+ dtype=object,
81
+ )
82
+ tm.assert_series_equal(result, expected)
83
+
84
+
85
+ def test_swapcase(any_string_dtype):
86
+ s = Series(["FOO", "BAR", np.nan, "Blah", "blurg"], dtype=any_string_dtype)
87
+ result = s.str.swapcase()
88
+ expected = Series(["foo", "bar", np.nan, "bLAH", "BLURG"], dtype=any_string_dtype)
89
+ tm.assert_series_equal(result, expected)
90
+
91
+
92
+ def test_swapcase_mixed_object():
93
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "Blah", None, 1, 2.0])
94
+ result = s.str.swapcase()
95
+ expected = Series(
96
+ ["foo", np.nan, "BAR", np.nan, np.nan, "bLAH", None, np.nan, np.nan],
97
+ dtype=object,
98
+ )
99
+ tm.assert_series_equal(result, expected)
100
+
101
+
102
+ def test_casefold():
103
+ # GH25405
104
+ expected = Series(["ss", np.nan, "case", "ssd"])
105
+ s = Series(["ß", np.nan, "case", "ßd"])
106
+ result = s.str.casefold()
107
+
108
+ tm.assert_series_equal(result, expected)
109
+
110
+
111
+ def test_casemethods(any_string_dtype):
112
+ values = ["aaa", "bbb", "CCC", "Dddd", "eEEE"]
113
+ s = Series(values, dtype=any_string_dtype)
114
+ assert s.str.lower().tolist() == [v.lower() for v in values]
115
+ assert s.str.upper().tolist() == [v.upper() for v in values]
116
+ assert s.str.title().tolist() == [v.title() for v in values]
117
+ assert s.str.capitalize().tolist() == [v.capitalize() for v in values]
118
+ assert s.str.swapcase().tolist() == [v.swapcase() for v in values]
119
+
120
+
121
+ def test_pad(any_string_dtype):
122
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
123
+
124
+ result = s.str.pad(5, side="left")
125
+ expected = Series(
126
+ [" a", " b", np.nan, " c", np.nan, "eeeeee"], dtype=any_string_dtype
127
+ )
128
+ tm.assert_series_equal(result, expected)
129
+
130
+ result = s.str.pad(5, side="right")
131
+ expected = Series(
132
+ ["a ", "b ", np.nan, "c ", np.nan, "eeeeee"], dtype=any_string_dtype
133
+ )
134
+ tm.assert_series_equal(result, expected)
135
+
136
+ result = s.str.pad(5, side="both")
137
+ expected = Series(
138
+ [" a ", " b ", np.nan, " c ", np.nan, "eeeeee"], dtype=any_string_dtype
139
+ )
140
+ tm.assert_series_equal(result, expected)
141
+
142
+
143
+ def test_pad_mixed_object():
144
+ s = Series(["a", np.nan, "b", True, datetime.today(), "ee", None, 1, 2.0])
145
+
146
+ result = s.str.pad(5, side="left")
147
+ expected = Series(
148
+ [" a", np.nan, " b", np.nan, np.nan, " ee", None, np.nan, np.nan],
149
+ dtype=object,
150
+ )
151
+ tm.assert_series_equal(result, expected)
152
+
153
+ result = s.str.pad(5, side="right")
154
+ expected = Series(
155
+ ["a ", np.nan, "b ", np.nan, np.nan, "ee ", None, np.nan, np.nan],
156
+ dtype=object,
157
+ )
158
+ tm.assert_series_equal(result, expected)
159
+
160
+ result = s.str.pad(5, side="both")
161
+ expected = Series(
162
+ [" a ", np.nan, " b ", np.nan, np.nan, " ee ", None, np.nan, np.nan],
163
+ dtype=object,
164
+ )
165
+ tm.assert_series_equal(result, expected)
166
+
167
+
168
+ def test_pad_fillchar(any_string_dtype):
169
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
170
+
171
+ result = s.str.pad(5, side="left", fillchar="X")
172
+ expected = Series(
173
+ ["XXXXa", "XXXXb", np.nan, "XXXXc", np.nan, "eeeeee"], dtype=any_string_dtype
174
+ )
175
+ tm.assert_series_equal(result, expected)
176
+
177
+ result = s.str.pad(5, side="right", fillchar="X")
178
+ expected = Series(
179
+ ["aXXXX", "bXXXX", np.nan, "cXXXX", np.nan, "eeeeee"], dtype=any_string_dtype
180
+ )
181
+ tm.assert_series_equal(result, expected)
182
+
183
+ result = s.str.pad(5, side="both", fillchar="X")
184
+ expected = Series(
185
+ ["XXaXX", "XXbXX", np.nan, "XXcXX", np.nan, "eeeeee"], dtype=any_string_dtype
186
+ )
187
+ tm.assert_series_equal(result, expected)
188
+
189
+
190
+ def test_pad_fillchar_bad_arg_raises(any_string_dtype):
191
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
192
+
193
+ msg = "fillchar must be a character, not str"
194
+ with pytest.raises(TypeError, match=msg):
195
+ s.str.pad(5, fillchar="XY")
196
+
197
+ msg = "fillchar must be a character, not int"
198
+ with pytest.raises(TypeError, match=msg):
199
+ s.str.pad(5, fillchar=5)
200
+
201
+
202
+ @pytest.mark.parametrize("method_name", ["center", "ljust", "rjust", "zfill", "pad"])
203
+ def test_pad_width_bad_arg_raises(method_name, any_string_dtype):
204
+ # see gh-13598
205
+ s = Series(["1", "22", "a", "bb"], dtype=any_string_dtype)
206
+ op = operator.methodcaller(method_name, "f")
207
+
208
+ msg = "width must be of integer type, not str"
209
+ with pytest.raises(TypeError, match=msg):
210
+ op(s.str)
211
+
212
+
213
+ def test_center_ljust_rjust(any_string_dtype):
214
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
215
+
216
+ result = s.str.center(5)
217
+ expected = Series(
218
+ [" a ", " b ", np.nan, " c ", np.nan, "eeeeee"], dtype=any_string_dtype
219
+ )
220
+ tm.assert_series_equal(result, expected)
221
+
222
+ result = s.str.ljust(5)
223
+ expected = Series(
224
+ ["a ", "b ", np.nan, "c ", np.nan, "eeeeee"], dtype=any_string_dtype
225
+ )
226
+ tm.assert_series_equal(result, expected)
227
+
228
+ result = s.str.rjust(5)
229
+ expected = Series(
230
+ [" a", " b", np.nan, " c", np.nan, "eeeeee"], dtype=any_string_dtype
231
+ )
232
+ tm.assert_series_equal(result, expected)
233
+
234
+
235
+ def test_center_ljust_rjust_mixed_object():
236
+ s = Series(["a", np.nan, "b", True, datetime.today(), "c", "eee", None, 1, 2.0])
237
+
238
+ result = s.str.center(5)
239
+ expected = Series(
240
+ [
241
+ " a ",
242
+ np.nan,
243
+ " b ",
244
+ np.nan,
245
+ np.nan,
246
+ " c ",
247
+ " eee ",
248
+ None,
249
+ np.nan,
250
+ np.nan,
251
+ ],
252
+ dtype=object,
253
+ )
254
+ tm.assert_series_equal(result, expected)
255
+
256
+ result = s.str.ljust(5)
257
+ expected = Series(
258
+ [
259
+ "a ",
260
+ np.nan,
261
+ "b ",
262
+ np.nan,
263
+ np.nan,
264
+ "c ",
265
+ "eee ",
266
+ None,
267
+ np.nan,
268
+ np.nan,
269
+ ],
270
+ dtype=object,
271
+ )
272
+ tm.assert_series_equal(result, expected)
273
+
274
+ result = s.str.rjust(5)
275
+ expected = Series(
276
+ [
277
+ " a",
278
+ np.nan,
279
+ " b",
280
+ np.nan,
281
+ np.nan,
282
+ " c",
283
+ " eee",
284
+ None,
285
+ np.nan,
286
+ np.nan,
287
+ ],
288
+ dtype=object,
289
+ )
290
+ tm.assert_series_equal(result, expected)
291
+
292
+
293
+ def test_center_ljust_rjust_fillchar(any_string_dtype):
294
+ if any_string_dtype == "string[pyarrow_numpy]":
295
+ pytest.skip(
296
+ "Arrow logic is different, "
297
+ "see https://github.com/pandas-dev/pandas/pull/54533/files#r1299808126",
298
+ )
299
+ s = Series(["a", "bb", "cccc", "ddddd", "eeeeee"], dtype=any_string_dtype)
300
+
301
+ result = s.str.center(5, fillchar="X")
302
+ expected = Series(
303
+ ["XXaXX", "XXbbX", "Xcccc", "ddddd", "eeeeee"], dtype=any_string_dtype
304
+ )
305
+ tm.assert_series_equal(result, expected)
306
+ expected = np.array([v.center(5, "X") for v in np.array(s)], dtype=np.object_)
307
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
308
+
309
+ result = s.str.ljust(5, fillchar="X")
310
+ expected = Series(
311
+ ["aXXXX", "bbXXX", "ccccX", "ddddd", "eeeeee"], dtype=any_string_dtype
312
+ )
313
+ tm.assert_series_equal(result, expected)
314
+ expected = np.array([v.ljust(5, "X") for v in np.array(s)], dtype=np.object_)
315
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
316
+
317
+ result = s.str.rjust(5, fillchar="X")
318
+ expected = Series(
319
+ ["XXXXa", "XXXbb", "Xcccc", "ddddd", "eeeeee"], dtype=any_string_dtype
320
+ )
321
+ tm.assert_series_equal(result, expected)
322
+ expected = np.array([v.rjust(5, "X") for v in np.array(s)], dtype=np.object_)
323
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
324
+
325
+
326
+ def test_center_ljust_rjust_fillchar_bad_arg_raises(any_string_dtype):
327
+ s = Series(["a", "bb", "cccc", "ddddd", "eeeeee"], dtype=any_string_dtype)
328
+
329
+ # If fillchar is not a character, normal str raises TypeError
330
+ # 'aaa'.ljust(5, 'XY')
331
+ # TypeError: must be char, not str
332
+ template = "fillchar must be a character, not {dtype}"
333
+
334
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
335
+ s.str.center(5, fillchar="XY")
336
+
337
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
338
+ s.str.ljust(5, fillchar="XY")
339
+
340
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
341
+ s.str.rjust(5, fillchar="XY")
342
+
343
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
344
+ s.str.center(5, fillchar=1)
345
+
346
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
347
+ s.str.ljust(5, fillchar=1)
348
+
349
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
350
+ s.str.rjust(5, fillchar=1)
351
+
352
+
353
+ def test_zfill(any_string_dtype):
354
+ s = Series(["1", "22", "aaa", "333", "45678"], dtype=any_string_dtype)
355
+
356
+ result = s.str.zfill(5)
357
+ expected = Series(
358
+ ["00001", "00022", "00aaa", "00333", "45678"], dtype=any_string_dtype
359
+ )
360
+ tm.assert_series_equal(result, expected)
361
+ expected = np.array([v.zfill(5) for v in np.array(s)], dtype=np.object_)
362
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
363
+
364
+ result = s.str.zfill(3)
365
+ expected = Series(["001", "022", "aaa", "333", "45678"], dtype=any_string_dtype)
366
+ tm.assert_series_equal(result, expected)
367
+ expected = np.array([v.zfill(3) for v in np.array(s)], dtype=np.object_)
368
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
369
+
370
+ s = Series(["1", np.nan, "aaa", np.nan, "45678"], dtype=any_string_dtype)
371
+ result = s.str.zfill(5)
372
+ expected = Series(
373
+ ["00001", np.nan, "00aaa", np.nan, "45678"], dtype=any_string_dtype
374
+ )
375
+ tm.assert_series_equal(result, expected)
376
+
377
+
378
+ def test_wrap(any_string_dtype):
379
+ # test values are: two words less than width, two words equal to width,
380
+ # two words greater than width, one word less than width, one word
381
+ # equal to width, one word greater than width, multiple tokens with
382
+ # trailing whitespace equal to width
383
+ s = Series(
384
+ [
385
+ "hello world",
386
+ "hello world!",
387
+ "hello world!!",
388
+ "abcdefabcde",
389
+ "abcdefabcdef",
390
+ "abcdefabcdefa",
391
+ "ab ab ab ab ",
392
+ "ab ab ab ab a",
393
+ "\t",
394
+ ],
395
+ dtype=any_string_dtype,
396
+ )
397
+
398
+ # expected values
399
+ expected = Series(
400
+ [
401
+ "hello world",
402
+ "hello world!",
403
+ "hello\nworld!!",
404
+ "abcdefabcde",
405
+ "abcdefabcdef",
406
+ "abcdefabcdef\na",
407
+ "ab ab ab ab",
408
+ "ab ab ab ab\na",
409
+ "",
410
+ ],
411
+ dtype=any_string_dtype,
412
+ )
413
+
414
+ result = s.str.wrap(12, break_long_words=True)
415
+ tm.assert_series_equal(result, expected)
416
+
417
+
418
+ def test_wrap_unicode(any_string_dtype):
419
+ # test with pre and post whitespace (non-unicode), NaN, and non-ascii Unicode
420
+ s = Series(
421
+ [" pre ", np.nan, "\xac\u20ac\U00008000 abadcafe"], dtype=any_string_dtype
422
+ )
423
+ expected = Series(
424
+ [" pre", np.nan, "\xac\u20ac\U00008000 ab\nadcafe"], dtype=any_string_dtype
425
+ )
426
+ result = s.str.wrap(6)
427
+ tm.assert_series_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_cat.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas.util._test_decorators as td
7
+
8
+ from pandas import (
9
+ DataFrame,
10
+ Index,
11
+ MultiIndex,
12
+ Series,
13
+ _testing as tm,
14
+ concat,
15
+ option_context,
16
+ )
17
+
18
+
19
+ @pytest.mark.parametrize("other", [None, Series, Index])
20
+ def test_str_cat_name(index_or_series, other):
21
+ # GH 21053
22
+ box = index_or_series
23
+ values = ["a", "b"]
24
+ if other:
25
+ other = other(values)
26
+ else:
27
+ other = values
28
+ result = box(values, name="name").str.cat(other, sep=",")
29
+ assert result.name == "name"
30
+
31
+
32
+ @pytest.mark.parametrize(
33
+ "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
34
+ )
35
+ def test_str_cat(index_or_series, infer_string):
36
+ with option_context("future.infer_string", infer_string):
37
+ box = index_or_series
38
+ # test_cat above tests "str_cat" from ndarray;
39
+ # here testing "str.cat" from Series/Index to ndarray/list
40
+ s = box(["a", "a", "b", "b", "c", np.nan])
41
+
42
+ # single array
43
+ result = s.str.cat()
44
+ expected = "aabbc"
45
+ assert result == expected
46
+
47
+ result = s.str.cat(na_rep="-")
48
+ expected = "aabbc-"
49
+ assert result == expected
50
+
51
+ result = s.str.cat(sep="_", na_rep="NA")
52
+ expected = "a_a_b_b_c_NA"
53
+ assert result == expected
54
+
55
+ t = np.array(["a", np.nan, "b", "d", "foo", np.nan], dtype=object)
56
+ expected = box(["aa", "a-", "bb", "bd", "cfoo", "--"])
57
+
58
+ # Series/Index with array
59
+ result = s.str.cat(t, na_rep="-")
60
+ tm.assert_equal(result, expected)
61
+
62
+ # Series/Index with list
63
+ result = s.str.cat(list(t), na_rep="-")
64
+ tm.assert_equal(result, expected)
65
+
66
+ # errors for incorrect lengths
67
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
68
+ z = Series(["1", "2", "3"])
69
+
70
+ with pytest.raises(ValueError, match=rgx):
71
+ s.str.cat(z.values)
72
+
73
+ with pytest.raises(ValueError, match=rgx):
74
+ s.str.cat(list(z))
75
+
76
+
77
+ def test_str_cat_raises_intuitive_error(index_or_series):
78
+ # GH 11334
79
+ box = index_or_series
80
+ s = box(["a", "b", "c", "d"])
81
+ message = "Did you mean to supply a `sep` keyword?"
82
+ with pytest.raises(ValueError, match=message):
83
+ s.str.cat("|")
84
+ with pytest.raises(ValueError, match=message):
85
+ s.str.cat(" ")
86
+
87
+
88
+ @pytest.mark.parametrize(
89
+ "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
90
+ )
91
+ @pytest.mark.parametrize("sep", ["", None])
92
+ @pytest.mark.parametrize("dtype_target", ["object", "category"])
93
+ @pytest.mark.parametrize("dtype_caller", ["object", "category"])
94
+ def test_str_cat_categorical(
95
+ index_or_series, dtype_caller, dtype_target, sep, infer_string
96
+ ):
97
+ box = index_or_series
98
+
99
+ with option_context("future.infer_string", infer_string):
100
+ s = Index(["a", "a", "b", "a"], dtype=dtype_caller)
101
+ s = s if box == Index else Series(s, index=s, dtype=s.dtype)
102
+ t = Index(["b", "a", "b", "c"], dtype=dtype_target)
103
+
104
+ expected = Index(
105
+ ["ab", "aa", "bb", "ac"], dtype=object if dtype_caller == "object" else None
106
+ )
107
+ expected = (
108
+ expected
109
+ if box == Index
110
+ else Series(
111
+ expected, index=Index(s, dtype=dtype_caller), dtype=expected.dtype
112
+ )
113
+ )
114
+
115
+ # Series/Index with unaligned Index -> t.values
116
+ result = s.str.cat(t.values, sep=sep)
117
+ tm.assert_equal(result, expected)
118
+
119
+ # Series/Index with Series having matching Index
120
+ t = Series(t.values, index=Index(s, dtype=dtype_caller))
121
+ result = s.str.cat(t, sep=sep)
122
+ tm.assert_equal(result, expected)
123
+
124
+ # Series/Index with Series.values
125
+ result = s.str.cat(t.values, sep=sep)
126
+ tm.assert_equal(result, expected)
127
+
128
+ # Series/Index with Series having different Index
129
+ t = Series(t.values, index=t.values)
130
+ expected = Index(
131
+ ["aa", "aa", "bb", "bb", "aa"],
132
+ dtype=object if dtype_caller == "object" else None,
133
+ )
134
+ dtype = object if dtype_caller == "object" else s.dtype.categories.dtype
135
+ expected = (
136
+ expected
137
+ if box == Index
138
+ else Series(
139
+ expected,
140
+ index=Index(expected.str[:1], dtype=dtype),
141
+ dtype=expected.dtype,
142
+ )
143
+ )
144
+
145
+ result = s.str.cat(t, sep=sep)
146
+ tm.assert_equal(result, expected)
147
+
148
+
149
+ @pytest.mark.parametrize(
150
+ "data",
151
+ [[1, 2, 3], [0.1, 0.2, 0.3], [1, 2, "b"]],
152
+ ids=["integers", "floats", "mixed"],
153
+ )
154
+ # without dtype=object, np.array would cast [1, 2, 'b'] to ['1', '2', 'b']
155
+ @pytest.mark.parametrize(
156
+ "box",
157
+ [Series, Index, list, lambda x: np.array(x, dtype=object)],
158
+ ids=["Series", "Index", "list", "np.array"],
159
+ )
160
+ def test_str_cat_wrong_dtype_raises(box, data):
161
+ # GH 22722
162
+ s = Series(["a", "b", "c"])
163
+ t = box(data)
164
+
165
+ msg = "Concatenation requires list-likes containing only strings.*"
166
+ with pytest.raises(TypeError, match=msg):
167
+ # need to use outer and na_rep, as otherwise Index would not raise
168
+ s.str.cat(t, join="outer", na_rep="-")
169
+
170
+
171
+ def test_str_cat_mixed_inputs(index_or_series):
172
+ box = index_or_series
173
+ s = Index(["a", "b", "c", "d"])
174
+ s = s if box == Index else Series(s, index=s)
175
+
176
+ t = Series(["A", "B", "C", "D"], index=s.values)
177
+ d = concat([t, Series(s, index=s)], axis=1)
178
+
179
+ expected = Index(["aAa", "bBb", "cCc", "dDd"])
180
+ expected = expected if box == Index else Series(expected.values, index=s.values)
181
+
182
+ # Series/Index with DataFrame
183
+ result = s.str.cat(d)
184
+ tm.assert_equal(result, expected)
185
+
186
+ # Series/Index with two-dimensional ndarray
187
+ result = s.str.cat(d.values)
188
+ tm.assert_equal(result, expected)
189
+
190
+ # Series/Index with list of Series
191
+ result = s.str.cat([t, s])
192
+ tm.assert_equal(result, expected)
193
+
194
+ # Series/Index with mixed list of Series/array
195
+ result = s.str.cat([t, s.values])
196
+ tm.assert_equal(result, expected)
197
+
198
+ # Series/Index with list of Series; different indexes
199
+ t.index = ["b", "c", "d", "a"]
200
+ expected = box(["aDa", "bAb", "cBc", "dCd"])
201
+ expected = expected if box == Index else Series(expected.values, index=s.values)
202
+ result = s.str.cat([t, s])
203
+ tm.assert_equal(result, expected)
204
+
205
+ # Series/Index with mixed list; different index
206
+ result = s.str.cat([t, s.values])
207
+ tm.assert_equal(result, expected)
208
+
209
+ # Series/Index with DataFrame; different indexes
210
+ d.index = ["b", "c", "d", "a"]
211
+ expected = box(["aDd", "bAa", "cBb", "dCc"])
212
+ expected = expected if box == Index else Series(expected.values, index=s.values)
213
+ result = s.str.cat(d)
214
+ tm.assert_equal(result, expected)
215
+
216
+ # errors for incorrect lengths
217
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
218
+ z = Series(["1", "2", "3"])
219
+ e = concat([z, z], axis=1)
220
+
221
+ # two-dimensional ndarray
222
+ with pytest.raises(ValueError, match=rgx):
223
+ s.str.cat(e.values)
224
+
225
+ # list of list-likes
226
+ with pytest.raises(ValueError, match=rgx):
227
+ s.str.cat([z.values, s.values])
228
+
229
+ # mixed list of Series/list-like
230
+ with pytest.raises(ValueError, match=rgx):
231
+ s.str.cat([z.values, s])
232
+
233
+ # errors for incorrect arguments in list-like
234
+ rgx = "others must be Series, Index, DataFrame,.*"
235
+ # make sure None/NaN do not crash checks in _get_series_list
236
+ u = Series(["a", np.nan, "c", None])
237
+
238
+ # mix of string and Series
239
+ with pytest.raises(TypeError, match=rgx):
240
+ s.str.cat([u, "u"])
241
+
242
+ # DataFrame in list
243
+ with pytest.raises(TypeError, match=rgx):
244
+ s.str.cat([u, d])
245
+
246
+ # 2-dim ndarray in list
247
+ with pytest.raises(TypeError, match=rgx):
248
+ s.str.cat([u, d.values])
249
+
250
+ # nested lists
251
+ with pytest.raises(TypeError, match=rgx):
252
+ s.str.cat([u, [u, d]])
253
+
254
+ # forbidden input type: set
255
+ # GH 23009
256
+ with pytest.raises(TypeError, match=rgx):
257
+ s.str.cat(set(u))
258
+
259
+ # forbidden input type: set in list
260
+ # GH 23009
261
+ with pytest.raises(TypeError, match=rgx):
262
+ s.str.cat([u, set(u)])
263
+
264
+ # other forbidden input type, e.g. int
265
+ with pytest.raises(TypeError, match=rgx):
266
+ s.str.cat(1)
267
+
268
+ # nested list-likes
269
+ with pytest.raises(TypeError, match=rgx):
270
+ s.str.cat(iter([t.values, list(s)]))
271
+
272
+
273
+ @pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
274
+ def test_str_cat_align_indexed(index_or_series, join):
275
+ # https://github.com/pandas-dev/pandas/issues/18657
276
+ box = index_or_series
277
+
278
+ s = Series(["a", "b", "c", "d"], index=["a", "b", "c", "d"])
279
+ t = Series(["D", "A", "E", "B"], index=["d", "a", "e", "b"])
280
+ sa, ta = s.align(t, join=join)
281
+ # result after manual alignment of inputs
282
+ expected = sa.str.cat(ta, na_rep="-")
283
+
284
+ if box == Index:
285
+ s = Index(s)
286
+ sa = Index(sa)
287
+ expected = Index(expected)
288
+
289
+ result = s.str.cat(t, join=join, na_rep="-")
290
+ tm.assert_equal(result, expected)
291
+
292
+
293
+ @pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
294
+ def test_str_cat_align_mixed_inputs(join):
295
+ s = Series(["a", "b", "c", "d"])
296
+ t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
297
+ d = concat([t, t], axis=1)
298
+
299
+ expected_outer = Series(["aaa", "bbb", "c--", "ddd", "-ee"])
300
+ expected = expected_outer.loc[s.index.join(t.index, how=join)]
301
+
302
+ # list of Series
303
+ result = s.str.cat([t, t], join=join, na_rep="-")
304
+ tm.assert_series_equal(result, expected)
305
+
306
+ # DataFrame
307
+ result = s.str.cat(d, join=join, na_rep="-")
308
+ tm.assert_series_equal(result, expected)
309
+
310
+ # mixed list of indexed/unindexed
311
+ u = np.array(["A", "B", "C", "D"])
312
+ expected_outer = Series(["aaA", "bbB", "c-C", "ddD", "-e-"])
313
+ # joint index of rhs [t, u]; u will be forced have index of s
314
+ rhs_idx = (
315
+ t.index.intersection(s.index)
316
+ if join == "inner"
317
+ else t.index.union(s.index)
318
+ if join == "outer"
319
+ else t.index.append(s.index.difference(t.index))
320
+ )
321
+
322
+ expected = expected_outer.loc[s.index.join(rhs_idx, how=join)]
323
+ result = s.str.cat([t, u], join=join, na_rep="-")
324
+ tm.assert_series_equal(result, expected)
325
+
326
+ with pytest.raises(TypeError, match="others must be Series,.*"):
327
+ # nested lists are forbidden
328
+ s.str.cat([t, list(u)], join=join)
329
+
330
+ # errors for incorrect lengths
331
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
332
+ z = Series(["1", "2", "3"]).values
333
+
334
+ # unindexed object of wrong length
335
+ with pytest.raises(ValueError, match=rgx):
336
+ s.str.cat(z, join=join)
337
+
338
+ # unindexed object of wrong length in list
339
+ with pytest.raises(ValueError, match=rgx):
340
+ s.str.cat([t, z], join=join)
341
+
342
+
343
+ def test_str_cat_all_na(index_or_series, index_or_series2):
344
+ # GH 24044
345
+ box = index_or_series
346
+ other = index_or_series2
347
+
348
+ # check that all NaNs in caller / target work
349
+ s = Index(["a", "b", "c", "d"])
350
+ s = s if box == Index else Series(s, index=s)
351
+ t = other([np.nan] * 4, dtype=object)
352
+ # add index of s for alignment
353
+ t = t if other == Index else Series(t, index=s)
354
+
355
+ # all-NA target
356
+ if box == Series:
357
+ expected = Series([np.nan] * 4, index=s.index, dtype=s.dtype)
358
+ else: # box == Index
359
+ # TODO: Strimg option, this should return string dtype
360
+ expected = Index([np.nan] * 4, dtype=object)
361
+ result = s.str.cat(t, join="left")
362
+ tm.assert_equal(result, expected)
363
+
364
+ # all-NA caller (only for Series)
365
+ if other == Series:
366
+ expected = Series([np.nan] * 4, dtype=object, index=t.index)
367
+ result = t.str.cat(s, join="left")
368
+ tm.assert_series_equal(result, expected)
369
+
370
+
371
+ def test_str_cat_special_cases():
372
+ s = Series(["a", "b", "c", "d"])
373
+ t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
374
+
375
+ # iterator of elements with different types
376
+ expected = Series(["aaa", "bbb", "c-c", "ddd", "-e-"])
377
+ result = s.str.cat(iter([t, s.values]), join="outer", na_rep="-")
378
+ tm.assert_series_equal(result, expected)
379
+
380
+ # right-align with different indexes in others
381
+ expected = Series(["aa-", "d-d"], index=[0, 3])
382
+ result = s.str.cat([t.loc[[0]], t.loc[[3]]], join="right", na_rep="-")
383
+ tm.assert_series_equal(result, expected)
384
+
385
+
386
+ def test_cat_on_filtered_index():
387
+ df = DataFrame(
388
+ index=MultiIndex.from_product(
389
+ [[2011, 2012], [1, 2, 3]], names=["year", "month"]
390
+ )
391
+ )
392
+
393
+ df = df.reset_index()
394
+ df = df[df.month > 1]
395
+
396
+ str_year = df.year.astype("str")
397
+ str_month = df.month.astype("str")
398
+ str_both = str_year.str.cat(str_month, sep=" ")
399
+
400
+ assert str_both.loc[1] == "2011 2"
401
+
402
+ str_multiple = str_year.str.cat([str_month, str_month], sep=" ")
403
+
404
+ assert str_multiple.loc[1] == "2011 2 2"
405
+
406
+
407
+ @pytest.mark.parametrize("klass", [tuple, list, np.array, Series, Index])
408
+ def test_cat_different_classes(klass):
409
+ # https://github.com/pandas-dev/pandas/issues/33425
410
+ s = Series(["a", "b", "c"])
411
+ result = s.str.cat(klass(["x", "y", "z"]))
412
+ expected = Series(["ax", "by", "cz"])
413
+ tm.assert_series_equal(result, expected)
414
+
415
+
416
+ def test_cat_on_series_dot_str():
417
+ # GH 28277
418
+ ps = Series(["AbC", "de", "FGHI", "j", "kLLLm"])
419
+
420
+ message = re.escape(
421
+ "others must be Series, Index, DataFrame, np.ndarray "
422
+ "or list-like (either containing only strings or "
423
+ "containing only objects of type Series/Index/"
424
+ "np.ndarray[1-dim])"
425
+ )
426
+ with pytest.raises(TypeError, match=message):
427
+ ps.str.cat(others=ps.str)
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_extract.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas.core.dtypes.dtypes import ArrowDtype
8
+
9
+ from pandas import (
10
+ DataFrame,
11
+ Index,
12
+ MultiIndex,
13
+ Series,
14
+ _testing as tm,
15
+ )
16
+
17
+
18
+ def test_extract_expand_kwarg_wrong_type_raises(any_string_dtype):
19
+ # TODO: should this raise TypeError
20
+ values = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
21
+ with pytest.raises(ValueError, match="expand must be True or False"):
22
+ values.str.extract(".*(BAD[_]+).*(BAD)", expand=None)
23
+
24
+
25
+ def test_extract_expand_kwarg(any_string_dtype):
26
+ s = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
27
+ expected = DataFrame(["BAD__", np.nan, np.nan], dtype=any_string_dtype)
28
+
29
+ result = s.str.extract(".*(BAD[_]+).*")
30
+ tm.assert_frame_equal(result, expected)
31
+
32
+ result = s.str.extract(".*(BAD[_]+).*", expand=True)
33
+ tm.assert_frame_equal(result, expected)
34
+
35
+ expected = DataFrame(
36
+ [["BAD__", "BAD"], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
37
+ )
38
+ result = s.str.extract(".*(BAD[_]+).*(BAD)", expand=False)
39
+ tm.assert_frame_equal(result, expected)
40
+
41
+
42
+ def test_extract_expand_False_mixed_object():
43
+ ser = Series(
44
+ ["aBAD_BAD", np.nan, "BAD_b_BAD", True, datetime.today(), "foo", None, 1, 2.0]
45
+ )
46
+
47
+ # two groups
48
+ result = ser.str.extract(".*(BAD[_]+).*(BAD)", expand=False)
49
+ er = [np.nan, np.nan] # empty row
50
+ expected = DataFrame(
51
+ [["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er], dtype=object
52
+ )
53
+ tm.assert_frame_equal(result, expected)
54
+
55
+ # single group
56
+ result = ser.str.extract(".*(BAD[_]+).*BAD", expand=False)
57
+ expected = Series(
58
+ ["BAD_", np.nan, "BAD_", np.nan, np.nan, np.nan, None, np.nan, np.nan],
59
+ dtype=object,
60
+ )
61
+ tm.assert_series_equal(result, expected)
62
+
63
+
64
+ def test_extract_expand_index_raises():
65
+ # GH9980
66
+ # Index only works with one regex group since
67
+ # multi-group would expand to a frame
68
+ idx = Index(["A1", "A2", "A3", "A4", "B5"])
69
+ msg = "only one regex group is supported with Index"
70
+ with pytest.raises(ValueError, match=msg):
71
+ idx.str.extract("([AB])([123])", expand=False)
72
+
73
+
74
+ def test_extract_expand_no_capture_groups_raises(index_or_series, any_string_dtype):
75
+ s_or_idx = index_or_series(["A1", "B2", "C3"], dtype=any_string_dtype)
76
+ msg = "pattern contains no capture groups"
77
+
78
+ # no groups
79
+ with pytest.raises(ValueError, match=msg):
80
+ s_or_idx.str.extract("[ABC][123]", expand=False)
81
+
82
+ # only non-capturing groups
83
+ with pytest.raises(ValueError, match=msg):
84
+ s_or_idx.str.extract("(?:[AB]).*", expand=False)
85
+
86
+
87
+ def test_extract_expand_single_capture_group(index_or_series, any_string_dtype):
88
+ # single group renames series/index properly
89
+ s_or_idx = index_or_series(["A1", "A2"], dtype=any_string_dtype)
90
+ result = s_or_idx.str.extract(r"(?P<uno>A)\d", expand=False)
91
+
92
+ expected = index_or_series(["A", "A"], name="uno", dtype=any_string_dtype)
93
+ if index_or_series == Series:
94
+ tm.assert_series_equal(result, expected)
95
+ else:
96
+ tm.assert_index_equal(result, expected)
97
+
98
+
99
+ def test_extract_expand_capture_groups(any_string_dtype):
100
+ s = Series(["A1", "B2", "C3"], dtype=any_string_dtype)
101
+ # one group, no matches
102
+ result = s.str.extract("(_)", expand=False)
103
+ expected = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype)
104
+ tm.assert_series_equal(result, expected)
105
+
106
+ # two groups, no matches
107
+ result = s.str.extract("(_)(_)", expand=False)
108
+ expected = DataFrame(
109
+ [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
110
+ )
111
+ tm.assert_frame_equal(result, expected)
112
+
113
+ # one group, some matches
114
+ result = s.str.extract("([AB])[123]", expand=False)
115
+ expected = Series(["A", "B", np.nan], dtype=any_string_dtype)
116
+ tm.assert_series_equal(result, expected)
117
+
118
+ # two groups, some matches
119
+ result = s.str.extract("([AB])([123])", expand=False)
120
+ expected = DataFrame(
121
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
122
+ )
123
+ tm.assert_frame_equal(result, expected)
124
+
125
+ # one named group
126
+ result = s.str.extract("(?P<letter>[AB])", expand=False)
127
+ expected = Series(["A", "B", np.nan], name="letter", dtype=any_string_dtype)
128
+ tm.assert_series_equal(result, expected)
129
+
130
+ # two named groups
131
+ result = s.str.extract("(?P<letter>[AB])(?P<number>[123])", expand=False)
132
+ expected = DataFrame(
133
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
134
+ columns=["letter", "number"],
135
+ dtype=any_string_dtype,
136
+ )
137
+ tm.assert_frame_equal(result, expected)
138
+
139
+ # mix named and unnamed groups
140
+ result = s.str.extract("([AB])(?P<number>[123])", expand=False)
141
+ expected = DataFrame(
142
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
143
+ columns=[0, "number"],
144
+ dtype=any_string_dtype,
145
+ )
146
+ tm.assert_frame_equal(result, expected)
147
+
148
+ # one normal group, one non-capturing group
149
+ result = s.str.extract("([AB])(?:[123])", expand=False)
150
+ expected = Series(["A", "B", np.nan], dtype=any_string_dtype)
151
+ tm.assert_series_equal(result, expected)
152
+
153
+ # two normal groups, one non-capturing group
154
+ s = Series(["A11", "B22", "C33"], dtype=any_string_dtype)
155
+ result = s.str.extract("([AB])([123])(?:[123])", expand=False)
156
+ expected = DataFrame(
157
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
158
+ )
159
+ tm.assert_frame_equal(result, expected)
160
+
161
+ # one optional group followed by one normal group
162
+ s = Series(["A1", "B2", "3"], dtype=any_string_dtype)
163
+ result = s.str.extract("(?P<letter>[AB])?(?P<number>[123])", expand=False)
164
+ expected = DataFrame(
165
+ [["A", "1"], ["B", "2"], [np.nan, "3"]],
166
+ columns=["letter", "number"],
167
+ dtype=any_string_dtype,
168
+ )
169
+ tm.assert_frame_equal(result, expected)
170
+
171
+ # one normal group followed by one optional group
172
+ s = Series(["A1", "B2", "C"], dtype=any_string_dtype)
173
+ result = s.str.extract("(?P<letter>[ABC])(?P<number>[123])?", expand=False)
174
+ expected = DataFrame(
175
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
176
+ columns=["letter", "number"],
177
+ dtype=any_string_dtype,
178
+ )
179
+ tm.assert_frame_equal(result, expected)
180
+
181
+
182
+ def test_extract_expand_capture_groups_index(index, any_string_dtype):
183
+ # https://github.com/pandas-dev/pandas/issues/6348
184
+ # not passing index to the extractor
185
+ data = ["A1", "B2", "C"]
186
+
187
+ if len(index) == 0:
188
+ pytest.skip("Test requires len(index) > 0")
189
+ while len(index) < len(data):
190
+ index = index.repeat(2)
191
+
192
+ index = index[: len(data)]
193
+ ser = Series(data, index=index, dtype=any_string_dtype)
194
+
195
+ result = ser.str.extract(r"(\d)", expand=False)
196
+ expected = Series(["1", "2", np.nan], index=index, dtype=any_string_dtype)
197
+ tm.assert_series_equal(result, expected)
198
+
199
+ result = ser.str.extract(r"(?P<letter>\D)(?P<number>\d)?", expand=False)
200
+ expected = DataFrame(
201
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
202
+ columns=["letter", "number"],
203
+ index=index,
204
+ dtype=any_string_dtype,
205
+ )
206
+ tm.assert_frame_equal(result, expected)
207
+
208
+
209
+ def test_extract_single_series_name_is_preserved(any_string_dtype):
210
+ s = Series(["a3", "b3", "c2"], name="bob", dtype=any_string_dtype)
211
+ result = s.str.extract(r"(?P<sue>[a-z])", expand=False)
212
+ expected = Series(["a", "b", "c"], name="sue", dtype=any_string_dtype)
213
+ tm.assert_series_equal(result, expected)
214
+
215
+
216
+ def test_extract_expand_True(any_string_dtype):
217
+ # Contains tests like those in test_match and some others.
218
+ s = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
219
+
220
+ result = s.str.extract(".*(BAD[_]+).*(BAD)", expand=True)
221
+ expected = DataFrame(
222
+ [["BAD__", "BAD"], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
223
+ )
224
+ tm.assert_frame_equal(result, expected)
225
+
226
+
227
+ def test_extract_expand_True_mixed_object():
228
+ er = [np.nan, np.nan] # empty row
229
+ mixed = Series(
230
+ [
231
+ "aBAD_BAD",
232
+ np.nan,
233
+ "BAD_b_BAD",
234
+ True,
235
+ datetime.today(),
236
+ "foo",
237
+ None,
238
+ 1,
239
+ 2.0,
240
+ ]
241
+ )
242
+
243
+ result = mixed.str.extract(".*(BAD[_]+).*(BAD)", expand=True)
244
+ expected = DataFrame(
245
+ [["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er], dtype=object
246
+ )
247
+ tm.assert_frame_equal(result, expected)
248
+
249
+
250
+ def test_extract_expand_True_single_capture_group_raises(
251
+ index_or_series, any_string_dtype
252
+ ):
253
+ # these should work for both Series and Index
254
+ # no groups
255
+ s_or_idx = index_or_series(["A1", "B2", "C3"], dtype=any_string_dtype)
256
+ msg = "pattern contains no capture groups"
257
+ with pytest.raises(ValueError, match=msg):
258
+ s_or_idx.str.extract("[ABC][123]", expand=True)
259
+
260
+ # only non-capturing groups
261
+ with pytest.raises(ValueError, match=msg):
262
+ s_or_idx.str.extract("(?:[AB]).*", expand=True)
263
+
264
+
265
+ def test_extract_expand_True_single_capture_group(index_or_series, any_string_dtype):
266
+ # single group renames series/index properly
267
+ s_or_idx = index_or_series(["A1", "A2"], dtype=any_string_dtype)
268
+ result = s_or_idx.str.extract(r"(?P<uno>A)\d", expand=True)
269
+ expected = DataFrame({"uno": ["A", "A"]}, dtype=any_string_dtype)
270
+ tm.assert_frame_equal(result, expected)
271
+
272
+
273
+ @pytest.mark.parametrize("name", [None, "series_name"])
274
+ def test_extract_series(name, any_string_dtype):
275
+ # extract should give the same result whether or not the series has a name.
276
+ s = Series(["A1", "B2", "C3"], name=name, dtype=any_string_dtype)
277
+
278
+ # one group, no matches
279
+ result = s.str.extract("(_)", expand=True)
280
+ expected = DataFrame([np.nan, np.nan, np.nan], dtype=any_string_dtype)
281
+ tm.assert_frame_equal(result, expected)
282
+
283
+ # two groups, no matches
284
+ result = s.str.extract("(_)(_)", expand=True)
285
+ expected = DataFrame(
286
+ [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
287
+ )
288
+ tm.assert_frame_equal(result, expected)
289
+
290
+ # one group, some matches
291
+ result = s.str.extract("([AB])[123]", expand=True)
292
+ expected = DataFrame(["A", "B", np.nan], dtype=any_string_dtype)
293
+ tm.assert_frame_equal(result, expected)
294
+
295
+ # two groups, some matches
296
+ result = s.str.extract("([AB])([123])", expand=True)
297
+ expected = DataFrame(
298
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
299
+ )
300
+ tm.assert_frame_equal(result, expected)
301
+
302
+ # one named group
303
+ result = s.str.extract("(?P<letter>[AB])", expand=True)
304
+ expected = DataFrame({"letter": ["A", "B", np.nan]}, dtype=any_string_dtype)
305
+ tm.assert_frame_equal(result, expected)
306
+
307
+ # two named groups
308
+ result = s.str.extract("(?P<letter>[AB])(?P<number>[123])", expand=True)
309
+ expected = DataFrame(
310
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
311
+ columns=["letter", "number"],
312
+ dtype=any_string_dtype,
313
+ )
314
+ tm.assert_frame_equal(result, expected)
315
+
316
+ # mix named and unnamed groups
317
+ result = s.str.extract("([AB])(?P<number>[123])", expand=True)
318
+ expected = DataFrame(
319
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
320
+ columns=[0, "number"],
321
+ dtype=any_string_dtype,
322
+ )
323
+ tm.assert_frame_equal(result, expected)
324
+
325
+ # one normal group, one non-capturing group
326
+ result = s.str.extract("([AB])(?:[123])", expand=True)
327
+ expected = DataFrame(["A", "B", np.nan], dtype=any_string_dtype)
328
+ tm.assert_frame_equal(result, expected)
329
+
330
+
331
+ def test_extract_optional_groups(any_string_dtype):
332
+ # two normal groups, one non-capturing group
333
+ s = Series(["A11", "B22", "C33"], dtype=any_string_dtype)
334
+ result = s.str.extract("([AB])([123])(?:[123])", expand=True)
335
+ expected = DataFrame(
336
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
337
+ )
338
+ tm.assert_frame_equal(result, expected)
339
+
340
+ # one optional group followed by one normal group
341
+ s = Series(["A1", "B2", "3"], dtype=any_string_dtype)
342
+ result = s.str.extract("(?P<letter>[AB])?(?P<number>[123])", expand=True)
343
+ expected = DataFrame(
344
+ [["A", "1"], ["B", "2"], [np.nan, "3"]],
345
+ columns=["letter", "number"],
346
+ dtype=any_string_dtype,
347
+ )
348
+ tm.assert_frame_equal(result, expected)
349
+
350
+ # one normal group followed by one optional group
351
+ s = Series(["A1", "B2", "C"], dtype=any_string_dtype)
352
+ result = s.str.extract("(?P<letter>[ABC])(?P<number>[123])?", expand=True)
353
+ expected = DataFrame(
354
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
355
+ columns=["letter", "number"],
356
+ dtype=any_string_dtype,
357
+ )
358
+ tm.assert_frame_equal(result, expected)
359
+
360
+
361
+ def test_extract_dataframe_capture_groups_index(index, any_string_dtype):
362
+ # GH6348
363
+ # not passing index to the extractor
364
+
365
+ data = ["A1", "B2", "C"]
366
+
367
+ if len(index) < len(data):
368
+ pytest.skip(f"Index needs more than {len(data)} values")
369
+
370
+ index = index[: len(data)]
371
+ s = Series(data, index=index, dtype=any_string_dtype)
372
+
373
+ result = s.str.extract(r"(\d)", expand=True)
374
+ expected = DataFrame(["1", "2", np.nan], index=index, dtype=any_string_dtype)
375
+ tm.assert_frame_equal(result, expected)
376
+
377
+ result = s.str.extract(r"(?P<letter>\D)(?P<number>\d)?", expand=True)
378
+ expected = DataFrame(
379
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
380
+ columns=["letter", "number"],
381
+ index=index,
382
+ dtype=any_string_dtype,
383
+ )
384
+ tm.assert_frame_equal(result, expected)
385
+
386
+
387
+ def test_extract_single_group_returns_frame(any_string_dtype):
388
+ # GH11386 extract should always return DataFrame, even when
389
+ # there is only one group. Prior to v0.18.0, extract returned
390
+ # Series when there was only one group in the regex.
391
+ s = Series(["a3", "b3", "c2"], name="series_name", dtype=any_string_dtype)
392
+ result = s.str.extract(r"(?P<letter>[a-z])", expand=True)
393
+ expected = DataFrame({"letter": ["a", "b", "c"]}, dtype=any_string_dtype)
394
+ tm.assert_frame_equal(result, expected)
395
+
396
+
397
+ def test_extractall(any_string_dtype):
398
+ data = [
399
400
401
402
403
404
+ np.nan,
405
+ "",
406
+ ]
407
+ expected_tuples = [
408
+ ("dave", "google", "com"),
409
+ ("tdhock5", "gmail", "com"),
410
+ ("maudelaperriere", "gmail", "com"),
411
+ ("rob", "gmail", "com"),
412
+ ("steve", "gmail", "com"),
413
+ ("a", "b", "com"),
414
+ ("c", "d", "com"),
415
+ ("e", "f", "com"),
416
+ ]
417
+ pat = r"""
418
+ (?P<user>[a-z0-9]+)
419
+ @
420
+ (?P<domain>[a-z]+)
421
+ \.
422
+ (?P<tld>[a-z]{2,4})
423
+ """
424
+ expected_columns = ["user", "domain", "tld"]
425
+ s = Series(data, dtype=any_string_dtype)
426
+ # extractall should return a DataFrame with one row for each match, indexed by the
427
+ # subject from which the match came.
428
+ expected_index = MultiIndex.from_tuples(
429
+ [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 0), (4, 1), (4, 2)],
430
+ names=(None, "match"),
431
+ )
432
+ expected = DataFrame(
433
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
434
+ )
435
+ result = s.str.extractall(pat, flags=re.VERBOSE)
436
+ tm.assert_frame_equal(result, expected)
437
+
438
+ # The index of the input Series should be used to construct the index of the output
439
+ # DataFrame:
440
+ mi = MultiIndex.from_tuples(
441
+ [
442
+ ("single", "Dave"),
443
+ ("single", "Toby"),
444
+ ("single", "Maude"),
445
+ ("multiple", "robAndSteve"),
446
+ ("multiple", "abcdef"),
447
+ ("none", "missing"),
448
+ ("none", "empty"),
449
+ ]
450
+ )
451
+ s = Series(data, index=mi, dtype=any_string_dtype)
452
+ expected_index = MultiIndex.from_tuples(
453
+ [
454
+ ("single", "Dave", 0),
455
+ ("single", "Toby", 0),
456
+ ("single", "Maude", 0),
457
+ ("multiple", "robAndSteve", 0),
458
+ ("multiple", "robAndSteve", 1),
459
+ ("multiple", "abcdef", 0),
460
+ ("multiple", "abcdef", 1),
461
+ ("multiple", "abcdef", 2),
462
+ ],
463
+ names=(None, None, "match"),
464
+ )
465
+ expected = DataFrame(
466
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
467
+ )
468
+ result = s.str.extractall(pat, flags=re.VERBOSE)
469
+ tm.assert_frame_equal(result, expected)
470
+
471
+ # MultiIndexed subject with names.
472
+ s = Series(data, index=mi, dtype=any_string_dtype)
473
+ s.index.names = ("matches", "description")
474
+ expected_index.names = ("matches", "description", "match")
475
+ expected = DataFrame(
476
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
477
+ )
478
+ result = s.str.extractall(pat, flags=re.VERBOSE)
479
+ tm.assert_frame_equal(result, expected)
480
+
481
+
482
+ @pytest.mark.parametrize(
483
+ "pat,expected_names",
484
+ [
485
+ # optional groups.
486
+ ("(?P<letter>[AB])?(?P<number>[123])", ["letter", "number"]),
487
+ # only one of two groups has a name.
488
+ ("([AB])?(?P<number>[123])", [0, "number"]),
489
+ ],
490
+ )
491
+ def test_extractall_column_names(pat, expected_names, any_string_dtype):
492
+ s = Series(["", "A1", "32"], dtype=any_string_dtype)
493
+
494
+ result = s.str.extractall(pat)
495
+ expected = DataFrame(
496
+ [("A", "1"), (np.nan, "3"), (np.nan, "2")],
497
+ index=MultiIndex.from_tuples([(1, 0), (2, 0), (2, 1)], names=(None, "match")),
498
+ columns=expected_names,
499
+ dtype=any_string_dtype,
500
+ )
501
+ tm.assert_frame_equal(result, expected)
502
+
503
+
504
+ def test_extractall_single_group(any_string_dtype):
505
+ s = Series(["a3", "b3", "d4c2"], name="series_name", dtype=any_string_dtype)
506
+ expected_index = MultiIndex.from_tuples(
507
+ [(0, 0), (1, 0), (2, 0), (2, 1)], names=(None, "match")
508
+ )
509
+
510
+ # extractall(one named group) returns DataFrame with one named column.
511
+ result = s.str.extractall(r"(?P<letter>[a-z])")
512
+ expected = DataFrame(
513
+ {"letter": ["a", "b", "d", "c"]}, index=expected_index, dtype=any_string_dtype
514
+ )
515
+ tm.assert_frame_equal(result, expected)
516
+
517
+ # extractall(one un-named group) returns DataFrame with one un-named column.
518
+ result = s.str.extractall(r"([a-z])")
519
+ expected = DataFrame(
520
+ ["a", "b", "d", "c"], index=expected_index, dtype=any_string_dtype
521
+ )
522
+ tm.assert_frame_equal(result, expected)
523
+
524
+
525
+ def test_extractall_single_group_with_quantifier(any_string_dtype):
526
+ # GH#13382
527
+ # extractall(one un-named group with quantifier) returns DataFrame with one un-named
528
+ # column.
529
+ s = Series(["ab3", "abc3", "d4cd2"], name="series_name", dtype=any_string_dtype)
530
+ result = s.str.extractall(r"([a-z]+)")
531
+ expected = DataFrame(
532
+ ["ab", "abc", "d", "cd"],
533
+ index=MultiIndex.from_tuples(
534
+ [(0, 0), (1, 0), (2, 0), (2, 1)], names=(None, "match")
535
+ ),
536
+ dtype=any_string_dtype,
537
+ )
538
+ tm.assert_frame_equal(result, expected)
539
+
540
+
541
+ @pytest.mark.parametrize(
542
+ "data, names",
543
+ [
544
+ ([], (None,)),
545
+ ([], ("i1",)),
546
+ ([], (None, "i2")),
547
+ ([], ("i1", "i2")),
548
+ (["a3", "b3", "d4c2"], (None,)),
549
+ (["a3", "b3", "d4c2"], ("i1", "i2")),
550
+ (["a3", "b3", "d4c2"], (None, "i2")),
551
+ (["a3", "b3", "d4c2"], ("i1", "i2")),
552
+ ],
553
+ )
554
+ def test_extractall_no_matches(data, names, any_string_dtype):
555
+ # GH19075 extractall with no matches should return a valid MultiIndex
556
+ n = len(data)
557
+ if len(names) == 1:
558
+ index = Index(range(n), name=names[0])
559
+ else:
560
+ tuples = (tuple([i] * (n - 1)) for i in range(n))
561
+ index = MultiIndex.from_tuples(tuples, names=names)
562
+ s = Series(data, name="series_name", index=index, dtype=any_string_dtype)
563
+ expected_index = MultiIndex.from_tuples([], names=(names + ("match",)))
564
+
565
+ # one un-named group.
566
+ result = s.str.extractall("(z)")
567
+ expected = DataFrame(columns=[0], index=expected_index, dtype=any_string_dtype)
568
+ tm.assert_frame_equal(result, expected)
569
+
570
+ # two un-named groups.
571
+ result = s.str.extractall("(z)(z)")
572
+ expected = DataFrame(columns=[0, 1], index=expected_index, dtype=any_string_dtype)
573
+ tm.assert_frame_equal(result, expected)
574
+
575
+ # one named group.
576
+ result = s.str.extractall("(?P<first>z)")
577
+ expected = DataFrame(
578
+ columns=["first"], index=expected_index, dtype=any_string_dtype
579
+ )
580
+ tm.assert_frame_equal(result, expected)
581
+
582
+ # two named groups.
583
+ result = s.str.extractall("(?P<first>z)(?P<second>z)")
584
+ expected = DataFrame(
585
+ columns=["first", "second"], index=expected_index, dtype=any_string_dtype
586
+ )
587
+ tm.assert_frame_equal(result, expected)
588
+
589
+ # one named, one un-named.
590
+ result = s.str.extractall("(z)(?P<second>z)")
591
+ expected = DataFrame(
592
+ columns=[0, "second"], index=expected_index, dtype=any_string_dtype
593
+ )
594
+ tm.assert_frame_equal(result, expected)
595
+
596
+
597
+ def test_extractall_stringindex(any_string_dtype):
598
+ s = Series(["a1a2", "b1", "c1"], name="xxx", dtype=any_string_dtype)
599
+ result = s.str.extractall(r"[ab](?P<digit>\d)")
600
+ expected = DataFrame(
601
+ {"digit": ["1", "2", "1"]},
602
+ index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0)], names=[None, "match"]),
603
+ dtype=any_string_dtype,
604
+ )
605
+ tm.assert_frame_equal(result, expected)
606
+
607
+ # index should return the same result as the default index without name thus
608
+ # index.name doesn't affect to the result
609
+ if any_string_dtype == "object":
610
+ for idx in [
611
+ Index(["a1a2", "b1", "c1"], dtype=object),
612
+ Index(["a1a2", "b1", "c1"], name="xxx", dtype=object),
613
+ ]:
614
+ result = idx.str.extractall(r"[ab](?P<digit>\d)")
615
+ tm.assert_frame_equal(result, expected)
616
+
617
+ s = Series(
618
+ ["a1a2", "b1", "c1"],
619
+ name="s_name",
620
+ index=Index(["XX", "yy", "zz"], name="idx_name"),
621
+ dtype=any_string_dtype,
622
+ )
623
+ result = s.str.extractall(r"[ab](?P<digit>\d)")
624
+ expected = DataFrame(
625
+ {"digit": ["1", "2", "1"]},
626
+ index=MultiIndex.from_tuples(
627
+ [("XX", 0), ("XX", 1), ("yy", 0)], names=["idx_name", "match"]
628
+ ),
629
+ dtype=any_string_dtype,
630
+ )
631
+ tm.assert_frame_equal(result, expected)
632
+
633
+
634
+ def test_extractall_no_capture_groups_raises(any_string_dtype):
635
+ # Does not make sense to use extractall with a regex that has no capture groups.
636
+ # (it returns DataFrame with one column for each capture group)
637
+ s = Series(["a3", "b3", "d4c2"], name="series_name", dtype=any_string_dtype)
638
+ with pytest.raises(ValueError, match="no capture groups"):
639
+ s.str.extractall(r"[a-z]")
640
+
641
+
642
+ def test_extract_index_one_two_groups():
643
+ s = Series(["a3", "b3", "d4c2"], index=["A3", "B3", "D4"], name="series_name")
644
+ r = s.index.str.extract(r"([A-Z])", expand=True)
645
+ e = DataFrame(["A", "B", "D"])
646
+ tm.assert_frame_equal(r, e)
647
+
648
+ # Prior to v0.18.0, index.str.extract(regex with one group)
649
+ # returned Index. With more than one group, extract raised an
650
+ # error (GH9980). Now extract always returns DataFrame.
651
+ r = s.index.str.extract(r"(?P<letter>[A-Z])(?P<digit>[0-9])", expand=True)
652
+ e_list = [("A", "3"), ("B", "3"), ("D", "4")]
653
+ e = DataFrame(e_list, columns=["letter", "digit"])
654
+ tm.assert_frame_equal(r, e)
655
+
656
+
657
+ def test_extractall_same_as_extract(any_string_dtype):
658
+ s = Series(["a3", "b3", "c2"], name="series_name", dtype=any_string_dtype)
659
+
660
+ pattern_two_noname = r"([a-z])([0-9])"
661
+ extract_two_noname = s.str.extract(pattern_two_noname, expand=True)
662
+ has_multi_index = s.str.extractall(pattern_two_noname)
663
+ no_multi_index = has_multi_index.xs(0, level="match")
664
+ tm.assert_frame_equal(extract_two_noname, no_multi_index)
665
+
666
+ pattern_two_named = r"(?P<letter>[a-z])(?P<digit>[0-9])"
667
+ extract_two_named = s.str.extract(pattern_two_named, expand=True)
668
+ has_multi_index = s.str.extractall(pattern_two_named)
669
+ no_multi_index = has_multi_index.xs(0, level="match")
670
+ tm.assert_frame_equal(extract_two_named, no_multi_index)
671
+
672
+ pattern_one_named = r"(?P<group_name>[a-z])"
673
+ extract_one_named = s.str.extract(pattern_one_named, expand=True)
674
+ has_multi_index = s.str.extractall(pattern_one_named)
675
+ no_multi_index = has_multi_index.xs(0, level="match")
676
+ tm.assert_frame_equal(extract_one_named, no_multi_index)
677
+
678
+ pattern_one_noname = r"([a-z])"
679
+ extract_one_noname = s.str.extract(pattern_one_noname, expand=True)
680
+ has_multi_index = s.str.extractall(pattern_one_noname)
681
+ no_multi_index = has_multi_index.xs(0, level="match")
682
+ tm.assert_frame_equal(extract_one_noname, no_multi_index)
683
+
684
+
685
+ def test_extractall_same_as_extract_subject_index(any_string_dtype):
686
+ # same as above tests, but s has an MultiIndex.
687
+ mi = MultiIndex.from_tuples(
688
+ [("A", "first"), ("B", "second"), ("C", "third")],
689
+ names=("capital", "ordinal"),
690
+ )
691
+ s = Series(["a3", "b3", "c2"], index=mi, name="series_name", dtype=any_string_dtype)
692
+
693
+ pattern_two_noname = r"([a-z])([0-9])"
694
+ extract_two_noname = s.str.extract(pattern_two_noname, expand=True)
695
+ has_match_index = s.str.extractall(pattern_two_noname)
696
+ no_match_index = has_match_index.xs(0, level="match")
697
+ tm.assert_frame_equal(extract_two_noname, no_match_index)
698
+
699
+ pattern_two_named = r"(?P<letter>[a-z])(?P<digit>[0-9])"
700
+ extract_two_named = s.str.extract(pattern_two_named, expand=True)
701
+ has_match_index = s.str.extractall(pattern_two_named)
702
+ no_match_index = has_match_index.xs(0, level="match")
703
+ tm.assert_frame_equal(extract_two_named, no_match_index)
704
+
705
+ pattern_one_named = r"(?P<group_name>[a-z])"
706
+ extract_one_named = s.str.extract(pattern_one_named, expand=True)
707
+ has_match_index = s.str.extractall(pattern_one_named)
708
+ no_match_index = has_match_index.xs(0, level="match")
709
+ tm.assert_frame_equal(extract_one_named, no_match_index)
710
+
711
+ pattern_one_noname = r"([a-z])"
712
+ extract_one_noname = s.str.extract(pattern_one_noname, expand=True)
713
+ has_match_index = s.str.extractall(pattern_one_noname)
714
+ no_match_index = has_match_index.xs(0, level="match")
715
+ tm.assert_frame_equal(extract_one_noname, no_match_index)
716
+
717
+
718
+ def test_extractall_preserves_dtype():
719
+ # Ensure that when extractall is called on a series with specific dtypes set, that
720
+ # the dtype is preserved in the resulting DataFrame's column.
721
+ pa = pytest.importorskip("pyarrow")
722
+
723
+ result = Series(["abc", "ab"], dtype=ArrowDtype(pa.string())).str.extractall("(ab)")
724
+ assert result.dtypes[0] == "string[pyarrow]"
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_find_replace.py ADDED
@@ -0,0 +1,972 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas.errors import PerformanceWarning
8
+ import pandas.util._test_decorators as td
9
+
10
+ import pandas as pd
11
+ from pandas import (
12
+ Series,
13
+ _testing as tm,
14
+ )
15
+ from pandas.tests.strings import (
16
+ _convert_na_value,
17
+ object_pyarrow_numpy,
18
+ )
19
+
20
+ # --------------------------------------------------------------------------------------
21
+ # str.contains
22
+ # --------------------------------------------------------------------------------------
23
+
24
+
25
+ def using_pyarrow(dtype):
26
+ return dtype in ("string[pyarrow]", "string[pyarrow_numpy]")
27
+
28
+
29
+ def test_contains(any_string_dtype):
30
+ values = np.array(
31
+ ["foo", np.nan, "fooommm__foo", "mmm_", "foommm[_]+bar"], dtype=np.object_
32
+ )
33
+ values = Series(values, dtype=any_string_dtype)
34
+ pat = "mmm[_]+"
35
+
36
+ result = values.str.contains(pat)
37
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
38
+ expected = Series(
39
+ np.array([False, np.nan, True, True, False], dtype=np.object_),
40
+ dtype=expected_dtype,
41
+ )
42
+ tm.assert_series_equal(result, expected)
43
+
44
+ result = values.str.contains(pat, regex=False)
45
+ expected = Series(
46
+ np.array([False, np.nan, False, False, True], dtype=np.object_),
47
+ dtype=expected_dtype,
48
+ )
49
+ tm.assert_series_equal(result, expected)
50
+
51
+ values = Series(
52
+ np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=object),
53
+ dtype=any_string_dtype,
54
+ )
55
+ result = values.str.contains(pat)
56
+ expected_dtype = np.bool_ if any_string_dtype in object_pyarrow_numpy else "boolean"
57
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
58
+ tm.assert_series_equal(result, expected)
59
+
60
+ # case insensitive using regex
61
+ values = Series(
62
+ np.array(["Foo", "xYz", "fOOomMm__fOo", "MMM_"], dtype=object),
63
+ dtype=any_string_dtype,
64
+ )
65
+
66
+ result = values.str.contains("FOO|mmm", case=False)
67
+ expected = Series(np.array([True, False, True, True]), dtype=expected_dtype)
68
+ tm.assert_series_equal(result, expected)
69
+
70
+ # case insensitive without regex
71
+ result = values.str.contains("foo", regex=False, case=False)
72
+ expected = Series(np.array([True, False, True, False]), dtype=expected_dtype)
73
+ tm.assert_series_equal(result, expected)
74
+
75
+ # unicode
76
+ values = Series(
77
+ np.array(["foo", np.nan, "fooommm__foo", "mmm_"], dtype=np.object_),
78
+ dtype=any_string_dtype,
79
+ )
80
+ pat = "mmm[_]+"
81
+
82
+ result = values.str.contains(pat)
83
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
84
+ expected = Series(
85
+ np.array([False, np.nan, True, True], dtype=np.object_), dtype=expected_dtype
86
+ )
87
+ tm.assert_series_equal(result, expected)
88
+
89
+ result = values.str.contains(pat, na=False)
90
+ expected_dtype = np.bool_ if any_string_dtype in object_pyarrow_numpy else "boolean"
91
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
92
+ tm.assert_series_equal(result, expected)
93
+
94
+ values = Series(
95
+ np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=np.object_),
96
+ dtype=any_string_dtype,
97
+ )
98
+ result = values.str.contains(pat)
99
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
100
+ tm.assert_series_equal(result, expected)
101
+
102
+
103
+ def test_contains_object_mixed():
104
+ mixed = Series(
105
+ np.array(
106
+ ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
107
+ dtype=object,
108
+ )
109
+ )
110
+ result = mixed.str.contains("o")
111
+ expected = Series(
112
+ np.array(
113
+ [False, np.nan, False, np.nan, np.nan, True, None, np.nan, np.nan],
114
+ dtype=np.object_,
115
+ )
116
+ )
117
+ tm.assert_series_equal(result, expected)
118
+
119
+
120
+ def test_contains_na_kwarg_for_object_category():
121
+ # gh 22158
122
+
123
+ # na for category
124
+ values = Series(["a", "b", "c", "a", np.nan], dtype="category")
125
+ result = values.str.contains("a", na=True)
126
+ expected = Series([True, False, False, True, True])
127
+ tm.assert_series_equal(result, expected)
128
+
129
+ result = values.str.contains("a", na=False)
130
+ expected = Series([True, False, False, True, False])
131
+ tm.assert_series_equal(result, expected)
132
+
133
+ # na for objects
134
+ values = Series(["a", "b", "c", "a", np.nan])
135
+ result = values.str.contains("a", na=True)
136
+ expected = Series([True, False, False, True, True])
137
+ tm.assert_series_equal(result, expected)
138
+
139
+ result = values.str.contains("a", na=False)
140
+ expected = Series([True, False, False, True, False])
141
+ tm.assert_series_equal(result, expected)
142
+
143
+
144
+ @pytest.mark.parametrize(
145
+ "na, expected",
146
+ [
147
+ (None, pd.NA),
148
+ (True, True),
149
+ (False, False),
150
+ (0, False),
151
+ (3, True),
152
+ (np.nan, pd.NA),
153
+ ],
154
+ )
155
+ @pytest.mark.parametrize("regex", [True, False])
156
+ def test_contains_na_kwarg_for_nullable_string_dtype(
157
+ nullable_string_dtype, na, expected, regex
158
+ ):
159
+ # https://github.com/pandas-dev/pandas/pull/41025#issuecomment-824062416
160
+
161
+ values = Series(["a", "b", "c", "a", np.nan], dtype=nullable_string_dtype)
162
+ result = values.str.contains("a", na=na, regex=regex)
163
+ expected = Series([True, False, False, True, expected], dtype="boolean")
164
+ tm.assert_series_equal(result, expected)
165
+
166
+
167
+ def test_contains_moar(any_string_dtype):
168
+ # PR #1179
169
+ s = Series(
170
+ ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"],
171
+ dtype=any_string_dtype,
172
+ )
173
+
174
+ result = s.str.contains("a")
175
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
176
+ expected = Series(
177
+ [False, False, False, True, True, False, np.nan, False, False, True],
178
+ dtype=expected_dtype,
179
+ )
180
+ tm.assert_series_equal(result, expected)
181
+
182
+ result = s.str.contains("a", case=False)
183
+ expected = Series(
184
+ [True, False, False, True, True, False, np.nan, True, False, True],
185
+ dtype=expected_dtype,
186
+ )
187
+ tm.assert_series_equal(result, expected)
188
+
189
+ result = s.str.contains("Aa")
190
+ expected = Series(
191
+ [False, False, False, True, False, False, np.nan, False, False, False],
192
+ dtype=expected_dtype,
193
+ )
194
+ tm.assert_series_equal(result, expected)
195
+
196
+ result = s.str.contains("ba")
197
+ expected = Series(
198
+ [False, False, False, True, False, False, np.nan, False, False, False],
199
+ dtype=expected_dtype,
200
+ )
201
+ tm.assert_series_equal(result, expected)
202
+
203
+ result = s.str.contains("ba", case=False)
204
+ expected = Series(
205
+ [False, False, False, True, True, False, np.nan, True, False, False],
206
+ dtype=expected_dtype,
207
+ )
208
+ tm.assert_series_equal(result, expected)
209
+
210
+
211
+ def test_contains_nan(any_string_dtype):
212
+ # PR #14171
213
+ s = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype)
214
+
215
+ result = s.str.contains("foo", na=False)
216
+ expected_dtype = np.bool_ if any_string_dtype in object_pyarrow_numpy else "boolean"
217
+ expected = Series([False, False, False], dtype=expected_dtype)
218
+ tm.assert_series_equal(result, expected)
219
+
220
+ result = s.str.contains("foo", na=True)
221
+ expected = Series([True, True, True], dtype=expected_dtype)
222
+ tm.assert_series_equal(result, expected)
223
+
224
+ result = s.str.contains("foo", na="foo")
225
+ if any_string_dtype == "object":
226
+ expected = Series(["foo", "foo", "foo"], dtype=np.object_)
227
+ elif any_string_dtype == "string[pyarrow_numpy]":
228
+ expected = Series([True, True, True], dtype=np.bool_)
229
+ else:
230
+ expected = Series([True, True, True], dtype="boolean")
231
+ tm.assert_series_equal(result, expected)
232
+
233
+ result = s.str.contains("foo")
234
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
235
+ expected = Series([np.nan, np.nan, np.nan], dtype=expected_dtype)
236
+ tm.assert_series_equal(result, expected)
237
+
238
+
239
+ # --------------------------------------------------------------------------------------
240
+ # str.startswith
241
+ # --------------------------------------------------------------------------------------
242
+
243
+
244
+ @pytest.mark.parametrize("pat", ["foo", ("foo", "baz")])
245
+ @pytest.mark.parametrize("dtype", ["object", "category"])
246
+ @pytest.mark.parametrize("null_value", [None, np.nan, pd.NA])
247
+ @pytest.mark.parametrize("na", [True, False])
248
+ def test_startswith(pat, dtype, null_value, na):
249
+ # add category dtype parametrizations for GH-36241
250
+ values = Series(
251
+ ["om", null_value, "foo_nom", "nom", "bar_foo", null_value, "foo"],
252
+ dtype=dtype,
253
+ )
254
+
255
+ result = values.str.startswith(pat)
256
+ exp = Series([False, np.nan, True, False, False, np.nan, True])
257
+ if dtype == "object" and null_value is pd.NA:
258
+ # GH#18463
259
+ exp = exp.fillna(null_value)
260
+ elif dtype == "object" and null_value is None:
261
+ exp[exp.isna()] = None
262
+ tm.assert_series_equal(result, exp)
263
+
264
+ result = values.str.startswith(pat, na=na)
265
+ exp = Series([False, na, True, False, False, na, True])
266
+ tm.assert_series_equal(result, exp)
267
+
268
+ # mixed
269
+ mixed = np.array(
270
+ ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
271
+ dtype=np.object_,
272
+ )
273
+ rs = Series(mixed).str.startswith("f")
274
+ xp = Series([False, np.nan, False, np.nan, np.nan, True, None, np.nan, np.nan])
275
+ tm.assert_series_equal(rs, xp)
276
+
277
+
278
+ @pytest.mark.parametrize("na", [None, True, False])
279
+ def test_startswith_nullable_string_dtype(nullable_string_dtype, na):
280
+ values = Series(
281
+ ["om", None, "foo_nom", "nom", "bar_foo", None, "foo", "regex", "rege."],
282
+ dtype=nullable_string_dtype,
283
+ )
284
+ result = values.str.startswith("foo", na=na)
285
+ exp = Series(
286
+ [False, na, True, False, False, na, True, False, False], dtype="boolean"
287
+ )
288
+ tm.assert_series_equal(result, exp)
289
+
290
+ result = values.str.startswith("rege.", na=na)
291
+ exp = Series(
292
+ [False, na, False, False, False, na, False, False, True], dtype="boolean"
293
+ )
294
+ tm.assert_series_equal(result, exp)
295
+
296
+
297
+ # --------------------------------------------------------------------------------------
298
+ # str.endswith
299
+ # --------------------------------------------------------------------------------------
300
+
301
+
302
+ @pytest.mark.parametrize("pat", ["foo", ("foo", "baz")])
303
+ @pytest.mark.parametrize("dtype", ["object", "category"])
304
+ @pytest.mark.parametrize("null_value", [None, np.nan, pd.NA])
305
+ @pytest.mark.parametrize("na", [True, False])
306
+ def test_endswith(pat, dtype, null_value, na):
307
+ # add category dtype parametrizations for GH-36241
308
+ values = Series(
309
+ ["om", null_value, "foo_nom", "nom", "bar_foo", null_value, "foo"],
310
+ dtype=dtype,
311
+ )
312
+
313
+ result = values.str.endswith(pat)
314
+ exp = Series([False, np.nan, False, False, True, np.nan, True])
315
+ if dtype == "object" and null_value is pd.NA:
316
+ # GH#18463
317
+ exp = exp.fillna(null_value)
318
+ elif dtype == "object" and null_value is None:
319
+ exp[exp.isna()] = None
320
+ tm.assert_series_equal(result, exp)
321
+
322
+ result = values.str.endswith(pat, na=na)
323
+ exp = Series([False, na, False, False, True, na, True])
324
+ tm.assert_series_equal(result, exp)
325
+
326
+ # mixed
327
+ mixed = np.array(
328
+ ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
329
+ dtype=object,
330
+ )
331
+ rs = Series(mixed).str.endswith("f")
332
+ xp = Series([False, np.nan, False, np.nan, np.nan, False, None, np.nan, np.nan])
333
+ tm.assert_series_equal(rs, xp)
334
+
335
+
336
+ @pytest.mark.parametrize("na", [None, True, False])
337
+ def test_endswith_nullable_string_dtype(nullable_string_dtype, na):
338
+ values = Series(
339
+ ["om", None, "foo_nom", "nom", "bar_foo", None, "foo", "regex", "rege."],
340
+ dtype=nullable_string_dtype,
341
+ )
342
+ result = values.str.endswith("foo", na=na)
343
+ exp = Series(
344
+ [False, na, False, False, True, na, True, False, False], dtype="boolean"
345
+ )
346
+ tm.assert_series_equal(result, exp)
347
+
348
+ result = values.str.endswith("rege.", na=na)
349
+ exp = Series(
350
+ [False, na, False, False, False, na, False, False, True], dtype="boolean"
351
+ )
352
+ tm.assert_series_equal(result, exp)
353
+
354
+
355
+ # --------------------------------------------------------------------------------------
356
+ # str.replace
357
+ # --------------------------------------------------------------------------------------
358
+
359
+
360
+ def test_replace(any_string_dtype):
361
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
362
+
363
+ result = ser.str.replace("BAD[_]*", "", regex=True)
364
+ expected = Series(["foobar", np.nan], dtype=any_string_dtype)
365
+ tm.assert_series_equal(result, expected)
366
+
367
+
368
+ def test_replace_max_replacements(any_string_dtype):
369
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
370
+
371
+ expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype)
372
+ result = ser.str.replace("BAD[_]*", "", n=1, regex=True)
373
+ tm.assert_series_equal(result, expected)
374
+
375
+ expected = Series(["foo__barBAD", np.nan], dtype=any_string_dtype)
376
+ result = ser.str.replace("BAD", "", n=1, regex=False)
377
+ tm.assert_series_equal(result, expected)
378
+
379
+
380
+ def test_replace_mixed_object():
381
+ ser = Series(
382
+ ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0]
383
+ )
384
+ result = Series(ser).str.replace("BAD[_]*", "", regex=True)
385
+ expected = Series(
386
+ ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object
387
+ )
388
+ tm.assert_series_equal(result, expected)
389
+
390
+
391
+ def test_replace_unicode(any_string_dtype):
392
+ ser = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
393
+ expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
394
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
395
+ result = ser.str.replace(r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE, regex=True)
396
+ tm.assert_series_equal(result, expected)
397
+
398
+
399
+ @pytest.mark.parametrize("repl", [None, 3, {"a": "b"}])
400
+ @pytest.mark.parametrize("data", [["a", "b", None], ["a", "b", "c", "ad"]])
401
+ def test_replace_wrong_repl_type_raises(any_string_dtype, index_or_series, repl, data):
402
+ # https://github.com/pandas-dev/pandas/issues/13438
403
+ msg = "repl must be a string or callable"
404
+ obj = index_or_series(data, dtype=any_string_dtype)
405
+ with pytest.raises(TypeError, match=msg):
406
+ obj.str.replace("a", repl)
407
+
408
+
409
+ def test_replace_callable(any_string_dtype):
410
+ # GH 15055
411
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
412
+
413
+ # test with callable
414
+ repl = lambda m: m.group(0).swapcase()
415
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
416
+ result = ser.str.replace("[a-z][A-Z]{2}", repl, n=2, regex=True)
417
+ expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype)
418
+ tm.assert_series_equal(result, expected)
419
+
420
+
421
+ @pytest.mark.parametrize(
422
+ "repl", [lambda: None, lambda m, x: None, lambda m, x, y=None: None]
423
+ )
424
+ def test_replace_callable_raises(any_string_dtype, repl):
425
+ # GH 15055
426
+ values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
427
+
428
+ # test with wrong number of arguments, raising an error
429
+ msg = (
430
+ r"((takes)|(missing)) (?(2)from \d+ to )?\d+ "
431
+ r"(?(3)required )positional arguments?"
432
+ )
433
+ with pytest.raises(TypeError, match=msg):
434
+ with tm.maybe_produces_warning(
435
+ PerformanceWarning, using_pyarrow(any_string_dtype)
436
+ ):
437
+ values.str.replace("a", repl, regex=True)
438
+
439
+
440
+ def test_replace_callable_named_groups(any_string_dtype):
441
+ # test regex named groups
442
+ ser = Series(["Foo Bar Baz", np.nan], dtype=any_string_dtype)
443
+ pat = r"(?P<first>\w+) (?P<middle>\w+) (?P<last>\w+)"
444
+ repl = lambda m: m.group("middle").swapcase()
445
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
446
+ result = ser.str.replace(pat, repl, regex=True)
447
+ expected = Series(["bAR", np.nan], dtype=any_string_dtype)
448
+ tm.assert_series_equal(result, expected)
449
+
450
+
451
+ def test_replace_compiled_regex(any_string_dtype):
452
+ # GH 15446
453
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
454
+
455
+ # test with compiled regex
456
+ pat = re.compile(r"BAD_*")
457
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
458
+ result = ser.str.replace(pat, "", regex=True)
459
+ expected = Series(["foobar", np.nan], dtype=any_string_dtype)
460
+ tm.assert_series_equal(result, expected)
461
+
462
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
463
+ result = ser.str.replace(pat, "", n=1, regex=True)
464
+ expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype)
465
+ tm.assert_series_equal(result, expected)
466
+
467
+
468
+ def test_replace_compiled_regex_mixed_object():
469
+ pat = re.compile(r"BAD_*")
470
+ ser = Series(
471
+ ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0]
472
+ )
473
+ result = Series(ser).str.replace(pat, "", regex=True)
474
+ expected = Series(
475
+ ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object
476
+ )
477
+ tm.assert_series_equal(result, expected)
478
+
479
+
480
+ def test_replace_compiled_regex_unicode(any_string_dtype):
481
+ ser = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
482
+ expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
483
+ pat = re.compile(r"(?<=\w),(?=\w)", flags=re.UNICODE)
484
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
485
+ result = ser.str.replace(pat, ", ", regex=True)
486
+ tm.assert_series_equal(result, expected)
487
+
488
+
489
+ def test_replace_compiled_regex_raises(any_string_dtype):
490
+ # case and flags provided to str.replace will have no effect
491
+ # and will produce warnings
492
+ ser = Series(["fooBAD__barBAD__bad", np.nan], dtype=any_string_dtype)
493
+ pat = re.compile(r"BAD_*")
494
+
495
+ msg = "case and flags cannot be set when pat is a compiled regex"
496
+
497
+ with pytest.raises(ValueError, match=msg):
498
+ ser.str.replace(pat, "", flags=re.IGNORECASE, regex=True)
499
+
500
+ with pytest.raises(ValueError, match=msg):
501
+ ser.str.replace(pat, "", case=False, regex=True)
502
+
503
+ with pytest.raises(ValueError, match=msg):
504
+ ser.str.replace(pat, "", case=True, regex=True)
505
+
506
+
507
+ def test_replace_compiled_regex_callable(any_string_dtype):
508
+ # test with callable
509
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
510
+ repl = lambda m: m.group(0).swapcase()
511
+ pat = re.compile("[a-z][A-Z]{2}")
512
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
513
+ result = ser.str.replace(pat, repl, n=2, regex=True)
514
+ expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype)
515
+ tm.assert_series_equal(result, expected)
516
+
517
+
518
+ @pytest.mark.parametrize(
519
+ "regex,expected", [(True, ["bao", "bao", np.nan]), (False, ["bao", "foo", np.nan])]
520
+ )
521
+ def test_replace_literal(regex, expected, any_string_dtype):
522
+ # GH16808 literal replace (regex=False vs regex=True)
523
+ ser = Series(["f.o", "foo", np.nan], dtype=any_string_dtype)
524
+ expected = Series(expected, dtype=any_string_dtype)
525
+ result = ser.str.replace("f.", "ba", regex=regex)
526
+ tm.assert_series_equal(result, expected)
527
+
528
+
529
+ def test_replace_literal_callable_raises(any_string_dtype):
530
+ ser = Series([], dtype=any_string_dtype)
531
+ repl = lambda m: m.group(0).swapcase()
532
+
533
+ msg = "Cannot use a callable replacement when regex=False"
534
+ with pytest.raises(ValueError, match=msg):
535
+ ser.str.replace("abc", repl, regex=False)
536
+
537
+
538
+ def test_replace_literal_compiled_raises(any_string_dtype):
539
+ ser = Series([], dtype=any_string_dtype)
540
+ pat = re.compile("[a-z][A-Z]{2}")
541
+
542
+ msg = "Cannot use a compiled regex as replacement pattern with regex=False"
543
+ with pytest.raises(ValueError, match=msg):
544
+ ser.str.replace(pat, "", regex=False)
545
+
546
+
547
+ def test_replace_moar(any_string_dtype):
548
+ # PR #1179
549
+ ser = Series(
550
+ ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"],
551
+ dtype=any_string_dtype,
552
+ )
553
+
554
+ result = ser.str.replace("A", "YYY")
555
+ expected = Series(
556
+ ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"],
557
+ dtype=any_string_dtype,
558
+ )
559
+ tm.assert_series_equal(result, expected)
560
+
561
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
562
+ result = ser.str.replace("A", "YYY", case=False)
563
+ expected = Series(
564
+ [
565
+ "YYY",
566
+ "B",
567
+ "C",
568
+ "YYYYYYbYYY",
569
+ "BYYYcYYY",
570
+ "",
571
+ np.nan,
572
+ "CYYYBYYY",
573
+ "dog",
574
+ "cYYYt",
575
+ ],
576
+ dtype=any_string_dtype,
577
+ )
578
+ tm.assert_series_equal(result, expected)
579
+
580
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
581
+ result = ser.str.replace("^.a|dog", "XX-XX ", case=False, regex=True)
582
+ expected = Series(
583
+ [
584
+ "A",
585
+ "B",
586
+ "C",
587
+ "XX-XX ba",
588
+ "XX-XX ca",
589
+ "",
590
+ np.nan,
591
+ "XX-XX BA",
592
+ "XX-XX ",
593
+ "XX-XX t",
594
+ ],
595
+ dtype=any_string_dtype,
596
+ )
597
+ tm.assert_series_equal(result, expected)
598
+
599
+
600
+ def test_replace_not_case_sensitive_not_regex(any_string_dtype):
601
+ # https://github.com/pandas-dev/pandas/issues/41602
602
+ ser = Series(["A.", "a.", "Ab", "ab", np.nan], dtype=any_string_dtype)
603
+
604
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
605
+ result = ser.str.replace("a", "c", case=False, regex=False)
606
+ expected = Series(["c.", "c.", "cb", "cb", np.nan], dtype=any_string_dtype)
607
+ tm.assert_series_equal(result, expected)
608
+
609
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
610
+ result = ser.str.replace("a.", "c.", case=False, regex=False)
611
+ expected = Series(["c.", "c.", "Ab", "ab", np.nan], dtype=any_string_dtype)
612
+ tm.assert_series_equal(result, expected)
613
+
614
+
615
+ def test_replace_regex(any_string_dtype):
616
+ # https://github.com/pandas-dev/pandas/pull/24809
617
+ s = Series(["a", "b", "ac", np.nan, ""], dtype=any_string_dtype)
618
+ result = s.str.replace("^.$", "a", regex=True)
619
+ expected = Series(["a", "a", "ac", np.nan, ""], dtype=any_string_dtype)
620
+ tm.assert_series_equal(result, expected)
621
+
622
+
623
+ @pytest.mark.parametrize("regex", [True, False])
624
+ def test_replace_regex_single_character(regex, any_string_dtype):
625
+ # https://github.com/pandas-dev/pandas/pull/24809, enforced in 2.0
626
+ # GH 24804
627
+ s = Series(["a.b", ".", "b", np.nan, ""], dtype=any_string_dtype)
628
+
629
+ result = s.str.replace(".", "a", regex=regex)
630
+ if regex:
631
+ expected = Series(["aaa", "a", "a", np.nan, ""], dtype=any_string_dtype)
632
+ else:
633
+ expected = Series(["aab", "a", "b", np.nan, ""], dtype=any_string_dtype)
634
+ tm.assert_series_equal(result, expected)
635
+
636
+
637
+ # --------------------------------------------------------------------------------------
638
+ # str.match
639
+ # --------------------------------------------------------------------------------------
640
+
641
+
642
+ def test_match(any_string_dtype):
643
+ # New match behavior introduced in 0.13
644
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
645
+
646
+ values = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
647
+ result = values.str.match(".*(BAD[_]+).*(BAD)")
648
+ expected = Series([True, np.nan, False], dtype=expected_dtype)
649
+ tm.assert_series_equal(result, expected)
650
+
651
+ values = Series(
652
+ ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
653
+ )
654
+ result = values.str.match(".*BAD[_]+.*BAD")
655
+ expected = Series([True, True, np.nan, False], dtype=expected_dtype)
656
+ tm.assert_series_equal(result, expected)
657
+
658
+ result = values.str.match("BAD[_]+.*BAD")
659
+ expected = Series([False, True, np.nan, False], dtype=expected_dtype)
660
+ tm.assert_series_equal(result, expected)
661
+
662
+ values = Series(
663
+ ["fooBAD__barBAD", "^BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
664
+ )
665
+ result = values.str.match("^BAD[_]+.*BAD")
666
+ expected = Series([False, False, np.nan, False], dtype=expected_dtype)
667
+ tm.assert_series_equal(result, expected)
668
+
669
+ result = values.str.match("\\^BAD[_]+.*BAD")
670
+ expected = Series([False, True, np.nan, False], dtype=expected_dtype)
671
+ tm.assert_series_equal(result, expected)
672
+
673
+
674
+ def test_match_mixed_object():
675
+ mixed = Series(
676
+ [
677
+ "aBAD_BAD",
678
+ np.nan,
679
+ "BAD_b_BAD",
680
+ True,
681
+ datetime.today(),
682
+ "foo",
683
+ None,
684
+ 1,
685
+ 2.0,
686
+ ]
687
+ )
688
+ result = Series(mixed).str.match(".*(BAD[_]+).*(BAD)")
689
+ expected = Series([True, np.nan, True, np.nan, np.nan, False, None, np.nan, np.nan])
690
+ assert isinstance(result, Series)
691
+ tm.assert_series_equal(result, expected)
692
+
693
+
694
+ def test_match_na_kwarg(any_string_dtype):
695
+ # GH #6609
696
+ s = Series(["a", "b", np.nan], dtype=any_string_dtype)
697
+
698
+ result = s.str.match("a", na=False)
699
+ expected_dtype = np.bool_ if any_string_dtype in object_pyarrow_numpy else "boolean"
700
+ expected = Series([True, False, False], dtype=expected_dtype)
701
+ tm.assert_series_equal(result, expected)
702
+
703
+ result = s.str.match("a")
704
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
705
+ expected = Series([True, False, np.nan], dtype=expected_dtype)
706
+ tm.assert_series_equal(result, expected)
707
+
708
+
709
+ def test_match_case_kwarg(any_string_dtype):
710
+ values = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
711
+ result = values.str.match("ab", case=False)
712
+ expected_dtype = np.bool_ if any_string_dtype in object_pyarrow_numpy else "boolean"
713
+ expected = Series([True, True, True, True], dtype=expected_dtype)
714
+ tm.assert_series_equal(result, expected)
715
+
716
+
717
+ # --------------------------------------------------------------------------------------
718
+ # str.fullmatch
719
+ # --------------------------------------------------------------------------------------
720
+
721
+
722
+ def test_fullmatch(any_string_dtype):
723
+ # GH 32806
724
+ ser = Series(
725
+ ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
726
+ )
727
+ result = ser.str.fullmatch(".*BAD[_]+.*BAD")
728
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
729
+ expected = Series([True, False, np.nan, False], dtype=expected_dtype)
730
+ tm.assert_series_equal(result, expected)
731
+
732
+
733
+ def test_fullmatch_dollar_literal(any_string_dtype):
734
+ # GH 56652
735
+ ser = Series(["foo", "foo$foo", np.nan, "foo$"], dtype=any_string_dtype)
736
+ result = ser.str.fullmatch("foo\\$")
737
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
738
+ expected = Series([False, False, np.nan, True], dtype=expected_dtype)
739
+ tm.assert_series_equal(result, expected)
740
+
741
+
742
+ def test_fullmatch_na_kwarg(any_string_dtype):
743
+ ser = Series(
744
+ ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
745
+ )
746
+ result = ser.str.fullmatch(".*BAD[_]+.*BAD", na=False)
747
+ expected_dtype = np.bool_ if any_string_dtype in object_pyarrow_numpy else "boolean"
748
+ expected = Series([True, False, False, False], dtype=expected_dtype)
749
+ tm.assert_series_equal(result, expected)
750
+
751
+
752
+ def test_fullmatch_case_kwarg(any_string_dtype):
753
+ ser = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
754
+ expected_dtype = np.bool_ if any_string_dtype in object_pyarrow_numpy else "boolean"
755
+
756
+ expected = Series([True, False, False, False], dtype=expected_dtype)
757
+
758
+ result = ser.str.fullmatch("ab", case=True)
759
+ tm.assert_series_equal(result, expected)
760
+
761
+ expected = Series([True, True, False, False], dtype=expected_dtype)
762
+
763
+ result = ser.str.fullmatch("ab", case=False)
764
+ tm.assert_series_equal(result, expected)
765
+
766
+ with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow(any_string_dtype)):
767
+ result = ser.str.fullmatch("ab", flags=re.IGNORECASE)
768
+ tm.assert_series_equal(result, expected)
769
+
770
+
771
+ # --------------------------------------------------------------------------------------
772
+ # str.findall
773
+ # --------------------------------------------------------------------------------------
774
+
775
+
776
+ def test_findall(any_string_dtype):
777
+ ser = Series(["fooBAD__barBAD", np.nan, "foo", "BAD"], dtype=any_string_dtype)
778
+ result = ser.str.findall("BAD[_]*")
779
+ expected = Series([["BAD__", "BAD"], np.nan, [], ["BAD"]])
780
+ expected = _convert_na_value(ser, expected)
781
+ tm.assert_series_equal(result, expected)
782
+
783
+
784
+ def test_findall_mixed_object():
785
+ ser = Series(
786
+ [
787
+ "fooBAD__barBAD",
788
+ np.nan,
789
+ "foo",
790
+ True,
791
+ datetime.today(),
792
+ "BAD",
793
+ None,
794
+ 1,
795
+ 2.0,
796
+ ]
797
+ )
798
+
799
+ result = ser.str.findall("BAD[_]*")
800
+ expected = Series(
801
+ [
802
+ ["BAD__", "BAD"],
803
+ np.nan,
804
+ [],
805
+ np.nan,
806
+ np.nan,
807
+ ["BAD"],
808
+ None,
809
+ np.nan,
810
+ np.nan,
811
+ ]
812
+ )
813
+
814
+ tm.assert_series_equal(result, expected)
815
+
816
+
817
+ # --------------------------------------------------------------------------------------
818
+ # str.find
819
+ # --------------------------------------------------------------------------------------
820
+
821
+
822
+ def test_find(any_string_dtype):
823
+ ser = Series(
824
+ ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF", "XXXX"], dtype=any_string_dtype
825
+ )
826
+ expected_dtype = np.int64 if any_string_dtype in object_pyarrow_numpy else "Int64"
827
+
828
+ result = ser.str.find("EF")
829
+ expected = Series([4, 3, 1, 0, -1], dtype=expected_dtype)
830
+ tm.assert_series_equal(result, expected)
831
+ expected = np.array([v.find("EF") for v in np.array(ser)], dtype=np.int64)
832
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
833
+
834
+ result = ser.str.rfind("EF")
835
+ expected = Series([4, 5, 7, 4, -1], dtype=expected_dtype)
836
+ tm.assert_series_equal(result, expected)
837
+ expected = np.array([v.rfind("EF") for v in np.array(ser)], dtype=np.int64)
838
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
839
+
840
+ result = ser.str.find("EF", 3)
841
+ expected = Series([4, 3, 7, 4, -1], dtype=expected_dtype)
842
+ tm.assert_series_equal(result, expected)
843
+ expected = np.array([v.find("EF", 3) for v in np.array(ser)], dtype=np.int64)
844
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
845
+
846
+ result = ser.str.rfind("EF", 3)
847
+ expected = Series([4, 5, 7, 4, -1], dtype=expected_dtype)
848
+ tm.assert_series_equal(result, expected)
849
+ expected = np.array([v.rfind("EF", 3) for v in np.array(ser)], dtype=np.int64)
850
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
851
+
852
+ result = ser.str.find("EF", 3, 6)
853
+ expected = Series([4, 3, -1, 4, -1], dtype=expected_dtype)
854
+ tm.assert_series_equal(result, expected)
855
+ expected = np.array([v.find("EF", 3, 6) for v in np.array(ser)], dtype=np.int64)
856
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
857
+
858
+ result = ser.str.rfind("EF", 3, 6)
859
+ expected = Series([4, 3, -1, 4, -1], dtype=expected_dtype)
860
+ tm.assert_series_equal(result, expected)
861
+ expected = np.array([v.rfind("EF", 3, 6) for v in np.array(ser)], dtype=np.int64)
862
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
863
+
864
+
865
+ def test_find_bad_arg_raises(any_string_dtype):
866
+ ser = Series([], dtype=any_string_dtype)
867
+ with pytest.raises(TypeError, match="expected a string object, not int"):
868
+ ser.str.find(0)
869
+
870
+ with pytest.raises(TypeError, match="expected a string object, not int"):
871
+ ser.str.rfind(0)
872
+
873
+
874
+ def test_find_nan(any_string_dtype):
875
+ ser = Series(
876
+ ["ABCDEFG", np.nan, "DEFGHIJEF", np.nan, "XXXX"], dtype=any_string_dtype
877
+ )
878
+ expected_dtype = np.float64 if any_string_dtype in object_pyarrow_numpy else "Int64"
879
+
880
+ result = ser.str.find("EF")
881
+ expected = Series([4, np.nan, 1, np.nan, -1], dtype=expected_dtype)
882
+ tm.assert_series_equal(result, expected)
883
+
884
+ result = ser.str.rfind("EF")
885
+ expected = Series([4, np.nan, 7, np.nan, -1], dtype=expected_dtype)
886
+ tm.assert_series_equal(result, expected)
887
+
888
+ result = ser.str.find("EF", 3)
889
+ expected = Series([4, np.nan, 7, np.nan, -1], dtype=expected_dtype)
890
+ tm.assert_series_equal(result, expected)
891
+
892
+ result = ser.str.rfind("EF", 3)
893
+ expected = Series([4, np.nan, 7, np.nan, -1], dtype=expected_dtype)
894
+ tm.assert_series_equal(result, expected)
895
+
896
+ result = ser.str.find("EF", 3, 6)
897
+ expected = Series([4, np.nan, -1, np.nan, -1], dtype=expected_dtype)
898
+ tm.assert_series_equal(result, expected)
899
+
900
+ result = ser.str.rfind("EF", 3, 6)
901
+ expected = Series([4, np.nan, -1, np.nan, -1], dtype=expected_dtype)
902
+ tm.assert_series_equal(result, expected)
903
+
904
+
905
+ # --------------------------------------------------------------------------------------
906
+ # str.translate
907
+ # --------------------------------------------------------------------------------------
908
+
909
+
910
+ @pytest.mark.parametrize(
911
+ "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
912
+ )
913
+ def test_translate(index_or_series, any_string_dtype, infer_string):
914
+ obj = index_or_series(
915
+ ["abcdefg", "abcc", "cdddfg", "cdefggg"], dtype=any_string_dtype
916
+ )
917
+ table = str.maketrans("abc", "cde")
918
+ result = obj.str.translate(table)
919
+ expected = index_or_series(
920
+ ["cdedefg", "cdee", "edddfg", "edefggg"], dtype=any_string_dtype
921
+ )
922
+ tm.assert_equal(result, expected)
923
+
924
+
925
+ def test_translate_mixed_object():
926
+ # Series with non-string values
927
+ s = Series(["a", "b", "c", 1.2])
928
+ table = str.maketrans("abc", "cde")
929
+ expected = Series(["c", "d", "e", np.nan], dtype=object)
930
+ result = s.str.translate(table)
931
+ tm.assert_series_equal(result, expected)
932
+
933
+
934
+ # --------------------------------------------------------------------------------------
935
+
936
+
937
+ def test_flags_kwarg(any_string_dtype):
938
+ data = {
939
+ "Dave": "[email protected]",
940
+ "Steve": "[email protected]",
941
+ "Rob": "[email protected]",
942
+ "Wes": np.nan,
943
+ }
944
+ data = Series(data, dtype=any_string_dtype)
945
+
946
+ pat = r"([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})"
947
+
948
+ use_pyarrow = using_pyarrow(any_string_dtype)
949
+
950
+ result = data.str.extract(pat, flags=re.IGNORECASE, expand=True)
951
+ assert result.iloc[0].tolist() == ["dave", "google", "com"]
952
+
953
+ with tm.maybe_produces_warning(PerformanceWarning, use_pyarrow):
954
+ result = data.str.match(pat, flags=re.IGNORECASE)
955
+ assert result.iloc[0]
956
+
957
+ with tm.maybe_produces_warning(PerformanceWarning, use_pyarrow):
958
+ result = data.str.fullmatch(pat, flags=re.IGNORECASE)
959
+ assert result.iloc[0]
960
+
961
+ result = data.str.findall(pat, flags=re.IGNORECASE)
962
+ assert result.iloc[0][0] == ("dave", "google", "com")
963
+
964
+ result = data.str.count(pat, flags=re.IGNORECASE)
965
+ assert result.iloc[0] == 1
966
+
967
+ msg = "has match groups"
968
+ with tm.assert_produces_warning(
969
+ UserWarning, match=msg, raise_on_extra_warnings=not use_pyarrow
970
+ ):
971
+ result = data.str.contains(pat, flags=re.IGNORECASE)
972
+ assert result.iloc[0]
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_get_dummies.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas import (
4
+ DataFrame,
5
+ Index,
6
+ MultiIndex,
7
+ Series,
8
+ _testing as tm,
9
+ )
10
+
11
+
12
+ def test_get_dummies(any_string_dtype):
13
+ s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype)
14
+ result = s.str.get_dummies("|")
15
+ expected = DataFrame([[1, 1, 0], [1, 0, 1], [0, 0, 0]], columns=list("abc"))
16
+ tm.assert_frame_equal(result, expected)
17
+
18
+ s = Series(["a;b", "a", 7], dtype=any_string_dtype)
19
+ result = s.str.get_dummies(";")
20
+ expected = DataFrame([[0, 1, 1], [0, 1, 0], [1, 0, 0]], columns=list("7ab"))
21
+ tm.assert_frame_equal(result, expected)
22
+
23
+
24
+ def test_get_dummies_index():
25
+ # GH9980, GH8028
26
+ idx = Index(["a|b", "a|c", "b|c"])
27
+ result = idx.str.get_dummies("|")
28
+
29
+ expected = MultiIndex.from_tuples(
30
+ [(1, 1, 0), (1, 0, 1), (0, 1, 1)], names=("a", "b", "c")
31
+ )
32
+ tm.assert_index_equal(result, expected)
33
+
34
+
35
+ def test_get_dummies_with_name_dummy(any_string_dtype):
36
+ # GH 12180
37
+ # Dummies named 'name' should work as expected
38
+ s = Series(["a", "b,name", "b"], dtype=any_string_dtype)
39
+ result = s.str.get_dummies(",")
40
+ expected = DataFrame([[1, 0, 0], [0, 1, 1], [0, 1, 0]], columns=["a", "b", "name"])
41
+ tm.assert_frame_equal(result, expected)
42
+
43
+
44
+ def test_get_dummies_with_name_dummy_index():
45
+ # GH 12180
46
+ # Dummies named 'name' should work as expected
47
+ idx = Index(["a|b", "name|c", "b|name"])
48
+ result = idx.str.get_dummies("|")
49
+
50
+ expected = MultiIndex.from_tuples(
51
+ [(1, 1, 0, 0), (0, 0, 1, 1), (0, 1, 0, 1)], names=("a", "b", "c", "name")
52
+ )
53
+ tm.assert_index_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_split_partition.py ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ import pandas as pd
8
+ from pandas import (
9
+ DataFrame,
10
+ Index,
11
+ MultiIndex,
12
+ Series,
13
+ _testing as tm,
14
+ )
15
+ from pandas.tests.strings import (
16
+ _convert_na_value,
17
+ object_pyarrow_numpy,
18
+ )
19
+
20
+
21
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
22
+ def test_split(any_string_dtype, method):
23
+ values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
24
+
25
+ result = getattr(values.str, method)("_")
26
+ exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]])
27
+ exp = _convert_na_value(values, exp)
28
+ tm.assert_series_equal(result, exp)
29
+
30
+
31
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
32
+ def test_split_more_than_one_char(any_string_dtype, method):
33
+ # more than one char
34
+ values = Series(["a__b__c", "c__d__e", np.nan, "f__g__h"], dtype=any_string_dtype)
35
+ result = getattr(values.str, method)("__")
36
+ exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]])
37
+ exp = _convert_na_value(values, exp)
38
+ tm.assert_series_equal(result, exp)
39
+
40
+ result = getattr(values.str, method)("__", expand=False)
41
+ tm.assert_series_equal(result, exp)
42
+
43
+
44
+ def test_split_more_regex_split(any_string_dtype):
45
+ # regex split
46
+ values = Series(["a,b_c", "c_d,e", np.nan, "f,g,h"], dtype=any_string_dtype)
47
+ result = values.str.split("[,_]")
48
+ exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]])
49
+ exp = _convert_na_value(values, exp)
50
+ tm.assert_series_equal(result, exp)
51
+
52
+
53
+ def test_split_regex(any_string_dtype):
54
+ # GH 43563
55
+ # explicit regex = True split
56
+ values = Series("xxxjpgzzz.jpg", dtype=any_string_dtype)
57
+ result = values.str.split(r"\.jpg", regex=True)
58
+ exp = Series([["xxxjpgzzz", ""]])
59
+ tm.assert_series_equal(result, exp)
60
+
61
+
62
+ def test_split_regex_explicit(any_string_dtype):
63
+ # explicit regex = True split with compiled regex
64
+ regex_pat = re.compile(r".jpg")
65
+ values = Series("xxxjpgzzz.jpg", dtype=any_string_dtype)
66
+ result = values.str.split(regex_pat)
67
+ exp = Series([["xx", "zzz", ""]])
68
+ tm.assert_series_equal(result, exp)
69
+
70
+ # explicit regex = False split
71
+ result = values.str.split(r"\.jpg", regex=False)
72
+ exp = Series([["xxxjpgzzz.jpg"]])
73
+ tm.assert_series_equal(result, exp)
74
+
75
+ # non explicit regex split, pattern length == 1
76
+ result = values.str.split(r".")
77
+ exp = Series([["xxxjpgzzz", "jpg"]])
78
+ tm.assert_series_equal(result, exp)
79
+
80
+ # non explicit regex split, pattern length != 1
81
+ result = values.str.split(r".jpg")
82
+ exp = Series([["xx", "zzz", ""]])
83
+ tm.assert_series_equal(result, exp)
84
+
85
+ # regex=False with pattern compiled regex raises error
86
+ with pytest.raises(
87
+ ValueError,
88
+ match="Cannot use a compiled regex as replacement pattern with regex=False",
89
+ ):
90
+ values.str.split(regex_pat, regex=False)
91
+
92
+
93
+ @pytest.mark.parametrize("expand", [None, False])
94
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
95
+ def test_split_object_mixed(expand, method):
96
+ mixed = Series(["a_b_c", np.nan, "d_e_f", True, datetime.today(), None, 1, 2.0])
97
+ result = getattr(mixed.str, method)("_", expand=expand)
98
+ exp = Series(
99
+ [
100
+ ["a", "b", "c"],
101
+ np.nan,
102
+ ["d", "e", "f"],
103
+ np.nan,
104
+ np.nan,
105
+ None,
106
+ np.nan,
107
+ np.nan,
108
+ ]
109
+ )
110
+ assert isinstance(result, Series)
111
+ tm.assert_almost_equal(result, exp)
112
+
113
+
114
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
115
+ @pytest.mark.parametrize("n", [None, 0])
116
+ def test_split_n(any_string_dtype, method, n):
117
+ s = Series(["a b", pd.NA, "b c"], dtype=any_string_dtype)
118
+ expected = Series([["a", "b"], pd.NA, ["b", "c"]])
119
+ result = getattr(s.str, method)(" ", n=n)
120
+ expected = _convert_na_value(s, expected)
121
+ tm.assert_series_equal(result, expected)
122
+
123
+
124
+ def test_rsplit(any_string_dtype):
125
+ # regex split is not supported by rsplit
126
+ values = Series(["a,b_c", "c_d,e", np.nan, "f,g,h"], dtype=any_string_dtype)
127
+ result = values.str.rsplit("[,_]")
128
+ exp = Series([["a,b_c"], ["c_d,e"], np.nan, ["f,g,h"]])
129
+ exp = _convert_na_value(values, exp)
130
+ tm.assert_series_equal(result, exp)
131
+
132
+
133
+ def test_rsplit_max_number(any_string_dtype):
134
+ # setting max number of splits, make sure it's from reverse
135
+ values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
136
+ result = values.str.rsplit("_", n=1)
137
+ exp = Series([["a_b", "c"], ["c_d", "e"], np.nan, ["f_g", "h"]])
138
+ exp = _convert_na_value(values, exp)
139
+ tm.assert_series_equal(result, exp)
140
+
141
+
142
+ def test_split_blank_string(any_string_dtype):
143
+ # expand blank split GH 20067
144
+ values = Series([""], name="test", dtype=any_string_dtype)
145
+ result = values.str.split(expand=True)
146
+ exp = DataFrame([[]], dtype=any_string_dtype) # NOTE: this is NOT an empty df
147
+ tm.assert_frame_equal(result, exp)
148
+
149
+
150
+ def test_split_blank_string_with_non_empty(any_string_dtype):
151
+ values = Series(["a b c", "a b", "", " "], name="test", dtype=any_string_dtype)
152
+ result = values.str.split(expand=True)
153
+ exp = DataFrame(
154
+ [
155
+ ["a", "b", "c"],
156
+ ["a", "b", None],
157
+ [None, None, None],
158
+ [None, None, None],
159
+ ],
160
+ dtype=any_string_dtype,
161
+ )
162
+ tm.assert_frame_equal(result, exp)
163
+
164
+
165
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
166
+ def test_split_noargs(any_string_dtype, method):
167
+ # #1859
168
+ s = Series(["Wes McKinney", "Travis Oliphant"], dtype=any_string_dtype)
169
+ result = getattr(s.str, method)()
170
+ expected = ["Travis", "Oliphant"]
171
+ assert result[1] == expected
172
+
173
+
174
+ @pytest.mark.parametrize(
175
+ "data, pat",
176
+ [
177
+ (["bd asdf jfg", "kjasdflqw asdfnfk"], None),
178
+ (["bd asdf jfg", "kjasdflqw asdfnfk"], "asdf"),
179
+ (["bd_asdf_jfg", "kjasdflqw_asdfnfk"], "_"),
180
+ ],
181
+ )
182
+ @pytest.mark.parametrize("n", [-1, 0])
183
+ def test_split_maxsplit(data, pat, any_string_dtype, n):
184
+ # re.split 0, str.split -1
185
+ s = Series(data, dtype=any_string_dtype)
186
+
187
+ result = s.str.split(pat=pat, n=n)
188
+ xp = s.str.split(pat=pat)
189
+ tm.assert_series_equal(result, xp)
190
+
191
+
192
+ @pytest.mark.parametrize(
193
+ "data, pat, expected",
194
+ [
195
+ (
196
+ ["split once", "split once too!"],
197
+ None,
198
+ Series({0: ["split", "once"], 1: ["split", "once too!"]}),
199
+ ),
200
+ (
201
+ ["split_once", "split_once_too!"],
202
+ "_",
203
+ Series({0: ["split", "once"], 1: ["split", "once_too!"]}),
204
+ ),
205
+ ],
206
+ )
207
+ def test_split_no_pat_with_nonzero_n(data, pat, expected, any_string_dtype):
208
+ s = Series(data, dtype=any_string_dtype)
209
+ result = s.str.split(pat=pat, n=1)
210
+ tm.assert_series_equal(expected, result, check_index_type=False)
211
+
212
+
213
+ def test_split_to_dataframe_no_splits(any_string_dtype):
214
+ s = Series(["nosplit", "alsonosplit"], dtype=any_string_dtype)
215
+ result = s.str.split("_", expand=True)
216
+ exp = DataFrame({0: Series(["nosplit", "alsonosplit"], dtype=any_string_dtype)})
217
+ tm.assert_frame_equal(result, exp)
218
+
219
+
220
+ def test_split_to_dataframe(any_string_dtype):
221
+ s = Series(["some_equal_splits", "with_no_nans"], dtype=any_string_dtype)
222
+ result = s.str.split("_", expand=True)
223
+ exp = DataFrame(
224
+ {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]},
225
+ dtype=any_string_dtype,
226
+ )
227
+ tm.assert_frame_equal(result, exp)
228
+
229
+
230
+ def test_split_to_dataframe_unequal_splits(any_string_dtype):
231
+ s = Series(
232
+ ["some_unequal_splits", "one_of_these_things_is_not"], dtype=any_string_dtype
233
+ )
234
+ result = s.str.split("_", expand=True)
235
+ exp = DataFrame(
236
+ {
237
+ 0: ["some", "one"],
238
+ 1: ["unequal", "of"],
239
+ 2: ["splits", "these"],
240
+ 3: [None, "things"],
241
+ 4: [None, "is"],
242
+ 5: [None, "not"],
243
+ },
244
+ dtype=any_string_dtype,
245
+ )
246
+ tm.assert_frame_equal(result, exp)
247
+
248
+
249
+ def test_split_to_dataframe_with_index(any_string_dtype):
250
+ s = Series(
251
+ ["some_splits", "with_index"], index=["preserve", "me"], dtype=any_string_dtype
252
+ )
253
+ result = s.str.split("_", expand=True)
254
+ exp = DataFrame(
255
+ {0: ["some", "with"], 1: ["splits", "index"]},
256
+ index=["preserve", "me"],
257
+ dtype=any_string_dtype,
258
+ )
259
+ tm.assert_frame_equal(result, exp)
260
+
261
+ with pytest.raises(ValueError, match="expand must be"):
262
+ s.str.split("_", expand="not_a_boolean")
263
+
264
+
265
+ def test_split_to_multiindex_expand_no_splits():
266
+ # https://github.com/pandas-dev/pandas/issues/23677
267
+
268
+ idx = Index(["nosplit", "alsonosplit", np.nan])
269
+ result = idx.str.split("_", expand=True)
270
+ exp = idx
271
+ tm.assert_index_equal(result, exp)
272
+ assert result.nlevels == 1
273
+
274
+
275
+ def test_split_to_multiindex_expand():
276
+ idx = Index(["some_equal_splits", "with_no_nans", np.nan, None])
277
+ result = idx.str.split("_", expand=True)
278
+ exp = MultiIndex.from_tuples(
279
+ [
280
+ ("some", "equal", "splits"),
281
+ ("with", "no", "nans"),
282
+ [np.nan, np.nan, np.nan],
283
+ [None, None, None],
284
+ ]
285
+ )
286
+ tm.assert_index_equal(result, exp)
287
+ assert result.nlevels == 3
288
+
289
+
290
+ def test_split_to_multiindex_expand_unequal_splits():
291
+ idx = Index(["some_unequal_splits", "one_of_these_things_is_not", np.nan, None])
292
+ result = idx.str.split("_", expand=True)
293
+ exp = MultiIndex.from_tuples(
294
+ [
295
+ ("some", "unequal", "splits", np.nan, np.nan, np.nan),
296
+ ("one", "of", "these", "things", "is", "not"),
297
+ (np.nan, np.nan, np.nan, np.nan, np.nan, np.nan),
298
+ (None, None, None, None, None, None),
299
+ ]
300
+ )
301
+ tm.assert_index_equal(result, exp)
302
+ assert result.nlevels == 6
303
+
304
+ with pytest.raises(ValueError, match="expand must be"):
305
+ idx.str.split("_", expand="not_a_boolean")
306
+
307
+
308
+ def test_rsplit_to_dataframe_expand_no_splits(any_string_dtype):
309
+ s = Series(["nosplit", "alsonosplit"], dtype=any_string_dtype)
310
+ result = s.str.rsplit("_", expand=True)
311
+ exp = DataFrame({0: Series(["nosplit", "alsonosplit"])}, dtype=any_string_dtype)
312
+ tm.assert_frame_equal(result, exp)
313
+
314
+
315
+ def test_rsplit_to_dataframe_expand(any_string_dtype):
316
+ s = Series(["some_equal_splits", "with_no_nans"], dtype=any_string_dtype)
317
+ result = s.str.rsplit("_", expand=True)
318
+ exp = DataFrame(
319
+ {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]},
320
+ dtype=any_string_dtype,
321
+ )
322
+ tm.assert_frame_equal(result, exp)
323
+
324
+ result = s.str.rsplit("_", expand=True, n=2)
325
+ exp = DataFrame(
326
+ {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]},
327
+ dtype=any_string_dtype,
328
+ )
329
+ tm.assert_frame_equal(result, exp)
330
+
331
+ result = s.str.rsplit("_", expand=True, n=1)
332
+ exp = DataFrame(
333
+ {0: ["some_equal", "with_no"], 1: ["splits", "nans"]}, dtype=any_string_dtype
334
+ )
335
+ tm.assert_frame_equal(result, exp)
336
+
337
+
338
+ def test_rsplit_to_dataframe_expand_with_index(any_string_dtype):
339
+ s = Series(
340
+ ["some_splits", "with_index"], index=["preserve", "me"], dtype=any_string_dtype
341
+ )
342
+ result = s.str.rsplit("_", expand=True)
343
+ exp = DataFrame(
344
+ {0: ["some", "with"], 1: ["splits", "index"]},
345
+ index=["preserve", "me"],
346
+ dtype=any_string_dtype,
347
+ )
348
+ tm.assert_frame_equal(result, exp)
349
+
350
+
351
+ def test_rsplit_to_multiindex_expand_no_split():
352
+ idx = Index(["nosplit", "alsonosplit"])
353
+ result = idx.str.rsplit("_", expand=True)
354
+ exp = idx
355
+ tm.assert_index_equal(result, exp)
356
+ assert result.nlevels == 1
357
+
358
+
359
+ def test_rsplit_to_multiindex_expand():
360
+ idx = Index(["some_equal_splits", "with_no_nans"])
361
+ result = idx.str.rsplit("_", expand=True)
362
+ exp = MultiIndex.from_tuples([("some", "equal", "splits"), ("with", "no", "nans")])
363
+ tm.assert_index_equal(result, exp)
364
+ assert result.nlevels == 3
365
+
366
+
367
+ def test_rsplit_to_multiindex_expand_n():
368
+ idx = Index(["some_equal_splits", "with_no_nans"])
369
+ result = idx.str.rsplit("_", expand=True, n=1)
370
+ exp = MultiIndex.from_tuples([("some_equal", "splits"), ("with_no", "nans")])
371
+ tm.assert_index_equal(result, exp)
372
+ assert result.nlevels == 2
373
+
374
+
375
+ def test_split_nan_expand(any_string_dtype):
376
+ # gh-18450
377
+ s = Series(["foo,bar,baz", np.nan], dtype=any_string_dtype)
378
+ result = s.str.split(",", expand=True)
379
+ exp = DataFrame(
380
+ [["foo", "bar", "baz"], [np.nan, np.nan, np.nan]], dtype=any_string_dtype
381
+ )
382
+ tm.assert_frame_equal(result, exp)
383
+
384
+ # check that these are actually np.nan/pd.NA and not None
385
+ # TODO see GH 18463
386
+ # tm.assert_frame_equal does not differentiate
387
+ if any_string_dtype in object_pyarrow_numpy:
388
+ assert all(np.isnan(x) for x in result.iloc[1])
389
+ else:
390
+ assert all(x is pd.NA for x in result.iloc[1])
391
+
392
+
393
+ def test_split_with_name_series(any_string_dtype):
394
+ # GH 12617
395
+
396
+ # should preserve name
397
+ s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype)
398
+ res = s.str.split(",")
399
+ exp = Series([["a", "b"], ["c", "d"]], name="xxx")
400
+ tm.assert_series_equal(res, exp)
401
+
402
+ res = s.str.split(",", expand=True)
403
+ exp = DataFrame([["a", "b"], ["c", "d"]], dtype=any_string_dtype)
404
+ tm.assert_frame_equal(res, exp)
405
+
406
+
407
+ def test_split_with_name_index():
408
+ # GH 12617
409
+ idx = Index(["a,b", "c,d"], name="xxx")
410
+ res = idx.str.split(",")
411
+ exp = Index([["a", "b"], ["c", "d"]], name="xxx")
412
+ assert res.nlevels == 1
413
+ tm.assert_index_equal(res, exp)
414
+
415
+ res = idx.str.split(",", expand=True)
416
+ exp = MultiIndex.from_tuples([("a", "b"), ("c", "d")])
417
+ assert res.nlevels == 2
418
+ tm.assert_index_equal(res, exp)
419
+
420
+
421
+ @pytest.mark.parametrize(
422
+ "method, exp",
423
+ [
424
+ [
425
+ "partition",
426
+ [
427
+ ("a", "__", "b__c"),
428
+ ("c", "__", "d__e"),
429
+ np.nan,
430
+ ("f", "__", "g__h"),
431
+ None,
432
+ ],
433
+ ],
434
+ [
435
+ "rpartition",
436
+ [
437
+ ("a__b", "__", "c"),
438
+ ("c__d", "__", "e"),
439
+ np.nan,
440
+ ("f__g", "__", "h"),
441
+ None,
442
+ ],
443
+ ],
444
+ ],
445
+ )
446
+ def test_partition_series_more_than_one_char(method, exp, any_string_dtype):
447
+ # https://github.com/pandas-dev/pandas/issues/23558
448
+ # more than one char
449
+ s = Series(["a__b__c", "c__d__e", np.nan, "f__g__h", None], dtype=any_string_dtype)
450
+ result = getattr(s.str, method)("__", expand=False)
451
+ expected = Series(exp)
452
+ expected = _convert_na_value(s, expected)
453
+ tm.assert_series_equal(result, expected)
454
+
455
+
456
+ @pytest.mark.parametrize(
457
+ "method, exp",
458
+ [
459
+ [
460
+ "partition",
461
+ [("a", " ", "b c"), ("c", " ", "d e"), np.nan, ("f", " ", "g h"), None],
462
+ ],
463
+ [
464
+ "rpartition",
465
+ [("a b", " ", "c"), ("c d", " ", "e"), np.nan, ("f g", " ", "h"), None],
466
+ ],
467
+ ],
468
+ )
469
+ def test_partition_series_none(any_string_dtype, method, exp):
470
+ # https://github.com/pandas-dev/pandas/issues/23558
471
+ # None
472
+ s = Series(["a b c", "c d e", np.nan, "f g h", None], dtype=any_string_dtype)
473
+ result = getattr(s.str, method)(expand=False)
474
+ expected = Series(exp)
475
+ expected = _convert_na_value(s, expected)
476
+ tm.assert_series_equal(result, expected)
477
+
478
+
479
+ @pytest.mark.parametrize(
480
+ "method, exp",
481
+ [
482
+ [
483
+ "partition",
484
+ [("abc", "", ""), ("cde", "", ""), np.nan, ("fgh", "", ""), None],
485
+ ],
486
+ [
487
+ "rpartition",
488
+ [("", "", "abc"), ("", "", "cde"), np.nan, ("", "", "fgh"), None],
489
+ ],
490
+ ],
491
+ )
492
+ def test_partition_series_not_split(any_string_dtype, method, exp):
493
+ # https://github.com/pandas-dev/pandas/issues/23558
494
+ # Not split
495
+ s = Series(["abc", "cde", np.nan, "fgh", None], dtype=any_string_dtype)
496
+ result = getattr(s.str, method)("_", expand=False)
497
+ expected = Series(exp)
498
+ expected = _convert_na_value(s, expected)
499
+ tm.assert_series_equal(result, expected)
500
+
501
+
502
+ @pytest.mark.parametrize(
503
+ "method, exp",
504
+ [
505
+ [
506
+ "partition",
507
+ [("a", "_", "b_c"), ("c", "_", "d_e"), np.nan, ("f", "_", "g_h")],
508
+ ],
509
+ [
510
+ "rpartition",
511
+ [("a_b", "_", "c"), ("c_d", "_", "e"), np.nan, ("f_g", "_", "h")],
512
+ ],
513
+ ],
514
+ )
515
+ def test_partition_series_unicode(any_string_dtype, method, exp):
516
+ # https://github.com/pandas-dev/pandas/issues/23558
517
+ # unicode
518
+ s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
519
+
520
+ result = getattr(s.str, method)("_", expand=False)
521
+ expected = Series(exp)
522
+ expected = _convert_na_value(s, expected)
523
+ tm.assert_series_equal(result, expected)
524
+
525
+
526
+ @pytest.mark.parametrize("method", ["partition", "rpartition"])
527
+ def test_partition_series_stdlib(any_string_dtype, method):
528
+ # https://github.com/pandas-dev/pandas/issues/23558
529
+ # compare to standard lib
530
+ s = Series(["A_B_C", "B_C_D", "E_F_G", "EFGHEF"], dtype=any_string_dtype)
531
+ result = getattr(s.str, method)("_", expand=False).tolist()
532
+ assert result == [getattr(v, method)("_") for v in s]
533
+
534
+
535
+ @pytest.mark.parametrize(
536
+ "method, expand, exp, exp_levels",
537
+ [
538
+ [
539
+ "partition",
540
+ False,
541
+ np.array(
542
+ [("a", "_", "b_c"), ("c", "_", "d_e"), ("f", "_", "g_h"), np.nan, None],
543
+ dtype=object,
544
+ ),
545
+ 1,
546
+ ],
547
+ [
548
+ "rpartition",
549
+ False,
550
+ np.array(
551
+ [("a_b", "_", "c"), ("c_d", "_", "e"), ("f_g", "_", "h"), np.nan, None],
552
+ dtype=object,
553
+ ),
554
+ 1,
555
+ ],
556
+ ],
557
+ )
558
+ def test_partition_index(method, expand, exp, exp_levels):
559
+ # https://github.com/pandas-dev/pandas/issues/23558
560
+
561
+ values = Index(["a_b_c", "c_d_e", "f_g_h", np.nan, None])
562
+
563
+ result = getattr(values.str, method)("_", expand=expand)
564
+ exp = Index(exp)
565
+ tm.assert_index_equal(result, exp)
566
+ assert result.nlevels == exp_levels
567
+
568
+
569
+ @pytest.mark.parametrize(
570
+ "method, exp",
571
+ [
572
+ [
573
+ "partition",
574
+ {
575
+ 0: ["a", "c", np.nan, "f", None],
576
+ 1: ["_", "_", np.nan, "_", None],
577
+ 2: ["b_c", "d_e", np.nan, "g_h", None],
578
+ },
579
+ ],
580
+ [
581
+ "rpartition",
582
+ {
583
+ 0: ["a_b", "c_d", np.nan, "f_g", None],
584
+ 1: ["_", "_", np.nan, "_", None],
585
+ 2: ["c", "e", np.nan, "h", None],
586
+ },
587
+ ],
588
+ ],
589
+ )
590
+ def test_partition_to_dataframe(any_string_dtype, method, exp):
591
+ # https://github.com/pandas-dev/pandas/issues/23558
592
+
593
+ s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h", None], dtype=any_string_dtype)
594
+ result = getattr(s.str, method)("_")
595
+ expected = DataFrame(
596
+ exp,
597
+ dtype=any_string_dtype,
598
+ )
599
+ tm.assert_frame_equal(result, expected)
600
+
601
+
602
+ @pytest.mark.parametrize(
603
+ "method, exp",
604
+ [
605
+ [
606
+ "partition",
607
+ {
608
+ 0: ["a", "c", np.nan, "f", None],
609
+ 1: ["_", "_", np.nan, "_", None],
610
+ 2: ["b_c", "d_e", np.nan, "g_h", None],
611
+ },
612
+ ],
613
+ [
614
+ "rpartition",
615
+ {
616
+ 0: ["a_b", "c_d", np.nan, "f_g", None],
617
+ 1: ["_", "_", np.nan, "_", None],
618
+ 2: ["c", "e", np.nan, "h", None],
619
+ },
620
+ ],
621
+ ],
622
+ )
623
+ def test_partition_to_dataframe_from_series(any_string_dtype, method, exp):
624
+ # https://github.com/pandas-dev/pandas/issues/23558
625
+ s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h", None], dtype=any_string_dtype)
626
+ result = getattr(s.str, method)("_", expand=True)
627
+ expected = DataFrame(
628
+ exp,
629
+ dtype=any_string_dtype,
630
+ )
631
+ tm.assert_frame_equal(result, expected)
632
+
633
+
634
+ def test_partition_with_name(any_string_dtype):
635
+ # GH 12617
636
+
637
+ s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype)
638
+ result = s.str.partition(",")
639
+ expected = DataFrame(
640
+ {0: ["a", "c"], 1: [",", ","], 2: ["b", "d"]}, dtype=any_string_dtype
641
+ )
642
+ tm.assert_frame_equal(result, expected)
643
+
644
+
645
+ def test_partition_with_name_expand(any_string_dtype):
646
+ # GH 12617
647
+ # should preserve name
648
+ s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype)
649
+ result = s.str.partition(",", expand=False)
650
+ expected = Series([("a", ",", "b"), ("c", ",", "d")], name="xxx")
651
+ tm.assert_series_equal(result, expected)
652
+
653
+
654
+ def test_partition_index_with_name():
655
+ idx = Index(["a,b", "c,d"], name="xxx")
656
+ result = idx.str.partition(",")
657
+ expected = MultiIndex.from_tuples([("a", ",", "b"), ("c", ",", "d")])
658
+ assert result.nlevels == 3
659
+ tm.assert_index_equal(result, expected)
660
+
661
+
662
+ def test_partition_index_with_name_expand_false():
663
+ idx = Index(["a,b", "c,d"], name="xxx")
664
+ # should preserve name
665
+ result = idx.str.partition(",", expand=False)
666
+ expected = Index(np.array([("a", ",", "b"), ("c", ",", "d")]), name="xxx")
667
+ assert result.nlevels == 1
668
+ tm.assert_index_equal(result, expected)
669
+
670
+
671
+ @pytest.mark.parametrize("method", ["partition", "rpartition"])
672
+ def test_partition_sep_kwarg(any_string_dtype, method):
673
+ # GH 22676; depr kwarg "pat" in favor of "sep"
674
+ s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
675
+
676
+ expected = getattr(s.str, method)(sep="_")
677
+ result = getattr(s.str, method)("_")
678
+ tm.assert_frame_equal(result, expected)
679
+
680
+
681
+ def test_get():
682
+ ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"])
683
+ result = ser.str.split("_").str.get(1)
684
+ expected = Series(["b", "d", np.nan, "g"], dtype=object)
685
+ tm.assert_series_equal(result, expected)
686
+
687
+
688
+ def test_get_mixed_object():
689
+ ser = Series(["a_b_c", np.nan, "c_d_e", True, datetime.today(), None, 1, 2.0])
690
+ result = ser.str.split("_").str.get(1)
691
+ expected = Series(
692
+ ["b", np.nan, "d", np.nan, np.nan, None, np.nan, np.nan], dtype=object
693
+ )
694
+ tm.assert_series_equal(result, expected)
695
+
696
+
697
+ @pytest.mark.parametrize("idx", [2, -3])
698
+ def test_get_bounds(idx):
699
+ ser = Series(["1_2_3_4_5", "6_7_8_9_10", "11_12"])
700
+ result = ser.str.split("_").str.get(idx)
701
+ expected = Series(["3", "8", np.nan], dtype=object)
702
+ tm.assert_series_equal(result, expected)
703
+
704
+
705
+ @pytest.mark.parametrize(
706
+ "idx, exp", [[2, [3, 3, np.nan, "b"]], [-1, [3, 3, np.nan, np.nan]]]
707
+ )
708
+ def test_get_complex(idx, exp):
709
+ # GH 20671, getting value not in dict raising `KeyError`
710
+ ser = Series([(1, 2, 3), [1, 2, 3], {1, 2, 3}, {1: "a", 2: "b", 3: "c"}])
711
+
712
+ result = ser.str.get(idx)
713
+ expected = Series(exp)
714
+ tm.assert_series_equal(result, expected)
715
+
716
+
717
+ @pytest.mark.parametrize("to_type", [tuple, list, np.array])
718
+ def test_get_complex_nested(to_type):
719
+ ser = Series([to_type([to_type([1, 2])])])
720
+
721
+ result = ser.str.get(0)
722
+ expected = Series([to_type([1, 2])])
723
+ tm.assert_series_equal(result, expected)
724
+
725
+ result = ser.str.get(1)
726
+ expected = Series([np.nan])
727
+ tm.assert_series_equal(result, expected)
728
+
729
+
730
+ def test_get_strings(any_string_dtype):
731
+ ser = Series(["a", "ab", np.nan, "abc"], dtype=any_string_dtype)
732
+ result = ser.str.get(2)
733
+ expected = Series([np.nan, np.nan, np.nan, "c"], dtype=any_string_dtype)
734
+ tm.assert_series_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_string_array.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._libs import lib
5
+
6
+ from pandas import (
7
+ NA,
8
+ DataFrame,
9
+ Series,
10
+ _testing as tm,
11
+ option_context,
12
+ )
13
+
14
+
15
+ @pytest.mark.filterwarnings("ignore:Falling back")
16
+ def test_string_array(nullable_string_dtype, any_string_method):
17
+ method_name, args, kwargs = any_string_method
18
+
19
+ data = ["a", "bb", np.nan, "ccc"]
20
+ a = Series(data, dtype=object)
21
+ b = Series(data, dtype=nullable_string_dtype)
22
+
23
+ if method_name == "decode":
24
+ with pytest.raises(TypeError, match="a bytes-like object is required"):
25
+ getattr(b.str, method_name)(*args, **kwargs)
26
+ return
27
+
28
+ expected = getattr(a.str, method_name)(*args, **kwargs)
29
+ result = getattr(b.str, method_name)(*args, **kwargs)
30
+
31
+ if isinstance(expected, Series):
32
+ if expected.dtype == "object" and lib.is_string_array(
33
+ expected.dropna().values,
34
+ ):
35
+ assert result.dtype == nullable_string_dtype
36
+ result = result.astype(object)
37
+
38
+ elif expected.dtype == "object" and lib.is_bool_array(
39
+ expected.values, skipna=True
40
+ ):
41
+ assert result.dtype == "boolean"
42
+ result = result.astype(object)
43
+
44
+ elif expected.dtype == "bool":
45
+ assert result.dtype == "boolean"
46
+ result = result.astype("bool")
47
+
48
+ elif expected.dtype == "float" and expected.isna().any():
49
+ assert result.dtype == "Int64"
50
+ result = result.astype("float")
51
+
52
+ if expected.dtype == object:
53
+ # GH#18463
54
+ expected[expected.isna()] = NA
55
+
56
+ elif isinstance(expected, DataFrame):
57
+ columns = expected.select_dtypes(include="object").columns
58
+ assert all(result[columns].dtypes == nullable_string_dtype)
59
+ result[columns] = result[columns].astype(object)
60
+ with option_context("future.no_silent_downcasting", True):
61
+ expected[columns] = expected[columns].fillna(NA) # GH#18463
62
+
63
+ tm.assert_equal(result, expected)
64
+
65
+
66
+ @pytest.mark.parametrize(
67
+ "method,expected",
68
+ [
69
+ ("count", [2, None]),
70
+ ("find", [0, None]),
71
+ ("index", [0, None]),
72
+ ("rindex", [2, None]),
73
+ ],
74
+ )
75
+ def test_string_array_numeric_integer_array(nullable_string_dtype, method, expected):
76
+ s = Series(["aba", None], dtype=nullable_string_dtype)
77
+ result = getattr(s.str, method)("a")
78
+ expected = Series(expected, dtype="Int64")
79
+ tm.assert_series_equal(result, expected)
80
+
81
+
82
+ @pytest.mark.parametrize(
83
+ "method,expected",
84
+ [
85
+ ("isdigit", [False, None, True]),
86
+ ("isalpha", [True, None, False]),
87
+ ("isalnum", [True, None, True]),
88
+ ("isnumeric", [False, None, True]),
89
+ ],
90
+ )
91
+ def test_string_array_boolean_array(nullable_string_dtype, method, expected):
92
+ s = Series(["a", None, "1"], dtype=nullable_string_dtype)
93
+ result = getattr(s.str, method)()
94
+ expected = Series(expected, dtype="boolean")
95
+ tm.assert_series_equal(result, expected)
96
+
97
+
98
+ def test_string_array_extract(nullable_string_dtype):
99
+ # https://github.com/pandas-dev/pandas/issues/30969
100
+ # Only expand=False & multiple groups was failing
101
+
102
+ a = Series(["a1", "b2", "cc"], dtype=nullable_string_dtype)
103
+ b = Series(["a1", "b2", "cc"], dtype="object")
104
+ pat = r"(\w)(\d)"
105
+
106
+ result = a.str.extract(pat, expand=False)
107
+ expected = b.str.extract(pat, expand=False)
108
+ expected = expected.fillna(NA) # GH#18463
109
+ assert all(result.dtypes == nullable_string_dtype)
110
+
111
+ result = result.astype(object)
112
+ tm.assert_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/strings/test_strings.py ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ datetime,
3
+ timedelta,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas import (
10
+ DataFrame,
11
+ Index,
12
+ MultiIndex,
13
+ Series,
14
+ )
15
+ import pandas._testing as tm
16
+ from pandas.core.strings.accessor import StringMethods
17
+ from pandas.tests.strings import object_pyarrow_numpy
18
+
19
+
20
+ @pytest.mark.parametrize("pattern", [0, True, Series(["foo", "bar"])])
21
+ def test_startswith_endswith_non_str_patterns(pattern):
22
+ # GH3485
23
+ ser = Series(["foo", "bar"])
24
+ msg = f"expected a string or tuple, not {type(pattern).__name__}"
25
+ with pytest.raises(TypeError, match=msg):
26
+ ser.str.startswith(pattern)
27
+ with pytest.raises(TypeError, match=msg):
28
+ ser.str.endswith(pattern)
29
+
30
+
31
+ def test_iter_raises():
32
+ # GH 54173
33
+ ser = Series(["foo", "bar"])
34
+ with pytest.raises(TypeError, match="'StringMethods' object is not iterable"):
35
+ iter(ser.str)
36
+
37
+
38
+ # test integer/float dtypes (inferred by constructor) and mixed
39
+
40
+
41
+ def test_count(any_string_dtype):
42
+ ser = Series(["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=any_string_dtype)
43
+ result = ser.str.count("f[o]+")
44
+ expected_dtype = np.float64 if any_string_dtype in object_pyarrow_numpy else "Int64"
45
+ expected = Series([1, 2, np.nan, 4], dtype=expected_dtype)
46
+ tm.assert_series_equal(result, expected)
47
+
48
+
49
+ def test_count_mixed_object():
50
+ ser = Series(
51
+ ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
52
+ dtype=object,
53
+ )
54
+ result = ser.str.count("a")
55
+ expected = Series([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan])
56
+ tm.assert_series_equal(result, expected)
57
+
58
+
59
+ def test_repeat(any_string_dtype):
60
+ ser = Series(["a", "b", np.nan, "c", np.nan, "d"], dtype=any_string_dtype)
61
+
62
+ result = ser.str.repeat(3)
63
+ expected = Series(
64
+ ["aaa", "bbb", np.nan, "ccc", np.nan, "ddd"], dtype=any_string_dtype
65
+ )
66
+ tm.assert_series_equal(result, expected)
67
+
68
+ result = ser.str.repeat([1, 2, 3, 4, 5, 6])
69
+ expected = Series(
70
+ ["a", "bb", np.nan, "cccc", np.nan, "dddddd"], dtype=any_string_dtype
71
+ )
72
+ tm.assert_series_equal(result, expected)
73
+
74
+
75
+ def test_repeat_mixed_object():
76
+ ser = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0])
77
+ result = ser.str.repeat(3)
78
+ expected = Series(
79
+ ["aaa", np.nan, "bbb", np.nan, np.nan, "foofoofoo", None, np.nan, np.nan],
80
+ dtype=object,
81
+ )
82
+ tm.assert_series_equal(result, expected)
83
+
84
+
85
+ @pytest.mark.parametrize("arg, repeat", [[None, 4], ["b", None]])
86
+ def test_repeat_with_null(any_string_dtype, arg, repeat):
87
+ # GH: 31632
88
+ ser = Series(["a", arg], dtype=any_string_dtype)
89
+ result = ser.str.repeat([3, repeat])
90
+ expected = Series(["aaa", None], dtype=any_string_dtype)
91
+ tm.assert_series_equal(result, expected)
92
+
93
+
94
+ def test_empty_str_methods(any_string_dtype):
95
+ empty_str = empty = Series(dtype=any_string_dtype)
96
+ if any_string_dtype in object_pyarrow_numpy:
97
+ empty_int = Series(dtype="int64")
98
+ empty_bool = Series(dtype=bool)
99
+ else:
100
+ empty_int = Series(dtype="Int64")
101
+ empty_bool = Series(dtype="boolean")
102
+ empty_object = Series(dtype=object)
103
+ empty_bytes = Series(dtype=object)
104
+ empty_df = DataFrame()
105
+
106
+ # GH7241
107
+ # (extract) on empty series
108
+
109
+ tm.assert_series_equal(empty_str, empty.str.cat(empty))
110
+ assert "" == empty.str.cat()
111
+ tm.assert_series_equal(empty_str, empty.str.title())
112
+ tm.assert_series_equal(empty_int, empty.str.count("a"))
113
+ tm.assert_series_equal(empty_bool, empty.str.contains("a"))
114
+ tm.assert_series_equal(empty_bool, empty.str.startswith("a"))
115
+ tm.assert_series_equal(empty_bool, empty.str.endswith("a"))
116
+ tm.assert_series_equal(empty_str, empty.str.lower())
117
+ tm.assert_series_equal(empty_str, empty.str.upper())
118
+ tm.assert_series_equal(empty_str, empty.str.replace("a", "b"))
119
+ tm.assert_series_equal(empty_str, empty.str.repeat(3))
120
+ tm.assert_series_equal(empty_bool, empty.str.match("^a"))
121
+ tm.assert_frame_equal(
122
+ DataFrame(columns=[0], dtype=any_string_dtype),
123
+ empty.str.extract("()", expand=True),
124
+ )
125
+ tm.assert_frame_equal(
126
+ DataFrame(columns=[0, 1], dtype=any_string_dtype),
127
+ empty.str.extract("()()", expand=True),
128
+ )
129
+ tm.assert_series_equal(empty_str, empty.str.extract("()", expand=False))
130
+ tm.assert_frame_equal(
131
+ DataFrame(columns=[0, 1], dtype=any_string_dtype),
132
+ empty.str.extract("()()", expand=False),
133
+ )
134
+ tm.assert_frame_equal(empty_df.set_axis([], axis=1), empty.str.get_dummies())
135
+ tm.assert_series_equal(empty_str, empty_str.str.join(""))
136
+ tm.assert_series_equal(empty_int, empty.str.len())
137
+ tm.assert_series_equal(empty_object, empty_str.str.findall("a"))
138
+ tm.assert_series_equal(empty_int, empty.str.find("a"))
139
+ tm.assert_series_equal(empty_int, empty.str.rfind("a"))
140
+ tm.assert_series_equal(empty_str, empty.str.pad(42))
141
+ tm.assert_series_equal(empty_str, empty.str.center(42))
142
+ tm.assert_series_equal(empty_object, empty.str.split("a"))
143
+ tm.assert_series_equal(empty_object, empty.str.rsplit("a"))
144
+ tm.assert_series_equal(empty_object, empty.str.partition("a", expand=False))
145
+ tm.assert_frame_equal(empty_df, empty.str.partition("a"))
146
+ tm.assert_series_equal(empty_object, empty.str.rpartition("a", expand=False))
147
+ tm.assert_frame_equal(empty_df, empty.str.rpartition("a"))
148
+ tm.assert_series_equal(empty_str, empty.str.slice(stop=1))
149
+ tm.assert_series_equal(empty_str, empty.str.slice(step=1))
150
+ tm.assert_series_equal(empty_str, empty.str.strip())
151
+ tm.assert_series_equal(empty_str, empty.str.lstrip())
152
+ tm.assert_series_equal(empty_str, empty.str.rstrip())
153
+ tm.assert_series_equal(empty_str, empty.str.wrap(42))
154
+ tm.assert_series_equal(empty_str, empty.str.get(0))
155
+ tm.assert_series_equal(empty_object, empty_bytes.str.decode("ascii"))
156
+ tm.assert_series_equal(empty_bytes, empty.str.encode("ascii"))
157
+ # ismethods should always return boolean (GH 29624)
158
+ tm.assert_series_equal(empty_bool, empty.str.isalnum())
159
+ tm.assert_series_equal(empty_bool, empty.str.isalpha())
160
+ tm.assert_series_equal(empty_bool, empty.str.isdigit())
161
+ tm.assert_series_equal(empty_bool, empty.str.isspace())
162
+ tm.assert_series_equal(empty_bool, empty.str.islower())
163
+ tm.assert_series_equal(empty_bool, empty.str.isupper())
164
+ tm.assert_series_equal(empty_bool, empty.str.istitle())
165
+ tm.assert_series_equal(empty_bool, empty.str.isnumeric())
166
+ tm.assert_series_equal(empty_bool, empty.str.isdecimal())
167
+ tm.assert_series_equal(empty_str, empty.str.capitalize())
168
+ tm.assert_series_equal(empty_str, empty.str.swapcase())
169
+ tm.assert_series_equal(empty_str, empty.str.normalize("NFC"))
170
+
171
+ table = str.maketrans("a", "b")
172
+ tm.assert_series_equal(empty_str, empty.str.translate(table))
173
+
174
+
175
+ @pytest.mark.parametrize(
176
+ "method, expected",
177
+ [
178
+ ("isalnum", [True, True, True, True, True, False, True, True, False, False]),
179
+ ("isalpha", [True, True, True, False, False, False, True, False, False, False]),
180
+ (
181
+ "isdigit",
182
+ [False, False, False, True, False, False, False, True, False, False],
183
+ ),
184
+ (
185
+ "isnumeric",
186
+ [False, False, False, True, False, False, False, True, False, False],
187
+ ),
188
+ (
189
+ "isspace",
190
+ [False, False, False, False, False, False, False, False, False, True],
191
+ ),
192
+ (
193
+ "islower",
194
+ [False, True, False, False, False, False, False, False, False, False],
195
+ ),
196
+ (
197
+ "isupper",
198
+ [True, False, False, False, True, False, True, False, False, False],
199
+ ),
200
+ (
201
+ "istitle",
202
+ [True, False, True, False, True, False, False, False, False, False],
203
+ ),
204
+ ],
205
+ )
206
+ def test_ismethods(method, expected, any_string_dtype):
207
+ ser = Series(
208
+ ["A", "b", "Xy", "4", "3A", "", "TT", "55", "-", " "], dtype=any_string_dtype
209
+ )
210
+ expected_dtype = "bool" if any_string_dtype in object_pyarrow_numpy else "boolean"
211
+ expected = Series(expected, dtype=expected_dtype)
212
+ result = getattr(ser.str, method)()
213
+ tm.assert_series_equal(result, expected)
214
+
215
+ # compare with standard library
216
+ expected = [getattr(item, method)() for item in ser]
217
+ assert list(result) == expected
218
+
219
+
220
+ @pytest.mark.parametrize(
221
+ "method, expected",
222
+ [
223
+ ("isnumeric", [False, True, True, False, True, True, False]),
224
+ ("isdecimal", [False, True, False, False, False, True, False]),
225
+ ],
226
+ )
227
+ def test_isnumeric_unicode(method, expected, any_string_dtype):
228
+ # 0x00bc: ¼ VULGAR FRACTION ONE QUARTER
229
+ # 0x2605: ★ not number
230
+ # 0x1378: ፸ ETHIOPIC NUMBER SEVENTY
231
+ # 0xFF13: 3 Em 3 # noqa: RUF003
232
+ ser = Series(
233
+ ["A", "3", "¼", "★", "፸", "3", "four"], dtype=any_string_dtype # noqa: RUF001
234
+ )
235
+ expected_dtype = "bool" if any_string_dtype in object_pyarrow_numpy else "boolean"
236
+ expected = Series(expected, dtype=expected_dtype)
237
+ result = getattr(ser.str, method)()
238
+ tm.assert_series_equal(result, expected)
239
+
240
+ # compare with standard library
241
+ expected = [getattr(item, method)() for item in ser]
242
+ assert list(result) == expected
243
+
244
+
245
+ @pytest.mark.parametrize(
246
+ "method, expected",
247
+ [
248
+ ("isnumeric", [False, np.nan, True, False, np.nan, True, False]),
249
+ ("isdecimal", [False, np.nan, False, False, np.nan, True, False]),
250
+ ],
251
+ )
252
+ def test_isnumeric_unicode_missing(method, expected, any_string_dtype):
253
+ values = ["A", np.nan, "¼", "★", np.nan, "3", "four"] # noqa: RUF001
254
+ ser = Series(values, dtype=any_string_dtype)
255
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
256
+ expected = Series(expected, dtype=expected_dtype)
257
+ result = getattr(ser.str, method)()
258
+ tm.assert_series_equal(result, expected)
259
+
260
+
261
+ def test_spilt_join_roundtrip(any_string_dtype):
262
+ ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
263
+ result = ser.str.split("_").str.join("_")
264
+ expected = ser.astype(object)
265
+ tm.assert_series_equal(result, expected)
266
+
267
+
268
+ def test_spilt_join_roundtrip_mixed_object():
269
+ ser = Series(
270
+ ["a_b", np.nan, "asdf_cas_asdf", True, datetime.today(), "foo", None, 1, 2.0]
271
+ )
272
+ result = ser.str.split("_").str.join("_")
273
+ expected = Series(
274
+ ["a_b", np.nan, "asdf_cas_asdf", np.nan, np.nan, "foo", None, np.nan, np.nan],
275
+ dtype=object,
276
+ )
277
+ tm.assert_series_equal(result, expected)
278
+
279
+
280
+ def test_len(any_string_dtype):
281
+ ser = Series(
282
+ ["foo", "fooo", "fooooo", np.nan, "fooooooo", "foo\n", "あ"],
283
+ dtype=any_string_dtype,
284
+ )
285
+ result = ser.str.len()
286
+ expected_dtype = "float64" if any_string_dtype in object_pyarrow_numpy else "Int64"
287
+ expected = Series([3, 4, 6, np.nan, 8, 4, 1], dtype=expected_dtype)
288
+ tm.assert_series_equal(result, expected)
289
+
290
+
291
+ def test_len_mixed():
292
+ ser = Series(
293
+ ["a_b", np.nan, "asdf_cas_asdf", True, datetime.today(), "foo", None, 1, 2.0]
294
+ )
295
+ result = ser.str.len()
296
+ expected = Series([3, np.nan, 13, np.nan, np.nan, 3, np.nan, np.nan, np.nan])
297
+ tm.assert_series_equal(result, expected)
298
+
299
+
300
+ @pytest.mark.parametrize(
301
+ "method,sub,start,end,expected",
302
+ [
303
+ ("index", "EF", None, None, [4, 3, 1, 0]),
304
+ ("rindex", "EF", None, None, [4, 5, 7, 4]),
305
+ ("index", "EF", 3, None, [4, 3, 7, 4]),
306
+ ("rindex", "EF", 3, None, [4, 5, 7, 4]),
307
+ ("index", "E", 4, 8, [4, 5, 7, 4]),
308
+ ("rindex", "E", 0, 5, [4, 3, 1, 4]),
309
+ ],
310
+ )
311
+ def test_index(method, sub, start, end, index_or_series, any_string_dtype, expected):
312
+ obj = index_or_series(
313
+ ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype
314
+ )
315
+ expected_dtype = np.int64 if any_string_dtype in object_pyarrow_numpy else "Int64"
316
+ expected = index_or_series(expected, dtype=expected_dtype)
317
+
318
+ result = getattr(obj.str, method)(sub, start, end)
319
+
320
+ if index_or_series is Series:
321
+ tm.assert_series_equal(result, expected)
322
+ else:
323
+ tm.assert_index_equal(result, expected)
324
+
325
+ # compare with standard library
326
+ expected = [getattr(item, method)(sub, start, end) for item in obj]
327
+ assert list(result) == expected
328
+
329
+
330
+ def test_index_not_found_raises(index_or_series, any_string_dtype):
331
+ obj = index_or_series(
332
+ ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype
333
+ )
334
+ with pytest.raises(ValueError, match="substring not found"):
335
+ obj.str.index("DE")
336
+
337
+
338
+ @pytest.mark.parametrize("method", ["index", "rindex"])
339
+ def test_index_wrong_type_raises(index_or_series, any_string_dtype, method):
340
+ obj = index_or_series([], dtype=any_string_dtype)
341
+ msg = "expected a string object, not int"
342
+
343
+ with pytest.raises(TypeError, match=msg):
344
+ getattr(obj.str, method)(0)
345
+
346
+
347
+ @pytest.mark.parametrize(
348
+ "method, exp",
349
+ [
350
+ ["index", [1, 1, 0]],
351
+ ["rindex", [3, 1, 2]],
352
+ ],
353
+ )
354
+ def test_index_missing(any_string_dtype, method, exp):
355
+ ser = Series(["abcb", "ab", "bcbe", np.nan], dtype=any_string_dtype)
356
+ expected_dtype = np.float64 if any_string_dtype in object_pyarrow_numpy else "Int64"
357
+
358
+ result = getattr(ser.str, method)("b")
359
+ expected = Series(exp + [np.nan], dtype=expected_dtype)
360
+ tm.assert_series_equal(result, expected)
361
+
362
+
363
+ def test_pipe_failures(any_string_dtype):
364
+ # #2119
365
+ ser = Series(["A|B|C"], dtype=any_string_dtype)
366
+
367
+ result = ser.str.split("|")
368
+ expected = Series([["A", "B", "C"]], dtype=object)
369
+ tm.assert_series_equal(result, expected)
370
+
371
+ result = ser.str.replace("|", " ", regex=False)
372
+ expected = Series(["A B C"], dtype=any_string_dtype)
373
+ tm.assert_series_equal(result, expected)
374
+
375
+
376
+ @pytest.mark.parametrize(
377
+ "start, stop, step, expected",
378
+ [
379
+ (2, 5, None, ["foo", "bar", np.nan, "baz"]),
380
+ (0, 3, -1, ["", "", np.nan, ""]),
381
+ (None, None, -1, ["owtoofaa", "owtrabaa", np.nan, "xuqzabaa"]),
382
+ (3, 10, 2, ["oto", "ato", np.nan, "aqx"]),
383
+ (3, 0, -1, ["ofa", "aba", np.nan, "aba"]),
384
+ ],
385
+ )
386
+ def test_slice(start, stop, step, expected, any_string_dtype):
387
+ ser = Series(["aafootwo", "aabartwo", np.nan, "aabazqux"], dtype=any_string_dtype)
388
+ result = ser.str.slice(start, stop, step)
389
+ expected = Series(expected, dtype=any_string_dtype)
390
+ tm.assert_series_equal(result, expected)
391
+
392
+
393
+ @pytest.mark.parametrize(
394
+ "start, stop, step, expected",
395
+ [
396
+ (2, 5, None, ["foo", np.nan, "bar", np.nan, np.nan, None, np.nan, np.nan]),
397
+ (4, 1, -1, ["oof", np.nan, "rab", np.nan, np.nan, None, np.nan, np.nan]),
398
+ ],
399
+ )
400
+ def test_slice_mixed_object(start, stop, step, expected):
401
+ ser = Series(["aafootwo", np.nan, "aabartwo", True, datetime.today(), None, 1, 2.0])
402
+ result = ser.str.slice(start, stop, step)
403
+ expected = Series(expected, dtype=object)
404
+ tm.assert_series_equal(result, expected)
405
+
406
+
407
+ @pytest.mark.parametrize(
408
+ "start,stop,repl,expected",
409
+ [
410
+ (2, 3, None, ["shrt", "a it longer", "evnlongerthanthat", "", np.nan]),
411
+ (2, 3, "z", ["shzrt", "a zit longer", "evznlongerthanthat", "z", np.nan]),
412
+ (2, 2, "z", ["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]),
413
+ (2, 1, "z", ["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]),
414
+ (-1, None, "z", ["shorz", "a bit longez", "evenlongerthanthaz", "z", np.nan]),
415
+ (None, -2, "z", ["zrt", "zer", "zat", "z", np.nan]),
416
+ (6, 8, "z", ["shortz", "a bit znger", "evenlozerthanthat", "z", np.nan]),
417
+ (-10, 3, "z", ["zrt", "a zit longer", "evenlongzerthanthat", "z", np.nan]),
418
+ ],
419
+ )
420
+ def test_slice_replace(start, stop, repl, expected, any_string_dtype):
421
+ ser = Series(
422
+ ["short", "a bit longer", "evenlongerthanthat", "", np.nan],
423
+ dtype=any_string_dtype,
424
+ )
425
+ expected = Series(expected, dtype=any_string_dtype)
426
+ result = ser.str.slice_replace(start, stop, repl)
427
+ tm.assert_series_equal(result, expected)
428
+
429
+
430
+ @pytest.mark.parametrize(
431
+ "method, exp",
432
+ [
433
+ ["strip", ["aa", "bb", np.nan, "cc"]],
434
+ ["lstrip", ["aa ", "bb \n", np.nan, "cc "]],
435
+ ["rstrip", [" aa", " bb", np.nan, "cc"]],
436
+ ],
437
+ )
438
+ def test_strip_lstrip_rstrip(any_string_dtype, method, exp):
439
+ ser = Series([" aa ", " bb \n", np.nan, "cc "], dtype=any_string_dtype)
440
+
441
+ result = getattr(ser.str, method)()
442
+ expected = Series(exp, dtype=any_string_dtype)
443
+ tm.assert_series_equal(result, expected)
444
+
445
+
446
+ @pytest.mark.parametrize(
447
+ "method, exp",
448
+ [
449
+ ["strip", ["aa", np.nan, "bb"]],
450
+ ["lstrip", ["aa ", np.nan, "bb \t\n"]],
451
+ ["rstrip", [" aa", np.nan, " bb"]],
452
+ ],
453
+ )
454
+ def test_strip_lstrip_rstrip_mixed_object(method, exp):
455
+ ser = Series([" aa ", np.nan, " bb \t\n", True, datetime.today(), None, 1, 2.0])
456
+
457
+ result = getattr(ser.str, method)()
458
+ expected = Series(exp + [np.nan, np.nan, None, np.nan, np.nan], dtype=object)
459
+ tm.assert_series_equal(result, expected)
460
+
461
+
462
+ @pytest.mark.parametrize(
463
+ "method, exp",
464
+ [
465
+ ["strip", ["ABC", " BNSD", "LDFJH "]],
466
+ ["lstrip", ["ABCxx", " BNSD", "LDFJH xx"]],
467
+ ["rstrip", ["xxABC", "xx BNSD", "LDFJH "]],
468
+ ],
469
+ )
470
+ def test_strip_lstrip_rstrip_args(any_string_dtype, method, exp):
471
+ ser = Series(["xxABCxx", "xx BNSD", "LDFJH xx"], dtype=any_string_dtype)
472
+
473
+ result = getattr(ser.str, method)("x")
474
+ expected = Series(exp, dtype=any_string_dtype)
475
+ tm.assert_series_equal(result, expected)
476
+
477
+
478
+ @pytest.mark.parametrize(
479
+ "prefix, expected", [("a", ["b", " b c", "bc"]), ("ab", ["", "a b c", "bc"])]
480
+ )
481
+ def test_removeprefix(any_string_dtype, prefix, expected):
482
+ ser = Series(["ab", "a b c", "bc"], dtype=any_string_dtype)
483
+ result = ser.str.removeprefix(prefix)
484
+ ser_expected = Series(expected, dtype=any_string_dtype)
485
+ tm.assert_series_equal(result, ser_expected)
486
+
487
+
488
+ @pytest.mark.parametrize(
489
+ "suffix, expected", [("c", ["ab", "a b ", "b"]), ("bc", ["ab", "a b c", ""])]
490
+ )
491
+ def test_removesuffix(any_string_dtype, suffix, expected):
492
+ ser = Series(["ab", "a b c", "bc"], dtype=any_string_dtype)
493
+ result = ser.str.removesuffix(suffix)
494
+ ser_expected = Series(expected, dtype=any_string_dtype)
495
+ tm.assert_series_equal(result, ser_expected)
496
+
497
+
498
+ def test_string_slice_get_syntax(any_string_dtype):
499
+ ser = Series(
500
+ ["YYY", "B", "C", "YYYYYYbYYY", "BYYYcYYY", np.nan, "CYYYBYYY", "dog", "cYYYt"],
501
+ dtype=any_string_dtype,
502
+ )
503
+
504
+ result = ser.str[0]
505
+ expected = ser.str.get(0)
506
+ tm.assert_series_equal(result, expected)
507
+
508
+ result = ser.str[:3]
509
+ expected = ser.str.slice(stop=3)
510
+ tm.assert_series_equal(result, expected)
511
+
512
+ result = ser.str[2::-1]
513
+ expected = ser.str.slice(start=2, step=-1)
514
+ tm.assert_series_equal(result, expected)
515
+
516
+
517
+ def test_string_slice_out_of_bounds_nested():
518
+ ser = Series([(1, 2), (1,), (3, 4, 5)])
519
+ result = ser.str[1]
520
+ expected = Series([2, np.nan, 4])
521
+ tm.assert_series_equal(result, expected)
522
+
523
+
524
+ def test_string_slice_out_of_bounds(any_string_dtype):
525
+ ser = Series(["foo", "b", "ba"], dtype=any_string_dtype)
526
+ result = ser.str[1]
527
+ expected = Series(["o", np.nan, "a"], dtype=any_string_dtype)
528
+ tm.assert_series_equal(result, expected)
529
+
530
+
531
+ def test_encode_decode(any_string_dtype):
532
+ ser = Series(["a", "b", "a\xe4"], dtype=any_string_dtype).str.encode("utf-8")
533
+ result = ser.str.decode("utf-8")
534
+ expected = ser.map(lambda x: x.decode("utf-8")).astype(object)
535
+ tm.assert_series_equal(result, expected)
536
+
537
+
538
+ def test_encode_errors_kwarg(any_string_dtype):
539
+ ser = Series(["a", "b", "a\x9d"], dtype=any_string_dtype)
540
+
541
+ msg = (
542
+ r"'charmap' codec can't encode character '\\x9d' in position 1: "
543
+ "character maps to <undefined>"
544
+ )
545
+ with pytest.raises(UnicodeEncodeError, match=msg):
546
+ ser.str.encode("cp1252")
547
+
548
+ result = ser.str.encode("cp1252", "ignore")
549
+ expected = ser.map(lambda x: x.encode("cp1252", "ignore"))
550
+ tm.assert_series_equal(result, expected)
551
+
552
+
553
+ def test_decode_errors_kwarg():
554
+ ser = Series([b"a", b"b", b"a\x9d"])
555
+
556
+ msg = (
557
+ "'charmap' codec can't decode byte 0x9d in position 1: "
558
+ "character maps to <undefined>"
559
+ )
560
+ with pytest.raises(UnicodeDecodeError, match=msg):
561
+ ser.str.decode("cp1252")
562
+
563
+ result = ser.str.decode("cp1252", "ignore")
564
+ expected = ser.map(lambda x: x.decode("cp1252", "ignore")).astype(object)
565
+ tm.assert_series_equal(result, expected)
566
+
567
+
568
+ @pytest.mark.parametrize(
569
+ "form, expected",
570
+ [
571
+ ("NFKC", ["ABC", "ABC", "123", np.nan, "アイエ"]),
572
+ ("NFC", ["ABC", "ABC", "123", np.nan, "アイエ"]), # noqa: RUF001
573
+ ],
574
+ )
575
+ def test_normalize(form, expected, any_string_dtype):
576
+ ser = Series(
577
+ ["ABC", "ABC", "123", np.nan, "アイエ"], # noqa: RUF001
578
+ index=["a", "b", "c", "d", "e"],
579
+ dtype=any_string_dtype,
580
+ )
581
+ expected = Series(expected, index=["a", "b", "c", "d", "e"], dtype=any_string_dtype)
582
+ result = ser.str.normalize(form)
583
+ tm.assert_series_equal(result, expected)
584
+
585
+
586
+ def test_normalize_bad_arg_raises(any_string_dtype):
587
+ ser = Series(
588
+ ["ABC", "ABC", "123", np.nan, "アイエ"], # noqa: RUF001
589
+ index=["a", "b", "c", "d", "e"],
590
+ dtype=any_string_dtype,
591
+ )
592
+ with pytest.raises(ValueError, match="invalid normalization form"):
593
+ ser.str.normalize("xxx")
594
+
595
+
596
+ def test_normalize_index():
597
+ idx = Index(["ABC", "123", "アイエ"]) # noqa: RUF001
598
+ expected = Index(["ABC", "123", "アイエ"])
599
+ result = idx.str.normalize("NFKC")
600
+ tm.assert_index_equal(result, expected)
601
+
602
+
603
+ @pytest.mark.parametrize(
604
+ "values,inferred_type",
605
+ [
606
+ (["a", "b"], "string"),
607
+ (["a", "b", 1], "mixed-integer"),
608
+ (["a", "b", 1.3], "mixed"),
609
+ (["a", "b", 1.3, 1], "mixed-integer"),
610
+ (["aa", datetime(2011, 1, 1)], "mixed"),
611
+ ],
612
+ )
613
+ def test_index_str_accessor_visibility(values, inferred_type, index_or_series):
614
+ obj = index_or_series(values)
615
+ if index_or_series is Index:
616
+ assert obj.inferred_type == inferred_type
617
+
618
+ assert isinstance(obj.str, StringMethods)
619
+
620
+
621
+ @pytest.mark.parametrize(
622
+ "values,inferred_type",
623
+ [
624
+ ([1, np.nan], "floating"),
625
+ ([datetime(2011, 1, 1)], "datetime64"),
626
+ ([timedelta(1)], "timedelta64"),
627
+ ],
628
+ )
629
+ def test_index_str_accessor_non_string_values_raises(
630
+ values, inferred_type, index_or_series
631
+ ):
632
+ obj = index_or_series(values)
633
+ if index_or_series is Index:
634
+ assert obj.inferred_type == inferred_type
635
+
636
+ msg = "Can only use .str accessor with string values"
637
+ with pytest.raises(AttributeError, match=msg):
638
+ obj.str
639
+
640
+
641
+ def test_index_str_accessor_multiindex_raises():
642
+ # MultiIndex has mixed dtype, but not allow to use accessor
643
+ idx = MultiIndex.from_tuples([("a", "b"), ("a", "b")])
644
+ assert idx.inferred_type == "mixed"
645
+
646
+ msg = "Can only use .str accessor with Index, not MultiIndex"
647
+ with pytest.raises(AttributeError, match=msg):
648
+ idx.str
649
+
650
+
651
+ def test_str_accessor_no_new_attributes(any_string_dtype):
652
+ # https://github.com/pandas-dev/pandas/issues/10673
653
+ ser = Series(list("aabbcde"), dtype=any_string_dtype)
654
+ with pytest.raises(AttributeError, match="You cannot add any new attribute"):
655
+ ser.str.xlabel = "a"
656
+
657
+
658
+ def test_cat_on_bytes_raises():
659
+ lhs = Series(np.array(list("abc"), "S1").astype(object))
660
+ rhs = Series(np.array(list("def"), "S1").astype(object))
661
+ msg = "Cannot use .str.cat with values of inferred dtype 'bytes'"
662
+ with pytest.raises(TypeError, match=msg):
663
+ lhs.str.cat(rhs)
664
+
665
+
666
+ def test_str_accessor_in_apply_func():
667
+ # https://github.com/pandas-dev/pandas/issues/38979
668
+ df = DataFrame(zip("abc", "def"))
669
+ expected = Series(["A/D", "B/E", "C/F"])
670
+ result = df.apply(lambda f: "/".join(f.str.upper()), axis=1)
671
+ tm.assert_series_equal(result, expected)
672
+
673
+
674
+ def test_zfill():
675
+ # https://github.com/pandas-dev/pandas/issues/20868
676
+ value = Series(["-1", "1", "1000", 10, np.nan])
677
+ expected = Series(["-01", "001", "1000", np.nan, np.nan], dtype=object)
678
+ tm.assert_series_equal(value.str.zfill(3), expected)
679
+
680
+ value = Series(["-2", "+5"])
681
+ expected = Series(["-0002", "+0005"])
682
+ tm.assert_series_equal(value.str.zfill(5), expected)
683
+
684
+
685
+ def test_zfill_with_non_integer_argument():
686
+ value = Series(["-2", "+5"])
687
+ wid = "a"
688
+ msg = f"width must be of integer type, not {type(wid).__name__}"
689
+ with pytest.raises(TypeError, match=msg):
690
+ value.str.zfill(wid)
691
+
692
+
693
+ def test_zfill_with_leading_sign():
694
+ value = Series(["-cat", "-1", "+dog"])
695
+ expected = Series(["-0cat", "-0001", "+0dog"])
696
+ tm.assert_series_equal(value.str.zfill(5), expected)
697
+
698
+
699
+ def test_get_with_dict_label():
700
+ # GH47911
701
+ s = Series(
702
+ [
703
+ {"name": "Hello", "value": "World"},
704
+ {"name": "Goodbye", "value": "Planet"},
705
+ {"value": "Sea"},
706
+ ]
707
+ )
708
+ result = s.str.get("name")
709
+ expected = Series(["Hello", "Goodbye", None], dtype=object)
710
+ tm.assert_series_equal(result, expected)
711
+ result = s.str.get("value")
712
+ expected = Series(["World", "Planet", "Sea"], dtype=object)
713
+ tm.assert_series_equal(result, expected)
714
+
715
+
716
+ def test_series_str_decode():
717
+ # GH 22613
718
+ result = Series([b"x", b"y"]).str.decode(encoding="UTF-8", errors="strict")
719
+ expected = Series(["x", "y"], dtype="object")
720
+ tm.assert_series_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_api.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_array_to_datetime.cpython-310.pyc ADDED
Binary file (10.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_ccalendar.cpython-310.pyc ADDED
Binary file (2.14 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_conversion.cpython-310.pyc ADDED
Binary file (4.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_fields.cpython-310.pyc ADDED
Binary file (1.64 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_libfrequencies.cpython-310.pyc ADDED
Binary file (825 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_liboffsets.cpython-310.pyc ADDED
Binary file (4.48 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_np_datetime.cpython-310.pyc ADDED
Binary file (5.77 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_npy_units.cpython-310.pyc ADDED
Binary file (1.32 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_parse_iso8601.cpython-310.pyc ADDED
Binary file (3.27 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_parsing.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_period.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_resolution.cpython-310.pyc ADDED
Binary file (1.79 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_strptime.cpython-310.pyc ADDED
Binary file (3.71 kB). View file