applied-ai-018 commited on
Commit
4f7d998
·
verified ·
1 Parent(s): 79490f8

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. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_10_mp_rank_02_optim_states.pt +3 -0
  2. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_117_mp_rank_01_optim_states.pt +3 -0
  3. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_166_mp_rank_00_optim_states.pt +3 -0
  4. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_176_mp_rank_01_optim_states.pt +3 -0
  5. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_25_mp_rank_02_optim_states.pt +3 -0
  6. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_42_mp_rank_02_optim_states.pt +3 -0
  7. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__init__.py +0 -0
  8. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/__init__.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/common.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/conftest.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_array_ops.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_categorical.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_datetime64.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_interval.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_numeric.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_object.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_period.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_timedelta64.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/common.py +155 -0
  20. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/conftest.py +139 -0
  21. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_array_ops.py +39 -0
  22. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_categorical.py +25 -0
  23. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_datetime64.py +2469 -0
  24. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_interval.py +306 -0
  25. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_numeric.py +1567 -0
  26. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_object.py +420 -0
  27. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_period.py +1675 -0
  28. venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_timedelta64.py +2173 -0
  29. venv/lib/python3.10/site-packages/pandas/tests/computation/__init__.py +0 -0
  30. venv/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/__init__.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/test_compat.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/test_eval.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pandas/tests/computation/test_compat.py +32 -0
  34. venv/lib/python3.10/site-packages/pandas/tests/computation/test_eval.py +1991 -0
  35. venv/lib/python3.10/site-packages/pandas/tests/config/__init__.py +0 -0
  36. venv/lib/python3.10/site-packages/pandas/tests/config/__pycache__/__init__.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pandas/tests/config/__pycache__/test_config.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pandas/tests/config/__pycache__/test_localization.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pandas/tests/config/test_config.py +437 -0
  40. venv/lib/python3.10/site-packages/pandas/tests/config/test_localization.py +156 -0
  41. venv/lib/python3.10/site-packages/pandas/tests/interchange/__init__.py +0 -0
  42. venv/lib/python3.10/site-packages/pandas/tests/interchange/__pycache__/__init__.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/pandas/tests/interchange/__pycache__/test_impl.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/pandas/tests/interchange/__pycache__/test_spec_conformance.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/pandas/tests/interchange/__pycache__/test_utils.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/pandas/tests/interchange/test_impl.py +604 -0
  47. venv/lib/python3.10/site-packages/pandas/tests/interchange/test_spec_conformance.py +175 -0
  48. venv/lib/python3.10/site-packages/pandas/tests/interchange/test_utils.py +89 -0
  49. venv/lib/python3.10/site-packages/pandas/tests/reductions/__init__.py +4 -0
  50. venv/lib/python3.10/site-packages/pandas/tests/reductions/test_stat_reductions.py +276 -0
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_10_mp_rank_02_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a83522709ecd9e873c718d26614a3a6610a535a441fcf1cc30fc62e45cb97de1
3
+ size 41830330
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_117_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a266534bf7539e089f03a1a369c7ceaee93c684db7f904f21b2798b019553684
3
+ size 41830212
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_166_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0242e5e55a1f46aa3a7d21ab2c78078fc66aa6dc31b1e93a60f5594dba3d674a
3
+ size 41830148
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_176_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42e58701f480ca658cdbcbbd73ce25dc83b00a8a12ca2403d941a4e965ffddc0
3
+ size 41830148
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_25_mp_rank_02_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3dda639e987980fbc5d2e2a63094ae8d7a10a5494214926518211962981229c
3
+ size 41830330
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_42_mp_rank_02_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c07c177eb87a7b23774429e588417b8bc5213dc448f3d2e6fdae42a9e8d7c04f
3
+ size 41830330
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (191 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/common.cpython-310.pyc ADDED
Binary file (3.83 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (3.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_array_ops.cpython-310.pyc ADDED
Binary file (1.18 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_categorical.cpython-310.pyc ADDED
Binary file (1.19 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_datetime64.cpython-310.pyc ADDED
Binary file (59 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_interval.cpython-310.pyc ADDED
Binary file (8.78 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_numeric.cpython-310.pyc ADDED
Binary file (44.6 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_object.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_period.cpython-310.pyc ADDED
Binary file (46.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/__pycache__/test_timedelta64.cpython-310.pyc ADDED
Binary file (54.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/common.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Assertion helpers for arithmetic tests.
3
+ """
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas import (
8
+ DataFrame,
9
+ Index,
10
+ Series,
11
+ array,
12
+ )
13
+ import pandas._testing as tm
14
+ from pandas.core.arrays import (
15
+ BooleanArray,
16
+ NumpyExtensionArray,
17
+ )
18
+
19
+
20
+ def assert_cannot_add(left, right, msg="cannot add"):
21
+ """
22
+ Helper to assert that left and right cannot be added.
23
+
24
+ Parameters
25
+ ----------
26
+ left : object
27
+ right : object
28
+ msg : str, default "cannot add"
29
+ """
30
+ with pytest.raises(TypeError, match=msg):
31
+ left + right
32
+ with pytest.raises(TypeError, match=msg):
33
+ right + left
34
+
35
+
36
+ def assert_invalid_addsub_type(left, right, msg=None):
37
+ """
38
+ Helper to assert that left and right can be neither added nor subtracted.
39
+
40
+ Parameters
41
+ ----------
42
+ left : object
43
+ right : object
44
+ msg : str or None, default None
45
+ """
46
+ with pytest.raises(TypeError, match=msg):
47
+ left + right
48
+ with pytest.raises(TypeError, match=msg):
49
+ right + left
50
+ with pytest.raises(TypeError, match=msg):
51
+ left - right
52
+ with pytest.raises(TypeError, match=msg):
53
+ right - left
54
+
55
+
56
+ def get_upcast_box(left, right, is_cmp: bool = False):
57
+ """
58
+ Get the box to use for 'expected' in an arithmetic or comparison operation.
59
+
60
+ Parameters
61
+ left : Any
62
+ right : Any
63
+ is_cmp : bool, default False
64
+ Whether the operation is a comparison method.
65
+ """
66
+
67
+ if isinstance(left, DataFrame) or isinstance(right, DataFrame):
68
+ return DataFrame
69
+ if isinstance(left, Series) or isinstance(right, Series):
70
+ if is_cmp and isinstance(left, Index):
71
+ # Index does not defer for comparisons
72
+ return np.array
73
+ return Series
74
+ if isinstance(left, Index) or isinstance(right, Index):
75
+ if is_cmp:
76
+ return np.array
77
+ return Index
78
+ return tm.to_array
79
+
80
+
81
+ def assert_invalid_comparison(left, right, box):
82
+ """
83
+ Assert that comparison operations with mismatched types behave correctly.
84
+
85
+ Parameters
86
+ ----------
87
+ left : np.ndarray, ExtensionArray, Index, or Series
88
+ right : object
89
+ box : {pd.DataFrame, pd.Series, pd.Index, pd.array, tm.to_array}
90
+ """
91
+ # Not for tznaive-tzaware comparison
92
+
93
+ # Note: not quite the same as how we do this for tm.box_expected
94
+ xbox = box if box not in [Index, array] else np.array
95
+
96
+ def xbox2(x):
97
+ # Eventually we'd like this to be tighter, but for now we'll
98
+ # just exclude NumpyExtensionArray[bool]
99
+ if isinstance(x, NumpyExtensionArray):
100
+ return x._ndarray
101
+ if isinstance(x, BooleanArray):
102
+ # NB: we are assuming no pd.NAs for now
103
+ return x.astype(bool)
104
+ return x
105
+
106
+ # rev_box: box to use for reversed comparisons
107
+ rev_box = xbox
108
+ if isinstance(right, Index) and isinstance(left, Series):
109
+ rev_box = np.array
110
+
111
+ result = xbox2(left == right)
112
+ expected = xbox(np.zeros(result.shape, dtype=np.bool_))
113
+
114
+ tm.assert_equal(result, expected)
115
+
116
+ result = xbox2(right == left)
117
+ tm.assert_equal(result, rev_box(expected))
118
+
119
+ result = xbox2(left != right)
120
+ tm.assert_equal(result, ~expected)
121
+
122
+ result = xbox2(right != left)
123
+ tm.assert_equal(result, rev_box(~expected))
124
+
125
+ msg = "|".join(
126
+ [
127
+ "Invalid comparison between",
128
+ "Cannot compare type",
129
+ "not supported between",
130
+ "invalid type promotion",
131
+ (
132
+ # GH#36706 npdev 1.20.0 2020-09-28
133
+ r"The DTypes <class 'numpy.dtype\[datetime64\]'> and "
134
+ r"<class 'numpy.dtype\[int64\]'> do not have a common DType. "
135
+ "For example they cannot be stored in a single array unless the "
136
+ "dtype is `object`."
137
+ ),
138
+ ]
139
+ )
140
+ with pytest.raises(TypeError, match=msg):
141
+ left < right
142
+ with pytest.raises(TypeError, match=msg):
143
+ left <= right
144
+ with pytest.raises(TypeError, match=msg):
145
+ left > right
146
+ with pytest.raises(TypeError, match=msg):
147
+ left >= right
148
+ with pytest.raises(TypeError, match=msg):
149
+ right < left
150
+ with pytest.raises(TypeError, match=msg):
151
+ right <= left
152
+ with pytest.raises(TypeError, match=msg):
153
+ right > left
154
+ with pytest.raises(TypeError, match=msg):
155
+ right >= left
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/conftest.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import Index
6
+
7
+
8
+ @pytest.fixture(params=[1, np.array(1, dtype=np.int64)])
9
+ def one(request):
10
+ """
11
+ Several variants of integer value 1. The zero-dim integer array
12
+ behaves like an integer.
13
+
14
+ This fixture can be used to check that datetimelike indexes handle
15
+ addition and subtraction of integers and zero-dimensional arrays
16
+ of integers.
17
+
18
+ Examples
19
+ --------
20
+ dti = pd.date_range('2016-01-01', periods=2, freq='h')
21
+ dti
22
+ DatetimeIndex(['2016-01-01 00:00:00', '2016-01-01 01:00:00'],
23
+ dtype='datetime64[ns]', freq='h')
24
+ dti + one
25
+ DatetimeIndex(['2016-01-01 01:00:00', '2016-01-01 02:00:00'],
26
+ dtype='datetime64[ns]', freq='h')
27
+ """
28
+ return request.param
29
+
30
+
31
+ zeros = [
32
+ box_cls([0] * 5, dtype=dtype)
33
+ for box_cls in [Index, np.array, pd.array]
34
+ for dtype in [np.int64, np.uint64, np.float64]
35
+ ]
36
+ zeros.extend([box_cls([-0.0] * 5, dtype=np.float64) for box_cls in [Index, np.array]])
37
+ zeros.extend([np.array(0, dtype=dtype) for dtype in [np.int64, np.uint64, np.float64]])
38
+ zeros.extend([np.array(-0.0, dtype=np.float64)])
39
+ zeros.extend([0, 0.0, -0.0])
40
+
41
+
42
+ @pytest.fixture(params=zeros)
43
+ def zero(request):
44
+ """
45
+ Several types of scalar zeros and length 5 vectors of zeros.
46
+
47
+ This fixture can be used to check that numeric-dtype indexes handle
48
+ division by any zero numeric-dtype.
49
+
50
+ Uses vector of length 5 for broadcasting with `numeric_idx` fixture,
51
+ which creates numeric-dtype vectors also of length 5.
52
+
53
+ Examples
54
+ --------
55
+ arr = RangeIndex(5)
56
+ arr / zeros
57
+ Index([nan, inf, inf, inf, inf], dtype='float64')
58
+ """
59
+ return request.param
60
+
61
+
62
+ # ------------------------------------------------------------------
63
+ # Scalar Fixtures
64
+
65
+
66
+ @pytest.fixture(
67
+ params=[
68
+ pd.Timedelta("10m7s").to_pytimedelta(),
69
+ pd.Timedelta("10m7s"),
70
+ pd.Timedelta("10m7s").to_timedelta64(),
71
+ ],
72
+ ids=lambda x: type(x).__name__,
73
+ )
74
+ def scalar_td(request):
75
+ """
76
+ Several variants of Timedelta scalars representing 10 minutes and 7 seconds.
77
+ """
78
+ return request.param
79
+
80
+
81
+ @pytest.fixture(
82
+ params=[
83
+ pd.offsets.Day(3),
84
+ pd.offsets.Hour(72),
85
+ pd.Timedelta(days=3).to_pytimedelta(),
86
+ pd.Timedelta("72:00:00"),
87
+ np.timedelta64(3, "D"),
88
+ np.timedelta64(72, "h"),
89
+ ],
90
+ ids=lambda x: type(x).__name__,
91
+ )
92
+ def three_days(request):
93
+ """
94
+ Several timedelta-like and DateOffset objects that each represent
95
+ a 3-day timedelta
96
+ """
97
+ return request.param
98
+
99
+
100
+ @pytest.fixture(
101
+ params=[
102
+ pd.offsets.Hour(2),
103
+ pd.offsets.Minute(120),
104
+ pd.Timedelta(hours=2).to_pytimedelta(),
105
+ pd.Timedelta(seconds=2 * 3600),
106
+ np.timedelta64(2, "h"),
107
+ np.timedelta64(120, "m"),
108
+ ],
109
+ ids=lambda x: type(x).__name__,
110
+ )
111
+ def two_hours(request):
112
+ """
113
+ Several timedelta-like and DateOffset objects that each represent
114
+ a 2-hour timedelta
115
+ """
116
+ return request.param
117
+
118
+
119
+ _common_mismatch = [
120
+ pd.offsets.YearBegin(2),
121
+ pd.offsets.MonthBegin(1),
122
+ pd.offsets.Minute(),
123
+ ]
124
+
125
+
126
+ @pytest.fixture(
127
+ params=[
128
+ np.timedelta64(4, "h"),
129
+ pd.Timedelta(hours=23).to_pytimedelta(),
130
+ pd.Timedelta("23:00:00"),
131
+ ]
132
+ + _common_mismatch
133
+ )
134
+ def not_daily(request):
135
+ """
136
+ Several timedelta-like and DateOffset instances that are _not_
137
+ compatible with Daily frequencies.
138
+ """
139
+ return request.param
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_array_ops.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas._testing as tm
7
+ from pandas.core.ops.array_ops import (
8
+ comparison_op,
9
+ na_logical_op,
10
+ )
11
+
12
+
13
+ def test_na_logical_op_2d():
14
+ left = np.arange(8).reshape(4, 2)
15
+ right = left.astype(object)
16
+ right[0, 0] = np.nan
17
+
18
+ # Check that we fall back to the vec_binop branch
19
+ with pytest.raises(TypeError, match="unsupported operand type"):
20
+ operator.or_(left, right)
21
+
22
+ result = na_logical_op(left, right, operator.or_)
23
+ expected = right
24
+ tm.assert_numpy_array_equal(result, expected)
25
+
26
+
27
+ def test_object_comparison_2d():
28
+ left = np.arange(9).reshape(3, 3).astype(object)
29
+ right = left.T
30
+
31
+ result = comparison_op(left, right, operator.eq)
32
+ expected = np.eye(3).astype(bool)
33
+ tm.assert_numpy_array_equal(result, expected)
34
+
35
+ # Ensure that cython doesn't raise on non-writeable arg, which
36
+ # we can get from np.broadcast_to
37
+ right.flags.writeable = False
38
+ result = comparison_op(left, right, operator.ne)
39
+ tm.assert_numpy_array_equal(result, ~expected)
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_categorical.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas import (
4
+ Categorical,
5
+ Series,
6
+ )
7
+ import pandas._testing as tm
8
+
9
+
10
+ class TestCategoricalComparisons:
11
+ def test_categorical_nan_equality(self):
12
+ cat = Series(Categorical(["a", "b", "c", np.nan]))
13
+ expected = Series([True, True, True, False])
14
+ result = cat == cat
15
+ tm.assert_series_equal(result, expected)
16
+
17
+ def test_categorical_tuple_equality(self):
18
+ # GH 18050
19
+ ser = Series([(0, 0), (0, 1), (0, 0), (1, 0), (1, 1)])
20
+ expected = Series([True, False, True, False, False])
21
+ result = ser == (0, 0)
22
+ tm.assert_series_equal(result, expected)
23
+
24
+ result = ser.astype("category") == (0, 0)
25
+ tm.assert_series_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_datetime64.py ADDED
@@ -0,0 +1,2469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Arithmetic tests for DataFrame/Series/Index/Array classes that should
2
+ # behave identically.
3
+ # Specifically for datetime64 and datetime64tz dtypes
4
+ from datetime import (
5
+ datetime,
6
+ time,
7
+ timedelta,
8
+ )
9
+ from itertools import (
10
+ product,
11
+ starmap,
12
+ )
13
+ import operator
14
+
15
+ import numpy as np
16
+ import pytest
17
+ import pytz
18
+
19
+ from pandas._libs.tslibs.conversion import localize_pydatetime
20
+ from pandas._libs.tslibs.offsets import shift_months
21
+ from pandas.errors import PerformanceWarning
22
+
23
+ import pandas as pd
24
+ from pandas import (
25
+ DateOffset,
26
+ DatetimeIndex,
27
+ NaT,
28
+ Period,
29
+ Series,
30
+ Timedelta,
31
+ TimedeltaIndex,
32
+ Timestamp,
33
+ date_range,
34
+ )
35
+ import pandas._testing as tm
36
+ from pandas.core import roperator
37
+ from pandas.tests.arithmetic.common import (
38
+ assert_cannot_add,
39
+ assert_invalid_addsub_type,
40
+ assert_invalid_comparison,
41
+ get_upcast_box,
42
+ )
43
+
44
+ # ------------------------------------------------------------------
45
+ # Comparisons
46
+
47
+
48
+ class TestDatetime64ArrayLikeComparisons:
49
+ # Comparison tests for datetime64 vectors fully parametrized over
50
+ # DataFrame/Series/DatetimeIndex/DatetimeArray. Ideally all comparison
51
+ # tests will eventually end up here.
52
+
53
+ def test_compare_zerodim(self, tz_naive_fixture, box_with_array):
54
+ # Test comparison with zero-dimensional array is unboxed
55
+ tz = tz_naive_fixture
56
+ box = box_with_array
57
+ dti = date_range("20130101", periods=3, tz=tz)
58
+
59
+ other = np.array(dti.to_numpy()[0])
60
+
61
+ dtarr = tm.box_expected(dti, box)
62
+ xbox = get_upcast_box(dtarr, other, True)
63
+ result = dtarr <= other
64
+ expected = np.array([True, False, False])
65
+ expected = tm.box_expected(expected, xbox)
66
+ tm.assert_equal(result, expected)
67
+
68
+ @pytest.mark.parametrize(
69
+ "other",
70
+ [
71
+ "foo",
72
+ -1,
73
+ 99,
74
+ 4.0,
75
+ object(),
76
+ timedelta(days=2),
77
+ # GH#19800, GH#19301 datetime.date comparison raises to
78
+ # match DatetimeIndex/Timestamp. This also matches the behavior
79
+ # of stdlib datetime.datetime
80
+ datetime(2001, 1, 1).date(),
81
+ # GH#19301 None and NaN are *not* cast to NaT for comparisons
82
+ None,
83
+ np.nan,
84
+ ],
85
+ )
86
+ def test_dt64arr_cmp_scalar_invalid(self, other, tz_naive_fixture, box_with_array):
87
+ # GH#22074, GH#15966
88
+ tz = tz_naive_fixture
89
+
90
+ rng = date_range("1/1/2000", periods=10, tz=tz)
91
+ dtarr = tm.box_expected(rng, box_with_array)
92
+ assert_invalid_comparison(dtarr, other, box_with_array)
93
+
94
+ @pytest.mark.parametrize(
95
+ "other",
96
+ [
97
+ # GH#4968 invalid date/int comparisons
98
+ list(range(10)),
99
+ np.arange(10),
100
+ np.arange(10).astype(np.float32),
101
+ np.arange(10).astype(object),
102
+ pd.timedelta_range("1ns", periods=10).array,
103
+ np.array(pd.timedelta_range("1ns", periods=10)),
104
+ list(pd.timedelta_range("1ns", periods=10)),
105
+ pd.timedelta_range("1 Day", periods=10).astype(object),
106
+ pd.period_range("1971-01-01", freq="D", periods=10).array,
107
+ pd.period_range("1971-01-01", freq="D", periods=10).astype(object),
108
+ ],
109
+ )
110
+ def test_dt64arr_cmp_arraylike_invalid(
111
+ self, other, tz_naive_fixture, box_with_array
112
+ ):
113
+ tz = tz_naive_fixture
114
+
115
+ dta = date_range("1970-01-01", freq="ns", periods=10, tz=tz)._data
116
+ obj = tm.box_expected(dta, box_with_array)
117
+ assert_invalid_comparison(obj, other, box_with_array)
118
+
119
+ def test_dt64arr_cmp_mixed_invalid(self, tz_naive_fixture):
120
+ tz = tz_naive_fixture
121
+
122
+ dta = date_range("1970-01-01", freq="h", periods=5, tz=tz)._data
123
+
124
+ other = np.array([0, 1, 2, dta[3], Timedelta(days=1)])
125
+ result = dta == other
126
+ expected = np.array([False, False, False, True, False])
127
+ tm.assert_numpy_array_equal(result, expected)
128
+
129
+ result = dta != other
130
+ tm.assert_numpy_array_equal(result, ~expected)
131
+
132
+ msg = "Invalid comparison between|Cannot compare type|not supported between"
133
+ with pytest.raises(TypeError, match=msg):
134
+ dta < other
135
+ with pytest.raises(TypeError, match=msg):
136
+ dta > other
137
+ with pytest.raises(TypeError, match=msg):
138
+ dta <= other
139
+ with pytest.raises(TypeError, match=msg):
140
+ dta >= other
141
+
142
+ def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array):
143
+ # GH#22242, GH#22163 DataFrame considered NaT == ts incorrectly
144
+ tz = tz_naive_fixture
145
+ box = box_with_array
146
+
147
+ ts = Timestamp("2021-01-01", tz=tz)
148
+ ser = Series([ts, NaT])
149
+
150
+ obj = tm.box_expected(ser, box)
151
+ xbox = get_upcast_box(obj, ts, True)
152
+
153
+ expected = Series([True, False], dtype=np.bool_)
154
+ expected = tm.box_expected(expected, xbox)
155
+
156
+ result = obj == ts
157
+ tm.assert_equal(result, expected)
158
+
159
+
160
+ class TestDatetime64SeriesComparison:
161
+ # TODO: moved from tests.series.test_operators; needs cleanup
162
+
163
+ @pytest.mark.parametrize(
164
+ "pair",
165
+ [
166
+ (
167
+ [Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")],
168
+ [NaT, NaT, Timestamp("2011-01-03")],
169
+ ),
170
+ (
171
+ [Timedelta("1 days"), NaT, Timedelta("3 days")],
172
+ [NaT, NaT, Timedelta("3 days")],
173
+ ),
174
+ (
175
+ [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")],
176
+ [NaT, NaT, Period("2011-03", freq="M")],
177
+ ),
178
+ ],
179
+ )
180
+ @pytest.mark.parametrize("reverse", [True, False])
181
+ @pytest.mark.parametrize("dtype", [None, object])
182
+ @pytest.mark.parametrize(
183
+ "op, expected",
184
+ [
185
+ (operator.eq, Series([False, False, True])),
186
+ (operator.ne, Series([True, True, False])),
187
+ (operator.lt, Series([False, False, False])),
188
+ (operator.gt, Series([False, False, False])),
189
+ (operator.ge, Series([False, False, True])),
190
+ (operator.le, Series([False, False, True])),
191
+ ],
192
+ )
193
+ def test_nat_comparisons(
194
+ self,
195
+ dtype,
196
+ index_or_series,
197
+ reverse,
198
+ pair,
199
+ op,
200
+ expected,
201
+ ):
202
+ box = index_or_series
203
+ lhs, rhs = pair
204
+ if reverse:
205
+ # add lhs / rhs switched data
206
+ lhs, rhs = rhs, lhs
207
+
208
+ left = Series(lhs, dtype=dtype)
209
+ right = box(rhs, dtype=dtype)
210
+
211
+ result = op(left, right)
212
+
213
+ tm.assert_series_equal(result, expected)
214
+
215
+ @pytest.mark.parametrize(
216
+ "data",
217
+ [
218
+ [Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")],
219
+ [Timedelta("1 days"), NaT, Timedelta("3 days")],
220
+ [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")],
221
+ ],
222
+ )
223
+ @pytest.mark.parametrize("dtype", [None, object])
224
+ def test_nat_comparisons_scalar(self, dtype, data, box_with_array):
225
+ box = box_with_array
226
+
227
+ left = Series(data, dtype=dtype)
228
+ left = tm.box_expected(left, box)
229
+ xbox = get_upcast_box(left, NaT, True)
230
+
231
+ expected = [False, False, False]
232
+ expected = tm.box_expected(expected, xbox)
233
+ if box is pd.array and dtype is object:
234
+ expected = pd.array(expected, dtype="bool")
235
+
236
+ tm.assert_equal(left == NaT, expected)
237
+ tm.assert_equal(NaT == left, expected)
238
+
239
+ expected = [True, True, True]
240
+ expected = tm.box_expected(expected, xbox)
241
+ if box is pd.array and dtype is object:
242
+ expected = pd.array(expected, dtype="bool")
243
+ tm.assert_equal(left != NaT, expected)
244
+ tm.assert_equal(NaT != left, expected)
245
+
246
+ expected = [False, False, False]
247
+ expected = tm.box_expected(expected, xbox)
248
+ if box is pd.array and dtype is object:
249
+ expected = pd.array(expected, dtype="bool")
250
+ tm.assert_equal(left < NaT, expected)
251
+ tm.assert_equal(NaT > left, expected)
252
+ tm.assert_equal(left <= NaT, expected)
253
+ tm.assert_equal(NaT >= left, expected)
254
+
255
+ tm.assert_equal(left > NaT, expected)
256
+ tm.assert_equal(NaT < left, expected)
257
+ tm.assert_equal(left >= NaT, expected)
258
+ tm.assert_equal(NaT <= left, expected)
259
+
260
+ @pytest.mark.parametrize("val", [datetime(2000, 1, 4), datetime(2000, 1, 5)])
261
+ def test_series_comparison_scalars(self, val):
262
+ series = Series(date_range("1/1/2000", periods=10))
263
+
264
+ result = series > val
265
+ expected = Series([x > val for x in series])
266
+ tm.assert_series_equal(result, expected)
267
+
268
+ @pytest.mark.parametrize(
269
+ "left,right", [("lt", "gt"), ("le", "ge"), ("eq", "eq"), ("ne", "ne")]
270
+ )
271
+ def test_timestamp_compare_series(self, left, right):
272
+ # see gh-4982
273
+ # Make sure we can compare Timestamps on the right AND left hand side.
274
+ ser = Series(date_range("20010101", periods=10), name="dates")
275
+ s_nat = ser.copy(deep=True)
276
+
277
+ ser[0] = Timestamp("nat")
278
+ ser[3] = Timestamp("nat")
279
+
280
+ left_f = getattr(operator, left)
281
+ right_f = getattr(operator, right)
282
+
283
+ # No NaT
284
+ expected = left_f(ser, Timestamp("20010109"))
285
+ result = right_f(Timestamp("20010109"), ser)
286
+ tm.assert_series_equal(result, expected)
287
+
288
+ # NaT
289
+ expected = left_f(ser, Timestamp("nat"))
290
+ result = right_f(Timestamp("nat"), ser)
291
+ tm.assert_series_equal(result, expected)
292
+
293
+ # Compare to Timestamp with series containing NaT
294
+ expected = left_f(s_nat, Timestamp("20010109"))
295
+ result = right_f(Timestamp("20010109"), s_nat)
296
+ tm.assert_series_equal(result, expected)
297
+
298
+ # Compare to NaT with series containing NaT
299
+ expected = left_f(s_nat, NaT)
300
+ result = right_f(NaT, s_nat)
301
+ tm.assert_series_equal(result, expected)
302
+
303
+ def test_dt64arr_timestamp_equality(self, box_with_array):
304
+ # GH#11034
305
+ box = box_with_array
306
+
307
+ ser = Series([Timestamp("2000-01-29 01:59:00"), Timestamp("2000-01-30"), NaT])
308
+ ser = tm.box_expected(ser, box)
309
+ xbox = get_upcast_box(ser, ser, True)
310
+
311
+ result = ser != ser
312
+ expected = tm.box_expected([False, False, True], xbox)
313
+ tm.assert_equal(result, expected)
314
+
315
+ if box is pd.DataFrame:
316
+ # alignment for frame vs series comparisons deprecated
317
+ # in GH#46795 enforced 2.0
318
+ with pytest.raises(ValueError, match="not aligned"):
319
+ ser != ser[0]
320
+
321
+ else:
322
+ result = ser != ser[0]
323
+ expected = tm.box_expected([False, True, True], xbox)
324
+ tm.assert_equal(result, expected)
325
+
326
+ if box is pd.DataFrame:
327
+ # alignment for frame vs series comparisons deprecated
328
+ # in GH#46795 enforced 2.0
329
+ with pytest.raises(ValueError, match="not aligned"):
330
+ ser != ser[2]
331
+ else:
332
+ result = ser != ser[2]
333
+ expected = tm.box_expected([True, True, True], xbox)
334
+ tm.assert_equal(result, expected)
335
+
336
+ result = ser == ser
337
+ expected = tm.box_expected([True, True, False], xbox)
338
+ tm.assert_equal(result, expected)
339
+
340
+ if box is pd.DataFrame:
341
+ # alignment for frame vs series comparisons deprecated
342
+ # in GH#46795 enforced 2.0
343
+ with pytest.raises(ValueError, match="not aligned"):
344
+ ser == ser[0]
345
+ else:
346
+ result = ser == ser[0]
347
+ expected = tm.box_expected([True, False, False], xbox)
348
+ tm.assert_equal(result, expected)
349
+
350
+ if box is pd.DataFrame:
351
+ # alignment for frame vs series comparisons deprecated
352
+ # in GH#46795 enforced 2.0
353
+ with pytest.raises(ValueError, match="not aligned"):
354
+ ser == ser[2]
355
+ else:
356
+ result = ser == ser[2]
357
+ expected = tm.box_expected([False, False, False], xbox)
358
+ tm.assert_equal(result, expected)
359
+
360
+ @pytest.mark.parametrize(
361
+ "datetimelike",
362
+ [
363
+ Timestamp("20130101"),
364
+ datetime(2013, 1, 1),
365
+ np.datetime64("2013-01-01T00:00", "ns"),
366
+ ],
367
+ )
368
+ @pytest.mark.parametrize(
369
+ "op,expected",
370
+ [
371
+ (operator.lt, [True, False, False, False]),
372
+ (operator.le, [True, True, False, False]),
373
+ (operator.eq, [False, True, False, False]),
374
+ (operator.gt, [False, False, False, True]),
375
+ ],
376
+ )
377
+ def test_dt64_compare_datetime_scalar(self, datetimelike, op, expected):
378
+ # GH#17965, test for ability to compare datetime64[ns] columns
379
+ # to datetimelike
380
+ ser = Series(
381
+ [
382
+ Timestamp("20120101"),
383
+ Timestamp("20130101"),
384
+ np.nan,
385
+ Timestamp("20130103"),
386
+ ],
387
+ name="A",
388
+ )
389
+ result = op(ser, datetimelike)
390
+ expected = Series(expected, name="A")
391
+ tm.assert_series_equal(result, expected)
392
+
393
+
394
+ class TestDatetimeIndexComparisons:
395
+ # TODO: moved from tests.indexes.test_base; parametrize and de-duplicate
396
+ def test_comparators(self, comparison_op):
397
+ index = date_range("2020-01-01", periods=10)
398
+ element = index[len(index) // 2]
399
+ element = Timestamp(element).to_datetime64()
400
+
401
+ arr = np.array(index)
402
+ arr_result = comparison_op(arr, element)
403
+ index_result = comparison_op(index, element)
404
+
405
+ assert isinstance(index_result, np.ndarray)
406
+ tm.assert_numpy_array_equal(arr_result, index_result)
407
+
408
+ @pytest.mark.parametrize(
409
+ "other",
410
+ [datetime(2016, 1, 1), Timestamp("2016-01-01"), np.datetime64("2016-01-01")],
411
+ )
412
+ def test_dti_cmp_datetimelike(self, other, tz_naive_fixture):
413
+ tz = tz_naive_fixture
414
+ dti = date_range("2016-01-01", periods=2, tz=tz)
415
+ if tz is not None:
416
+ if isinstance(other, np.datetime64):
417
+ pytest.skip(f"{type(other).__name__} is not tz aware")
418
+ other = localize_pydatetime(other, dti.tzinfo)
419
+
420
+ result = dti == other
421
+ expected = np.array([True, False])
422
+ tm.assert_numpy_array_equal(result, expected)
423
+
424
+ result = dti > other
425
+ expected = np.array([False, True])
426
+ tm.assert_numpy_array_equal(result, expected)
427
+
428
+ result = dti >= other
429
+ expected = np.array([True, True])
430
+ tm.assert_numpy_array_equal(result, expected)
431
+
432
+ result = dti < other
433
+ expected = np.array([False, False])
434
+ tm.assert_numpy_array_equal(result, expected)
435
+
436
+ result = dti <= other
437
+ expected = np.array([True, False])
438
+ tm.assert_numpy_array_equal(result, expected)
439
+
440
+ @pytest.mark.parametrize("dtype", [None, object])
441
+ def test_dti_cmp_nat(self, dtype, box_with_array):
442
+ left = DatetimeIndex([Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")])
443
+ right = DatetimeIndex([NaT, NaT, Timestamp("2011-01-03")])
444
+
445
+ left = tm.box_expected(left, box_with_array)
446
+ right = tm.box_expected(right, box_with_array)
447
+ xbox = get_upcast_box(left, right, True)
448
+
449
+ lhs, rhs = left, right
450
+ if dtype is object:
451
+ lhs, rhs = left.astype(object), right.astype(object)
452
+
453
+ result = rhs == lhs
454
+ expected = np.array([False, False, True])
455
+ expected = tm.box_expected(expected, xbox)
456
+ tm.assert_equal(result, expected)
457
+
458
+ result = lhs != rhs
459
+ expected = np.array([True, True, False])
460
+ expected = tm.box_expected(expected, xbox)
461
+ tm.assert_equal(result, expected)
462
+
463
+ expected = np.array([False, False, False])
464
+ expected = tm.box_expected(expected, xbox)
465
+ tm.assert_equal(lhs == NaT, expected)
466
+ tm.assert_equal(NaT == rhs, expected)
467
+
468
+ expected = np.array([True, True, True])
469
+ expected = tm.box_expected(expected, xbox)
470
+ tm.assert_equal(lhs != NaT, expected)
471
+ tm.assert_equal(NaT != lhs, expected)
472
+
473
+ expected = np.array([False, False, False])
474
+ expected = tm.box_expected(expected, xbox)
475
+ tm.assert_equal(lhs < NaT, expected)
476
+ tm.assert_equal(NaT > lhs, expected)
477
+
478
+ def test_dti_cmp_nat_behaves_like_float_cmp_nan(self):
479
+ fidx1 = pd.Index([1.0, np.nan, 3.0, np.nan, 5.0, 7.0])
480
+ fidx2 = pd.Index([2.0, 3.0, np.nan, np.nan, 6.0, 7.0])
481
+
482
+ didx1 = DatetimeIndex(
483
+ ["2014-01-01", NaT, "2014-03-01", NaT, "2014-05-01", "2014-07-01"]
484
+ )
485
+ didx2 = DatetimeIndex(
486
+ ["2014-02-01", "2014-03-01", NaT, NaT, "2014-06-01", "2014-07-01"]
487
+ )
488
+ darr = np.array(
489
+ [
490
+ np.datetime64("2014-02-01 00:00"),
491
+ np.datetime64("2014-03-01 00:00"),
492
+ np.datetime64("nat"),
493
+ np.datetime64("nat"),
494
+ np.datetime64("2014-06-01 00:00"),
495
+ np.datetime64("2014-07-01 00:00"),
496
+ ]
497
+ )
498
+
499
+ cases = [(fidx1, fidx2), (didx1, didx2), (didx1, darr)]
500
+
501
+ # Check pd.NaT is handles as the same as np.nan
502
+ with tm.assert_produces_warning(None):
503
+ for idx1, idx2 in cases:
504
+ result = idx1 < idx2
505
+ expected = np.array([True, False, False, False, True, False])
506
+ tm.assert_numpy_array_equal(result, expected)
507
+
508
+ result = idx2 > idx1
509
+ expected = np.array([True, False, False, False, True, False])
510
+ tm.assert_numpy_array_equal(result, expected)
511
+
512
+ result = idx1 <= idx2
513
+ expected = np.array([True, False, False, False, True, True])
514
+ tm.assert_numpy_array_equal(result, expected)
515
+
516
+ result = idx2 >= idx1
517
+ expected = np.array([True, False, False, False, True, True])
518
+ tm.assert_numpy_array_equal(result, expected)
519
+
520
+ result = idx1 == idx2
521
+ expected = np.array([False, False, False, False, False, True])
522
+ tm.assert_numpy_array_equal(result, expected)
523
+
524
+ result = idx1 != idx2
525
+ expected = np.array([True, True, True, True, True, False])
526
+ tm.assert_numpy_array_equal(result, expected)
527
+
528
+ with tm.assert_produces_warning(None):
529
+ for idx1, val in [(fidx1, np.nan), (didx1, NaT)]:
530
+ result = idx1 < val
531
+ expected = np.array([False, False, False, False, False, False])
532
+ tm.assert_numpy_array_equal(result, expected)
533
+ result = idx1 > val
534
+ tm.assert_numpy_array_equal(result, expected)
535
+
536
+ result = idx1 <= val
537
+ tm.assert_numpy_array_equal(result, expected)
538
+ result = idx1 >= val
539
+ tm.assert_numpy_array_equal(result, expected)
540
+
541
+ result = idx1 == val
542
+ tm.assert_numpy_array_equal(result, expected)
543
+
544
+ result = idx1 != val
545
+ expected = np.array([True, True, True, True, True, True])
546
+ tm.assert_numpy_array_equal(result, expected)
547
+
548
+ # Check pd.NaT is handles as the same as np.nan
549
+ with tm.assert_produces_warning(None):
550
+ for idx1, val in [(fidx1, 3), (didx1, datetime(2014, 3, 1))]:
551
+ result = idx1 < val
552
+ expected = np.array([True, False, False, False, False, False])
553
+ tm.assert_numpy_array_equal(result, expected)
554
+ result = idx1 > val
555
+ expected = np.array([False, False, False, False, True, True])
556
+ tm.assert_numpy_array_equal(result, expected)
557
+
558
+ result = idx1 <= val
559
+ expected = np.array([True, False, True, False, False, False])
560
+ tm.assert_numpy_array_equal(result, expected)
561
+ result = idx1 >= val
562
+ expected = np.array([False, False, True, False, True, True])
563
+ tm.assert_numpy_array_equal(result, expected)
564
+
565
+ result = idx1 == val
566
+ expected = np.array([False, False, True, False, False, False])
567
+ tm.assert_numpy_array_equal(result, expected)
568
+
569
+ result = idx1 != val
570
+ expected = np.array([True, True, False, True, True, True])
571
+ tm.assert_numpy_array_equal(result, expected)
572
+
573
+ def test_comparison_tzawareness_compat(self, comparison_op, box_with_array):
574
+ # GH#18162
575
+ op = comparison_op
576
+ box = box_with_array
577
+
578
+ dr = date_range("2016-01-01", periods=6)
579
+ dz = dr.tz_localize("US/Pacific")
580
+
581
+ dr = tm.box_expected(dr, box)
582
+ dz = tm.box_expected(dz, box)
583
+
584
+ if box is pd.DataFrame:
585
+ tolist = lambda x: x.astype(object).values.tolist()[0]
586
+ else:
587
+ tolist = list
588
+
589
+ if op not in [operator.eq, operator.ne]:
590
+ msg = (
591
+ r"Invalid comparison between dtype=datetime64\[ns.*\] "
592
+ "and (Timestamp|DatetimeArray|list|ndarray)"
593
+ )
594
+ with pytest.raises(TypeError, match=msg):
595
+ op(dr, dz)
596
+
597
+ with pytest.raises(TypeError, match=msg):
598
+ op(dr, tolist(dz))
599
+ with pytest.raises(TypeError, match=msg):
600
+ op(dr, np.array(tolist(dz), dtype=object))
601
+ with pytest.raises(TypeError, match=msg):
602
+ op(dz, dr)
603
+
604
+ with pytest.raises(TypeError, match=msg):
605
+ op(dz, tolist(dr))
606
+ with pytest.raises(TypeError, match=msg):
607
+ op(dz, np.array(tolist(dr), dtype=object))
608
+
609
+ # The aware==aware and naive==naive comparisons should *not* raise
610
+ assert np.all(dr == dr)
611
+ assert np.all(dr == tolist(dr))
612
+ assert np.all(tolist(dr) == dr)
613
+ assert np.all(np.array(tolist(dr), dtype=object) == dr)
614
+ assert np.all(dr == np.array(tolist(dr), dtype=object))
615
+
616
+ assert np.all(dz == dz)
617
+ assert np.all(dz == tolist(dz))
618
+ assert np.all(tolist(dz) == dz)
619
+ assert np.all(np.array(tolist(dz), dtype=object) == dz)
620
+ assert np.all(dz == np.array(tolist(dz), dtype=object))
621
+
622
+ def test_comparison_tzawareness_compat_scalars(self, comparison_op, box_with_array):
623
+ # GH#18162
624
+ op = comparison_op
625
+
626
+ dr = date_range("2016-01-01", periods=6)
627
+ dz = dr.tz_localize("US/Pacific")
628
+
629
+ dr = tm.box_expected(dr, box_with_array)
630
+ dz = tm.box_expected(dz, box_with_array)
631
+
632
+ # Check comparisons against scalar Timestamps
633
+ ts = Timestamp("2000-03-14 01:59")
634
+ ts_tz = Timestamp("2000-03-14 01:59", tz="Europe/Amsterdam")
635
+
636
+ assert np.all(dr > ts)
637
+ msg = r"Invalid comparison between dtype=datetime64\[ns.*\] and Timestamp"
638
+ if op not in [operator.eq, operator.ne]:
639
+ with pytest.raises(TypeError, match=msg):
640
+ op(dr, ts_tz)
641
+
642
+ assert np.all(dz > ts_tz)
643
+ if op not in [operator.eq, operator.ne]:
644
+ with pytest.raises(TypeError, match=msg):
645
+ op(dz, ts)
646
+
647
+ if op not in [operator.eq, operator.ne]:
648
+ # GH#12601: Check comparison against Timestamps and DatetimeIndex
649
+ with pytest.raises(TypeError, match=msg):
650
+ op(ts, dz)
651
+
652
+ @pytest.mark.parametrize(
653
+ "other",
654
+ [datetime(2016, 1, 1), Timestamp("2016-01-01"), np.datetime64("2016-01-01")],
655
+ )
656
+ # Bug in NumPy? https://github.com/numpy/numpy/issues/13841
657
+ # Raising in __eq__ will fallback to NumPy, which warns, fails,
658
+ # then re-raises the original exception. So we just need to ignore.
659
+ @pytest.mark.filterwarnings("ignore:elementwise comp:DeprecationWarning")
660
+ def test_scalar_comparison_tzawareness(
661
+ self, comparison_op, other, tz_aware_fixture, box_with_array
662
+ ):
663
+ op = comparison_op
664
+ tz = tz_aware_fixture
665
+ dti = date_range("2016-01-01", periods=2, tz=tz)
666
+
667
+ dtarr = tm.box_expected(dti, box_with_array)
668
+ xbox = get_upcast_box(dtarr, other, True)
669
+ if op in [operator.eq, operator.ne]:
670
+ exbool = op is operator.ne
671
+ expected = np.array([exbool, exbool], dtype=bool)
672
+ expected = tm.box_expected(expected, xbox)
673
+
674
+ result = op(dtarr, other)
675
+ tm.assert_equal(result, expected)
676
+
677
+ result = op(other, dtarr)
678
+ tm.assert_equal(result, expected)
679
+ else:
680
+ msg = (
681
+ r"Invalid comparison between dtype=datetime64\[ns, .*\] "
682
+ f"and {type(other).__name__}"
683
+ )
684
+ with pytest.raises(TypeError, match=msg):
685
+ op(dtarr, other)
686
+ with pytest.raises(TypeError, match=msg):
687
+ op(other, dtarr)
688
+
689
+ def test_nat_comparison_tzawareness(self, comparison_op):
690
+ # GH#19276
691
+ # tzaware DatetimeIndex should not raise when compared to NaT
692
+ op = comparison_op
693
+
694
+ dti = DatetimeIndex(
695
+ ["2014-01-01", NaT, "2014-03-01", NaT, "2014-05-01", "2014-07-01"]
696
+ )
697
+ expected = np.array([op == operator.ne] * len(dti))
698
+ result = op(dti, NaT)
699
+ tm.assert_numpy_array_equal(result, expected)
700
+
701
+ result = op(dti.tz_localize("US/Pacific"), NaT)
702
+ tm.assert_numpy_array_equal(result, expected)
703
+
704
+ def test_dti_cmp_str(self, tz_naive_fixture):
705
+ # GH#22074
706
+ # regardless of tz, we expect these comparisons are valid
707
+ tz = tz_naive_fixture
708
+ rng = date_range("1/1/2000", periods=10, tz=tz)
709
+ other = "1/1/2000"
710
+
711
+ result = rng == other
712
+ expected = np.array([True] + [False] * 9)
713
+ tm.assert_numpy_array_equal(result, expected)
714
+
715
+ result = rng != other
716
+ expected = np.array([False] + [True] * 9)
717
+ tm.assert_numpy_array_equal(result, expected)
718
+
719
+ result = rng < other
720
+ expected = np.array([False] * 10)
721
+ tm.assert_numpy_array_equal(result, expected)
722
+
723
+ result = rng <= other
724
+ expected = np.array([True] + [False] * 9)
725
+ tm.assert_numpy_array_equal(result, expected)
726
+
727
+ result = rng > other
728
+ expected = np.array([False] + [True] * 9)
729
+ tm.assert_numpy_array_equal(result, expected)
730
+
731
+ result = rng >= other
732
+ expected = np.array([True] * 10)
733
+ tm.assert_numpy_array_equal(result, expected)
734
+
735
+ def test_dti_cmp_list(self):
736
+ rng = date_range("1/1/2000", periods=10)
737
+
738
+ result = rng == list(rng)
739
+ expected = rng == rng
740
+ tm.assert_numpy_array_equal(result, expected)
741
+
742
+ @pytest.mark.parametrize(
743
+ "other",
744
+ [
745
+ pd.timedelta_range("1D", periods=10),
746
+ pd.timedelta_range("1D", periods=10).to_series(),
747
+ pd.timedelta_range("1D", periods=10).asi8.view("m8[ns]"),
748
+ ],
749
+ ids=lambda x: type(x).__name__,
750
+ )
751
+ def test_dti_cmp_tdi_tzawareness(self, other):
752
+ # GH#22074
753
+ # reversion test that we _don't_ call _assert_tzawareness_compat
754
+ # when comparing against TimedeltaIndex
755
+ dti = date_range("2000-01-01", periods=10, tz="Asia/Tokyo")
756
+
757
+ result = dti == other
758
+ expected = np.array([False] * 10)
759
+ tm.assert_numpy_array_equal(result, expected)
760
+
761
+ result = dti != other
762
+ expected = np.array([True] * 10)
763
+ tm.assert_numpy_array_equal(result, expected)
764
+ msg = "Invalid comparison between"
765
+ with pytest.raises(TypeError, match=msg):
766
+ dti < other
767
+ with pytest.raises(TypeError, match=msg):
768
+ dti <= other
769
+ with pytest.raises(TypeError, match=msg):
770
+ dti > other
771
+ with pytest.raises(TypeError, match=msg):
772
+ dti >= other
773
+
774
+ def test_dti_cmp_object_dtype(self):
775
+ # GH#22074
776
+ dti = date_range("2000-01-01", periods=10, tz="Asia/Tokyo")
777
+
778
+ other = dti.astype("O")
779
+
780
+ result = dti == other
781
+ expected = np.array([True] * 10)
782
+ tm.assert_numpy_array_equal(result, expected)
783
+
784
+ other = dti.tz_localize(None)
785
+ result = dti != other
786
+ tm.assert_numpy_array_equal(result, expected)
787
+
788
+ other = np.array(list(dti[:5]) + [Timedelta(days=1)] * 5)
789
+ result = dti == other
790
+ expected = np.array([True] * 5 + [False] * 5)
791
+ tm.assert_numpy_array_equal(result, expected)
792
+ msg = ">=' not supported between instances of 'Timestamp' and 'Timedelta'"
793
+ with pytest.raises(TypeError, match=msg):
794
+ dti >= other
795
+
796
+
797
+ # ------------------------------------------------------------------
798
+ # Arithmetic
799
+
800
+
801
+ class TestDatetime64Arithmetic:
802
+ # This class is intended for "finished" tests that are fully parametrized
803
+ # over DataFrame/Series/Index/DatetimeArray
804
+
805
+ # -------------------------------------------------------------
806
+ # Addition/Subtraction of timedelta-like
807
+
808
+ @pytest.mark.arm_slow
809
+ def test_dt64arr_add_timedeltalike_scalar(
810
+ self, tz_naive_fixture, two_hours, box_with_array
811
+ ):
812
+ # GH#22005, GH#22163 check DataFrame doesn't raise TypeError
813
+ tz = tz_naive_fixture
814
+
815
+ rng = date_range("2000-01-01", "2000-02-01", tz=tz)
816
+ expected = date_range("2000-01-01 02:00", "2000-02-01 02:00", tz=tz)
817
+
818
+ rng = tm.box_expected(rng, box_with_array)
819
+ expected = tm.box_expected(expected, box_with_array)
820
+
821
+ result = rng + two_hours
822
+ tm.assert_equal(result, expected)
823
+
824
+ result = two_hours + rng
825
+ tm.assert_equal(result, expected)
826
+
827
+ rng += two_hours
828
+ tm.assert_equal(rng, expected)
829
+
830
+ def test_dt64arr_sub_timedeltalike_scalar(
831
+ self, tz_naive_fixture, two_hours, box_with_array
832
+ ):
833
+ tz = tz_naive_fixture
834
+
835
+ rng = date_range("2000-01-01", "2000-02-01", tz=tz)
836
+ expected = date_range("1999-12-31 22:00", "2000-01-31 22:00", tz=tz)
837
+
838
+ rng = tm.box_expected(rng, box_with_array)
839
+ expected = tm.box_expected(expected, box_with_array)
840
+
841
+ result = rng - two_hours
842
+ tm.assert_equal(result, expected)
843
+
844
+ rng -= two_hours
845
+ tm.assert_equal(rng, expected)
846
+
847
+ def test_dt64_array_sub_dt_with_different_timezone(self, box_with_array):
848
+ t1 = date_range("20130101", periods=3).tz_localize("US/Eastern")
849
+ t1 = tm.box_expected(t1, box_with_array)
850
+ t2 = Timestamp("20130101").tz_localize("CET")
851
+ tnaive = Timestamp(20130101)
852
+
853
+ result = t1 - t2
854
+ expected = TimedeltaIndex(
855
+ ["0 days 06:00:00", "1 days 06:00:00", "2 days 06:00:00"]
856
+ )
857
+ expected = tm.box_expected(expected, box_with_array)
858
+ tm.assert_equal(result, expected)
859
+
860
+ result = t2 - t1
861
+ expected = TimedeltaIndex(
862
+ ["-1 days +18:00:00", "-2 days +18:00:00", "-3 days +18:00:00"]
863
+ )
864
+ expected = tm.box_expected(expected, box_with_array)
865
+ tm.assert_equal(result, expected)
866
+
867
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
868
+ with pytest.raises(TypeError, match=msg):
869
+ t1 - tnaive
870
+
871
+ with pytest.raises(TypeError, match=msg):
872
+ tnaive - t1
873
+
874
+ def test_dt64_array_sub_dt64_array_with_different_timezone(self, box_with_array):
875
+ t1 = date_range("20130101", periods=3).tz_localize("US/Eastern")
876
+ t1 = tm.box_expected(t1, box_with_array)
877
+ t2 = date_range("20130101", periods=3).tz_localize("CET")
878
+ t2 = tm.box_expected(t2, box_with_array)
879
+ tnaive = date_range("20130101", periods=3)
880
+
881
+ result = t1 - t2
882
+ expected = TimedeltaIndex(
883
+ ["0 days 06:00:00", "0 days 06:00:00", "0 days 06:00:00"]
884
+ )
885
+ expected = tm.box_expected(expected, box_with_array)
886
+ tm.assert_equal(result, expected)
887
+
888
+ result = t2 - t1
889
+ expected = TimedeltaIndex(
890
+ ["-1 days +18:00:00", "-1 days +18:00:00", "-1 days +18:00:00"]
891
+ )
892
+ expected = tm.box_expected(expected, box_with_array)
893
+ tm.assert_equal(result, expected)
894
+
895
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
896
+ with pytest.raises(TypeError, match=msg):
897
+ t1 - tnaive
898
+
899
+ with pytest.raises(TypeError, match=msg):
900
+ tnaive - t1
901
+
902
+ def test_dt64arr_add_sub_td64_nat(self, box_with_array, tz_naive_fixture):
903
+ # GH#23320 special handling for timedelta64("NaT")
904
+ tz = tz_naive_fixture
905
+
906
+ dti = date_range("1994-04-01", periods=9, tz=tz, freq="QS")
907
+ other = np.timedelta64("NaT")
908
+ expected = DatetimeIndex(["NaT"] * 9, tz=tz).as_unit("ns")
909
+
910
+ obj = tm.box_expected(dti, box_with_array)
911
+ expected = tm.box_expected(expected, box_with_array)
912
+
913
+ result = obj + other
914
+ tm.assert_equal(result, expected)
915
+ result = other + obj
916
+ tm.assert_equal(result, expected)
917
+ result = obj - other
918
+ tm.assert_equal(result, expected)
919
+ msg = "cannot subtract"
920
+ with pytest.raises(TypeError, match=msg):
921
+ other - obj
922
+
923
+ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array):
924
+ tz = tz_naive_fixture
925
+ dti = date_range("2016-01-01", periods=3, tz=tz)
926
+ tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
927
+ tdarr = tdi.values
928
+
929
+ expected = date_range("2015-12-31", "2016-01-02", periods=3, tz=tz)
930
+
931
+ dtarr = tm.box_expected(dti, box_with_array)
932
+ expected = tm.box_expected(expected, box_with_array)
933
+
934
+ result = dtarr + tdarr
935
+ tm.assert_equal(result, expected)
936
+ result = tdarr + dtarr
937
+ tm.assert_equal(result, expected)
938
+
939
+ expected = date_range("2016-01-02", "2016-01-04", periods=3, tz=tz)
940
+ expected = tm.box_expected(expected, box_with_array)
941
+
942
+ result = dtarr - tdarr
943
+ tm.assert_equal(result, expected)
944
+ msg = "cannot subtract|(bad|unsupported) operand type for unary"
945
+ with pytest.raises(TypeError, match=msg):
946
+ tdarr - dtarr
947
+
948
+ # -----------------------------------------------------------------
949
+ # Subtraction of datetime-like scalars
950
+
951
+ @pytest.mark.parametrize(
952
+ "ts",
953
+ [
954
+ Timestamp("2013-01-01"),
955
+ Timestamp("2013-01-01").to_pydatetime(),
956
+ Timestamp("2013-01-01").to_datetime64(),
957
+ # GH#7996, GH#22163 ensure non-nano datetime64 is converted to nano
958
+ # for DataFrame operation
959
+ np.datetime64("2013-01-01", "D"),
960
+ ],
961
+ )
962
+ def test_dt64arr_sub_dtscalar(self, box_with_array, ts):
963
+ # GH#8554, GH#22163 DataFrame op should _not_ return dt64 dtype
964
+ idx = date_range("2013-01-01", periods=3)._with_freq(None)
965
+ idx = tm.box_expected(idx, box_with_array)
966
+
967
+ expected = TimedeltaIndex(["0 Days", "1 Day", "2 Days"])
968
+ expected = tm.box_expected(expected, box_with_array)
969
+
970
+ result = idx - ts
971
+ tm.assert_equal(result, expected)
972
+
973
+ result = ts - idx
974
+ tm.assert_equal(result, -expected)
975
+ tm.assert_equal(result, -expected)
976
+
977
+ def test_dt64arr_sub_timestamp_tzaware(self, box_with_array):
978
+ ser = date_range("2014-03-17", periods=2, freq="D", tz="US/Eastern")
979
+ ser = ser._with_freq(None)
980
+ ts = ser[0]
981
+
982
+ ser = tm.box_expected(ser, box_with_array)
983
+
984
+ delta_series = Series([np.timedelta64(0, "D"), np.timedelta64(1, "D")])
985
+ expected = tm.box_expected(delta_series, box_with_array)
986
+
987
+ tm.assert_equal(ser - ts, expected)
988
+ tm.assert_equal(ts - ser, -expected)
989
+
990
+ def test_dt64arr_sub_NaT(self, box_with_array, unit):
991
+ # GH#18808
992
+ dti = DatetimeIndex([NaT, Timestamp("19900315")]).as_unit(unit)
993
+ ser = tm.box_expected(dti, box_with_array)
994
+
995
+ result = ser - NaT
996
+ expected = Series([NaT, NaT], dtype=f"timedelta64[{unit}]")
997
+ expected = tm.box_expected(expected, box_with_array)
998
+ tm.assert_equal(result, expected)
999
+
1000
+ dti_tz = dti.tz_localize("Asia/Tokyo")
1001
+ ser_tz = tm.box_expected(dti_tz, box_with_array)
1002
+
1003
+ result = ser_tz - NaT
1004
+ expected = Series([NaT, NaT], dtype=f"timedelta64[{unit}]")
1005
+ expected = tm.box_expected(expected, box_with_array)
1006
+ tm.assert_equal(result, expected)
1007
+
1008
+ # -------------------------------------------------------------
1009
+ # Subtraction of datetime-like array-like
1010
+
1011
+ def test_dt64arr_sub_dt64object_array(self, box_with_array, tz_naive_fixture):
1012
+ dti = date_range("2016-01-01", periods=3, tz=tz_naive_fixture)
1013
+ expected = dti - dti
1014
+
1015
+ obj = tm.box_expected(dti, box_with_array)
1016
+ expected = tm.box_expected(expected, box_with_array).astype(object)
1017
+
1018
+ with tm.assert_produces_warning(PerformanceWarning):
1019
+ result = obj - obj.astype(object)
1020
+ tm.assert_equal(result, expected)
1021
+
1022
+ def test_dt64arr_naive_sub_dt64ndarray(self, box_with_array):
1023
+ dti = date_range("2016-01-01", periods=3, tz=None)
1024
+ dt64vals = dti.values
1025
+
1026
+ dtarr = tm.box_expected(dti, box_with_array)
1027
+
1028
+ expected = dtarr - dtarr
1029
+ result = dtarr - dt64vals
1030
+ tm.assert_equal(result, expected)
1031
+ result = dt64vals - dtarr
1032
+ tm.assert_equal(result, expected)
1033
+
1034
+ def test_dt64arr_aware_sub_dt64ndarray_raises(
1035
+ self, tz_aware_fixture, box_with_array
1036
+ ):
1037
+ tz = tz_aware_fixture
1038
+ dti = date_range("2016-01-01", periods=3, tz=tz)
1039
+ dt64vals = dti.values
1040
+
1041
+ dtarr = tm.box_expected(dti, box_with_array)
1042
+ msg = "Cannot subtract tz-naive and tz-aware datetime"
1043
+ with pytest.raises(TypeError, match=msg):
1044
+ dtarr - dt64vals
1045
+ with pytest.raises(TypeError, match=msg):
1046
+ dt64vals - dtarr
1047
+
1048
+ # -------------------------------------------------------------
1049
+ # Addition of datetime-like others (invalid)
1050
+
1051
+ def test_dt64arr_add_dtlike_raises(self, tz_naive_fixture, box_with_array):
1052
+ # GH#22163 ensure DataFrame doesn't cast Timestamp to i8
1053
+ # GH#9631
1054
+ tz = tz_naive_fixture
1055
+
1056
+ dti = date_range("2016-01-01", periods=3, tz=tz)
1057
+ if tz is None:
1058
+ dti2 = dti.tz_localize("US/Eastern")
1059
+ else:
1060
+ dti2 = dti.tz_localize(None)
1061
+ dtarr = tm.box_expected(dti, box_with_array)
1062
+
1063
+ assert_cannot_add(dtarr, dti.values)
1064
+ assert_cannot_add(dtarr, dti)
1065
+ assert_cannot_add(dtarr, dtarr)
1066
+ assert_cannot_add(dtarr, dti[0])
1067
+ assert_cannot_add(dtarr, dti[0].to_pydatetime())
1068
+ assert_cannot_add(dtarr, dti[0].to_datetime64())
1069
+ assert_cannot_add(dtarr, dti2[0])
1070
+ assert_cannot_add(dtarr, dti2[0].to_pydatetime())
1071
+ assert_cannot_add(dtarr, np.datetime64("2011-01-01", "D"))
1072
+
1073
+ # -------------------------------------------------------------
1074
+ # Other Invalid Addition/Subtraction
1075
+
1076
+ # Note: freq here includes both Tick and non-Tick offsets; this is
1077
+ # relevant because historically integer-addition was allowed if we had
1078
+ # a freq.
1079
+ @pytest.mark.parametrize("freq", ["h", "D", "W", "2ME", "MS", "QE", "B", None])
1080
+ @pytest.mark.parametrize("dtype", [None, "uint8"])
1081
+ def test_dt64arr_addsub_intlike(
1082
+ self, request, dtype, index_or_series_or_array, freq, tz_naive_fixture
1083
+ ):
1084
+ # GH#19959, GH#19123, GH#19012
1085
+ # GH#55860 use index_or_series_or_array instead of box_with_array
1086
+ # bc DataFrame alignment makes it inapplicable
1087
+ tz = tz_naive_fixture
1088
+
1089
+ if freq is None:
1090
+ dti = DatetimeIndex(["NaT", "2017-04-05 06:07:08"], tz=tz)
1091
+ else:
1092
+ dti = date_range("2016-01-01", periods=2, freq=freq, tz=tz)
1093
+
1094
+ obj = index_or_series_or_array(dti)
1095
+ other = np.array([4, -1])
1096
+ if dtype is not None:
1097
+ other = other.astype(dtype)
1098
+
1099
+ msg = "|".join(
1100
+ [
1101
+ "Addition/subtraction of integers",
1102
+ "cannot subtract DatetimeArray from",
1103
+ # IntegerArray
1104
+ "can only perform ops with numeric values",
1105
+ "unsupported operand type.*Categorical",
1106
+ r"unsupported operand type\(s\) for -: 'int' and 'Timestamp'",
1107
+ ]
1108
+ )
1109
+ assert_invalid_addsub_type(obj, 1, msg)
1110
+ assert_invalid_addsub_type(obj, np.int64(2), msg)
1111
+ assert_invalid_addsub_type(obj, np.array(3, dtype=np.int64), msg)
1112
+ assert_invalid_addsub_type(obj, other, msg)
1113
+ assert_invalid_addsub_type(obj, np.array(other), msg)
1114
+ assert_invalid_addsub_type(obj, pd.array(other), msg)
1115
+ assert_invalid_addsub_type(obj, pd.Categorical(other), msg)
1116
+ assert_invalid_addsub_type(obj, pd.Index(other), msg)
1117
+ assert_invalid_addsub_type(obj, Series(other), msg)
1118
+
1119
+ @pytest.mark.parametrize(
1120
+ "other",
1121
+ [
1122
+ 3.14,
1123
+ np.array([2.0, 3.0]),
1124
+ # GH#13078 datetime +/- Period is invalid
1125
+ Period("2011-01-01", freq="D"),
1126
+ # https://github.com/pandas-dev/pandas/issues/10329
1127
+ time(1, 2, 3),
1128
+ ],
1129
+ )
1130
+ @pytest.mark.parametrize("dti_freq", [None, "D"])
1131
+ def test_dt64arr_add_sub_invalid(self, dti_freq, other, box_with_array):
1132
+ dti = DatetimeIndex(["2011-01-01", "2011-01-02"], freq=dti_freq)
1133
+ dtarr = tm.box_expected(dti, box_with_array)
1134
+ msg = "|".join(
1135
+ [
1136
+ "unsupported operand type",
1137
+ "cannot (add|subtract)",
1138
+ "cannot use operands with types",
1139
+ "ufunc '?(add|subtract)'? cannot use operands with types",
1140
+ "Concatenation operation is not implemented for NumPy arrays",
1141
+ ]
1142
+ )
1143
+ assert_invalid_addsub_type(dtarr, other, msg)
1144
+
1145
+ @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "h"])
1146
+ @pytest.mark.parametrize("dti_freq", [None, "D"])
1147
+ def test_dt64arr_add_sub_parr(
1148
+ self, dti_freq, pi_freq, box_with_array, box_with_array2
1149
+ ):
1150
+ # GH#20049 subtracting PeriodIndex should raise TypeError
1151
+ dti = DatetimeIndex(["2011-01-01", "2011-01-02"], freq=dti_freq)
1152
+ pi = dti.to_period(pi_freq)
1153
+
1154
+ dtarr = tm.box_expected(dti, box_with_array)
1155
+ parr = tm.box_expected(pi, box_with_array2)
1156
+ msg = "|".join(
1157
+ [
1158
+ "cannot (add|subtract)",
1159
+ "unsupported operand",
1160
+ "descriptor.*requires",
1161
+ "ufunc.*cannot use operands",
1162
+ ]
1163
+ )
1164
+ assert_invalid_addsub_type(dtarr, parr, msg)
1165
+
1166
+ @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")
1167
+ def test_dt64arr_addsub_time_objects_raises(self, box_with_array, tz_naive_fixture):
1168
+ # https://github.com/pandas-dev/pandas/issues/10329
1169
+
1170
+ tz = tz_naive_fixture
1171
+
1172
+ obj1 = date_range("2012-01-01", periods=3, tz=tz)
1173
+ obj2 = [time(i, i, i) for i in range(3)]
1174
+
1175
+ obj1 = tm.box_expected(obj1, box_with_array)
1176
+ obj2 = tm.box_expected(obj2, box_with_array)
1177
+
1178
+ msg = "|".join(
1179
+ [
1180
+ "unsupported operand",
1181
+ "cannot subtract DatetimeArray from ndarray",
1182
+ ]
1183
+ )
1184
+ # pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
1185
+ # applied to Series or DatetimeIndex
1186
+ # we aren't testing that here, so ignore.
1187
+ assert_invalid_addsub_type(obj1, obj2, msg=msg)
1188
+
1189
+ # -------------------------------------------------------------
1190
+ # Other invalid operations
1191
+
1192
+ @pytest.mark.parametrize(
1193
+ "dt64_series",
1194
+ [
1195
+ Series([Timestamp("19900315"), Timestamp("19900315")]),
1196
+ Series([NaT, Timestamp("19900315")]),
1197
+ Series([NaT, NaT], dtype="datetime64[ns]"),
1198
+ ],
1199
+ )
1200
+ @pytest.mark.parametrize("one", [1, 1.0, np.array(1)])
1201
+ def test_dt64_mul_div_numeric_invalid(self, one, dt64_series, box_with_array):
1202
+ obj = tm.box_expected(dt64_series, box_with_array)
1203
+
1204
+ msg = "cannot perform .* with this index type"
1205
+
1206
+ # multiplication
1207
+ with pytest.raises(TypeError, match=msg):
1208
+ obj * one
1209
+ with pytest.raises(TypeError, match=msg):
1210
+ one * obj
1211
+
1212
+ # division
1213
+ with pytest.raises(TypeError, match=msg):
1214
+ obj / one
1215
+ with pytest.raises(TypeError, match=msg):
1216
+ one / obj
1217
+
1218
+
1219
+ class TestDatetime64DateOffsetArithmetic:
1220
+ # -------------------------------------------------------------
1221
+ # Tick DateOffsets
1222
+
1223
+ # TODO: parametrize over timezone?
1224
+ @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
1225
+ def test_dt64arr_series_add_tick_DateOffset(self, box_with_array, unit):
1226
+ # GH#4532
1227
+ # operate with pd.offsets
1228
+ ser = Series(
1229
+ [Timestamp("20130101 9:01"), Timestamp("20130101 9:02")]
1230
+ ).dt.as_unit(unit)
1231
+ expected = Series(
1232
+ [Timestamp("20130101 9:01:05"), Timestamp("20130101 9:02:05")]
1233
+ ).dt.as_unit(unit)
1234
+
1235
+ ser = tm.box_expected(ser, box_with_array)
1236
+ expected = tm.box_expected(expected, box_with_array)
1237
+
1238
+ result = ser + pd.offsets.Second(5)
1239
+ tm.assert_equal(result, expected)
1240
+
1241
+ result2 = pd.offsets.Second(5) + ser
1242
+ tm.assert_equal(result2, expected)
1243
+
1244
+ def test_dt64arr_series_sub_tick_DateOffset(self, box_with_array):
1245
+ # GH#4532
1246
+ # operate with pd.offsets
1247
+ ser = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")])
1248
+ expected = Series(
1249
+ [Timestamp("20130101 9:00:55"), Timestamp("20130101 9:01:55")]
1250
+ )
1251
+
1252
+ ser = tm.box_expected(ser, box_with_array)
1253
+ expected = tm.box_expected(expected, box_with_array)
1254
+
1255
+ result = ser - pd.offsets.Second(5)
1256
+ tm.assert_equal(result, expected)
1257
+
1258
+ result2 = -pd.offsets.Second(5) + ser
1259
+ tm.assert_equal(result2, expected)
1260
+ msg = "(bad|unsupported) operand type for unary"
1261
+ with pytest.raises(TypeError, match=msg):
1262
+ pd.offsets.Second(5) - ser
1263
+
1264
+ @pytest.mark.parametrize(
1265
+ "cls_name", ["Day", "Hour", "Minute", "Second", "Milli", "Micro", "Nano"]
1266
+ )
1267
+ def test_dt64arr_add_sub_tick_DateOffset_smoke(self, cls_name, box_with_array):
1268
+ # GH#4532
1269
+ # smoke tests for valid DateOffsets
1270
+ ser = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")])
1271
+ ser = tm.box_expected(ser, box_with_array)
1272
+
1273
+ offset_cls = getattr(pd.offsets, cls_name)
1274
+ ser + offset_cls(5)
1275
+ offset_cls(5) + ser
1276
+ ser - offset_cls(5)
1277
+
1278
+ def test_dti_add_tick_tzaware(self, tz_aware_fixture, box_with_array):
1279
+ # GH#21610, GH#22163 ensure DataFrame doesn't return object-dtype
1280
+ tz = tz_aware_fixture
1281
+ if tz == "US/Pacific":
1282
+ dates = date_range("2012-11-01", periods=3, tz=tz)
1283
+ offset = dates + pd.offsets.Hour(5)
1284
+ assert dates[0] + pd.offsets.Hour(5) == offset[0]
1285
+
1286
+ dates = date_range("2010-11-01 00:00", periods=3, tz=tz, freq="h")
1287
+ expected = DatetimeIndex(
1288
+ ["2010-11-01 05:00", "2010-11-01 06:00", "2010-11-01 07:00"],
1289
+ freq="h",
1290
+ tz=tz,
1291
+ ).as_unit("ns")
1292
+
1293
+ dates = tm.box_expected(dates, box_with_array)
1294
+ expected = tm.box_expected(expected, box_with_array)
1295
+
1296
+ for scalar in [pd.offsets.Hour(5), np.timedelta64(5, "h"), timedelta(hours=5)]:
1297
+ offset = dates + scalar
1298
+ tm.assert_equal(offset, expected)
1299
+ offset = scalar + dates
1300
+ tm.assert_equal(offset, expected)
1301
+
1302
+ roundtrip = offset - scalar
1303
+ tm.assert_equal(roundtrip, dates)
1304
+
1305
+ msg = "|".join(
1306
+ ["bad operand type for unary -", "cannot subtract DatetimeArray"]
1307
+ )
1308
+ with pytest.raises(TypeError, match=msg):
1309
+ scalar - dates
1310
+
1311
+ # -------------------------------------------------------------
1312
+ # RelativeDelta DateOffsets
1313
+
1314
+ @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
1315
+ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array, unit):
1316
+ # GH#10699
1317
+ vec = DatetimeIndex(
1318
+ [
1319
+ Timestamp("2000-01-05 00:15:00"),
1320
+ Timestamp("2000-01-31 00:23:00"),
1321
+ Timestamp("2000-01-01"),
1322
+ Timestamp("2000-03-31"),
1323
+ Timestamp("2000-02-29"),
1324
+ Timestamp("2000-12-31"),
1325
+ Timestamp("2000-05-15"),
1326
+ Timestamp("2001-06-15"),
1327
+ ]
1328
+ ).as_unit(unit)
1329
+ vec = tm.box_expected(vec, box_with_array)
1330
+ vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec
1331
+
1332
+ # DateOffset relativedelta fastpath
1333
+ relative_kwargs = [
1334
+ ("years", 2),
1335
+ ("months", 5),
1336
+ ("days", 3),
1337
+ ("hours", 5),
1338
+ ("minutes", 10),
1339
+ ("seconds", 2),
1340
+ ("microseconds", 5),
1341
+ ]
1342
+ for i, (offset_unit, value) in enumerate(relative_kwargs):
1343
+ off = DateOffset(**{offset_unit: value})
1344
+
1345
+ exp_unit = unit
1346
+ if offset_unit == "microseconds" and unit != "ns":
1347
+ exp_unit = "us"
1348
+
1349
+ # TODO(GH#55564): as_unit will be unnecessary
1350
+ expected = DatetimeIndex([x + off for x in vec_items]).as_unit(exp_unit)
1351
+ expected = tm.box_expected(expected, box_with_array)
1352
+ tm.assert_equal(expected, vec + off)
1353
+
1354
+ expected = DatetimeIndex([x - off for x in vec_items]).as_unit(exp_unit)
1355
+ expected = tm.box_expected(expected, box_with_array)
1356
+ tm.assert_equal(expected, vec - off)
1357
+
1358
+ off = DateOffset(**dict(relative_kwargs[: i + 1]))
1359
+
1360
+ expected = DatetimeIndex([x + off for x in vec_items]).as_unit(exp_unit)
1361
+ expected = tm.box_expected(expected, box_with_array)
1362
+ tm.assert_equal(expected, vec + off)
1363
+
1364
+ expected = DatetimeIndex([x - off for x in vec_items]).as_unit(exp_unit)
1365
+ expected = tm.box_expected(expected, box_with_array)
1366
+ tm.assert_equal(expected, vec - off)
1367
+ msg = "(bad|unsupported) operand type for unary"
1368
+ with pytest.raises(TypeError, match=msg):
1369
+ off - vec
1370
+
1371
+ # -------------------------------------------------------------
1372
+ # Non-Tick, Non-RelativeDelta DateOffsets
1373
+
1374
+ # TODO: redundant with test_dt64arr_add_sub_DateOffset? that includes
1375
+ # tz-aware cases which this does not
1376
+ @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")
1377
+ @pytest.mark.parametrize(
1378
+ "cls_and_kwargs",
1379
+ [
1380
+ "YearBegin",
1381
+ ("YearBegin", {"month": 5}),
1382
+ "YearEnd",
1383
+ ("YearEnd", {"month": 5}),
1384
+ "MonthBegin",
1385
+ "MonthEnd",
1386
+ "SemiMonthEnd",
1387
+ "SemiMonthBegin",
1388
+ "Week",
1389
+ ("Week", {"weekday": 3}),
1390
+ "Week",
1391
+ ("Week", {"weekday": 6}),
1392
+ "BusinessDay",
1393
+ "BDay",
1394
+ "QuarterEnd",
1395
+ "QuarterBegin",
1396
+ "CustomBusinessDay",
1397
+ "CDay",
1398
+ "CBMonthEnd",
1399
+ "CBMonthBegin",
1400
+ "BMonthBegin",
1401
+ "BMonthEnd",
1402
+ "BusinessHour",
1403
+ "BYearBegin",
1404
+ "BYearEnd",
1405
+ "BQuarterBegin",
1406
+ ("LastWeekOfMonth", {"weekday": 2}),
1407
+ (
1408
+ "FY5253Quarter",
1409
+ {
1410
+ "qtr_with_extra_week": 1,
1411
+ "startingMonth": 1,
1412
+ "weekday": 2,
1413
+ "variation": "nearest",
1414
+ },
1415
+ ),
1416
+ ("FY5253", {"weekday": 0, "startingMonth": 2, "variation": "nearest"}),
1417
+ ("WeekOfMonth", {"weekday": 2, "week": 2}),
1418
+ "Easter",
1419
+ ("DateOffset", {"day": 4}),
1420
+ ("DateOffset", {"month": 5}),
1421
+ ],
1422
+ )
1423
+ @pytest.mark.parametrize("normalize", [True, False])
1424
+ @pytest.mark.parametrize("n", [0, 5])
1425
+ @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
1426
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
1427
+ def test_dt64arr_add_sub_DateOffsets(
1428
+ self, box_with_array, n, normalize, cls_and_kwargs, unit, tz
1429
+ ):
1430
+ # GH#10699
1431
+ # assert vectorized operation matches pointwise operations
1432
+
1433
+ if isinstance(cls_and_kwargs, tuple):
1434
+ # If cls_name param is a tuple, then 2nd entry is kwargs for
1435
+ # the offset constructor
1436
+ cls_name, kwargs = cls_and_kwargs
1437
+ else:
1438
+ cls_name = cls_and_kwargs
1439
+ kwargs = {}
1440
+
1441
+ if n == 0 and cls_name in [
1442
+ "WeekOfMonth",
1443
+ "LastWeekOfMonth",
1444
+ "FY5253Quarter",
1445
+ "FY5253",
1446
+ ]:
1447
+ # passing n = 0 is invalid for these offset classes
1448
+ return
1449
+
1450
+ vec = (
1451
+ DatetimeIndex(
1452
+ [
1453
+ Timestamp("2000-01-05 00:15:00"),
1454
+ Timestamp("2000-01-31 00:23:00"),
1455
+ Timestamp("2000-01-01"),
1456
+ Timestamp("2000-03-31"),
1457
+ Timestamp("2000-02-29"),
1458
+ Timestamp("2000-12-31"),
1459
+ Timestamp("2000-05-15"),
1460
+ Timestamp("2001-06-15"),
1461
+ ]
1462
+ )
1463
+ .as_unit(unit)
1464
+ .tz_localize(tz)
1465
+ )
1466
+ vec = tm.box_expected(vec, box_with_array)
1467
+ vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec
1468
+
1469
+ offset_cls = getattr(pd.offsets, cls_name)
1470
+ offset = offset_cls(n, normalize=normalize, **kwargs)
1471
+
1472
+ # TODO(GH#55564): as_unit will be unnecessary
1473
+ expected = DatetimeIndex([x + offset for x in vec_items]).as_unit(unit)
1474
+ expected = tm.box_expected(expected, box_with_array)
1475
+ tm.assert_equal(expected, vec + offset)
1476
+ tm.assert_equal(expected, offset + vec)
1477
+
1478
+ expected = DatetimeIndex([x - offset for x in vec_items]).as_unit(unit)
1479
+ expected = tm.box_expected(expected, box_with_array)
1480
+ tm.assert_equal(expected, vec - offset)
1481
+
1482
+ expected = DatetimeIndex([offset + x for x in vec_items]).as_unit(unit)
1483
+ expected = tm.box_expected(expected, box_with_array)
1484
+ tm.assert_equal(expected, offset + vec)
1485
+ msg = "(bad|unsupported) operand type for unary"
1486
+ with pytest.raises(TypeError, match=msg):
1487
+ offset - vec
1488
+
1489
+ @pytest.mark.parametrize(
1490
+ "other",
1491
+ [
1492
+ np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]),
1493
+ np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()]),
1494
+ np.array( # matching offsets
1495
+ [pd.offsets.DateOffset(years=1), pd.offsets.DateOffset(years=1)]
1496
+ ),
1497
+ ],
1498
+ )
1499
+ @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub])
1500
+ def test_dt64arr_add_sub_offset_array(
1501
+ self, tz_naive_fixture, box_with_array, op, other
1502
+ ):
1503
+ # GH#18849
1504
+ # GH#10699 array of offsets
1505
+
1506
+ tz = tz_naive_fixture
1507
+ dti = date_range("2017-01-01", periods=2, tz=tz)
1508
+ dtarr = tm.box_expected(dti, box_with_array)
1509
+
1510
+ expected = DatetimeIndex([op(dti[n], other[n]) for n in range(len(dti))])
1511
+ expected = tm.box_expected(expected, box_with_array).astype(object)
1512
+
1513
+ with tm.assert_produces_warning(PerformanceWarning):
1514
+ res = op(dtarr, other)
1515
+ tm.assert_equal(res, expected)
1516
+
1517
+ # Same thing but boxing other
1518
+ other = tm.box_expected(other, box_with_array)
1519
+ if box_with_array is pd.array and op is roperator.radd:
1520
+ # We expect a NumpyExtensionArray, not ndarray[object] here
1521
+ expected = pd.array(expected, dtype=object)
1522
+ with tm.assert_produces_warning(PerformanceWarning):
1523
+ res = op(dtarr, other)
1524
+ tm.assert_equal(res, expected)
1525
+
1526
+ @pytest.mark.parametrize(
1527
+ "op, offset, exp, exp_freq",
1528
+ [
1529
+ (
1530
+ "__add__",
1531
+ DateOffset(months=3, days=10),
1532
+ [
1533
+ Timestamp("2014-04-11"),
1534
+ Timestamp("2015-04-11"),
1535
+ Timestamp("2016-04-11"),
1536
+ Timestamp("2017-04-11"),
1537
+ ],
1538
+ None,
1539
+ ),
1540
+ (
1541
+ "__add__",
1542
+ DateOffset(months=3),
1543
+ [
1544
+ Timestamp("2014-04-01"),
1545
+ Timestamp("2015-04-01"),
1546
+ Timestamp("2016-04-01"),
1547
+ Timestamp("2017-04-01"),
1548
+ ],
1549
+ "YS-APR",
1550
+ ),
1551
+ (
1552
+ "__sub__",
1553
+ DateOffset(months=3, days=10),
1554
+ [
1555
+ Timestamp("2013-09-21"),
1556
+ Timestamp("2014-09-21"),
1557
+ Timestamp("2015-09-21"),
1558
+ Timestamp("2016-09-21"),
1559
+ ],
1560
+ None,
1561
+ ),
1562
+ (
1563
+ "__sub__",
1564
+ DateOffset(months=3),
1565
+ [
1566
+ Timestamp("2013-10-01"),
1567
+ Timestamp("2014-10-01"),
1568
+ Timestamp("2015-10-01"),
1569
+ Timestamp("2016-10-01"),
1570
+ ],
1571
+ "YS-OCT",
1572
+ ),
1573
+ ],
1574
+ )
1575
+ def test_dti_add_sub_nonzero_mth_offset(
1576
+ self, op, offset, exp, exp_freq, tz_aware_fixture, box_with_array
1577
+ ):
1578
+ # GH 26258
1579
+ tz = tz_aware_fixture
1580
+ date = date_range(start="01 Jan 2014", end="01 Jan 2017", freq="YS", tz=tz)
1581
+ date = tm.box_expected(date, box_with_array, False)
1582
+ mth = getattr(date, op)
1583
+ result = mth(offset)
1584
+
1585
+ expected = DatetimeIndex(exp, tz=tz).as_unit("ns")
1586
+ expected = tm.box_expected(expected, box_with_array, False)
1587
+ tm.assert_equal(result, expected)
1588
+
1589
+ def test_dt64arr_series_add_DateOffset_with_milli(self):
1590
+ # GH 57529
1591
+ dti = DatetimeIndex(
1592
+ [
1593
+ "2000-01-01 00:00:00.012345678",
1594
+ "2000-01-31 00:00:00.012345678",
1595
+ "2000-02-29 00:00:00.012345678",
1596
+ ],
1597
+ dtype="datetime64[ns]",
1598
+ )
1599
+ result = dti + DateOffset(milliseconds=4)
1600
+ expected = DatetimeIndex(
1601
+ [
1602
+ "2000-01-01 00:00:00.016345678",
1603
+ "2000-01-31 00:00:00.016345678",
1604
+ "2000-02-29 00:00:00.016345678",
1605
+ ],
1606
+ dtype="datetime64[ns]",
1607
+ )
1608
+ tm.assert_index_equal(result, expected)
1609
+
1610
+ result = dti + DateOffset(days=1, milliseconds=4)
1611
+ expected = DatetimeIndex(
1612
+ [
1613
+ "2000-01-02 00:00:00.016345678",
1614
+ "2000-02-01 00:00:00.016345678",
1615
+ "2000-03-01 00:00:00.016345678",
1616
+ ],
1617
+ dtype="datetime64[ns]",
1618
+ )
1619
+ tm.assert_index_equal(result, expected)
1620
+
1621
+
1622
+ class TestDatetime64OverflowHandling:
1623
+ # TODO: box + de-duplicate
1624
+
1625
+ def test_dt64_overflow_masking(self, box_with_array):
1626
+ # GH#25317
1627
+ left = Series([Timestamp("1969-12-31")], dtype="M8[ns]")
1628
+ right = Series([NaT])
1629
+
1630
+ left = tm.box_expected(left, box_with_array)
1631
+ right = tm.box_expected(right, box_with_array)
1632
+
1633
+ expected = TimedeltaIndex([NaT], dtype="m8[ns]")
1634
+ expected = tm.box_expected(expected, box_with_array)
1635
+
1636
+ result = left - right
1637
+ tm.assert_equal(result, expected)
1638
+
1639
+ def test_dt64_series_arith_overflow(self):
1640
+ # GH#12534, fixed by GH#19024
1641
+ dt = Timestamp("1700-01-31")
1642
+ td = Timedelta("20000 Days")
1643
+ dti = date_range("1949-09-30", freq="100YE", periods=4)
1644
+ ser = Series(dti)
1645
+ msg = "Overflow in int64 addition"
1646
+ with pytest.raises(OverflowError, match=msg):
1647
+ ser - dt
1648
+ with pytest.raises(OverflowError, match=msg):
1649
+ dt - ser
1650
+ with pytest.raises(OverflowError, match=msg):
1651
+ ser + td
1652
+ with pytest.raises(OverflowError, match=msg):
1653
+ td + ser
1654
+
1655
+ ser.iloc[-1] = NaT
1656
+ expected = Series(
1657
+ ["2004-10-03", "2104-10-04", "2204-10-04", "NaT"], dtype="datetime64[ns]"
1658
+ )
1659
+ res = ser + td
1660
+ tm.assert_series_equal(res, expected)
1661
+ res = td + ser
1662
+ tm.assert_series_equal(res, expected)
1663
+
1664
+ ser.iloc[1:] = NaT
1665
+ expected = Series(["91279 Days", "NaT", "NaT", "NaT"], dtype="timedelta64[ns]")
1666
+ res = ser - dt
1667
+ tm.assert_series_equal(res, expected)
1668
+ res = dt - ser
1669
+ tm.assert_series_equal(res, -expected)
1670
+
1671
+ def test_datetimeindex_sub_timestamp_overflow(self):
1672
+ dtimax = pd.to_datetime(["2021-12-28 17:19", Timestamp.max]).as_unit("ns")
1673
+ dtimin = pd.to_datetime(["2021-12-28 17:19", Timestamp.min]).as_unit("ns")
1674
+
1675
+ tsneg = Timestamp("1950-01-01").as_unit("ns")
1676
+ ts_neg_variants = [
1677
+ tsneg,
1678
+ tsneg.to_pydatetime(),
1679
+ tsneg.to_datetime64().astype("datetime64[ns]"),
1680
+ tsneg.to_datetime64().astype("datetime64[D]"),
1681
+ ]
1682
+
1683
+ tspos = Timestamp("1980-01-01").as_unit("ns")
1684
+ ts_pos_variants = [
1685
+ tspos,
1686
+ tspos.to_pydatetime(),
1687
+ tspos.to_datetime64().astype("datetime64[ns]"),
1688
+ tspos.to_datetime64().astype("datetime64[D]"),
1689
+ ]
1690
+ msg = "Overflow in int64 addition"
1691
+ for variant in ts_neg_variants:
1692
+ with pytest.raises(OverflowError, match=msg):
1693
+ dtimax - variant
1694
+
1695
+ expected = Timestamp.max._value - tspos._value
1696
+ for variant in ts_pos_variants:
1697
+ res = dtimax - variant
1698
+ assert res[1]._value == expected
1699
+
1700
+ expected = Timestamp.min._value - tsneg._value
1701
+ for variant in ts_neg_variants:
1702
+ res = dtimin - variant
1703
+ assert res[1]._value == expected
1704
+
1705
+ for variant in ts_pos_variants:
1706
+ with pytest.raises(OverflowError, match=msg):
1707
+ dtimin - variant
1708
+
1709
+ def test_datetimeindex_sub_datetimeindex_overflow(self):
1710
+ # GH#22492, GH#22508
1711
+ dtimax = pd.to_datetime(["2021-12-28 17:19", Timestamp.max]).as_unit("ns")
1712
+ dtimin = pd.to_datetime(["2021-12-28 17:19", Timestamp.min]).as_unit("ns")
1713
+
1714
+ ts_neg = pd.to_datetime(["1950-01-01", "1950-01-01"]).as_unit("ns")
1715
+ ts_pos = pd.to_datetime(["1980-01-01", "1980-01-01"]).as_unit("ns")
1716
+
1717
+ # General tests
1718
+ expected = Timestamp.max._value - ts_pos[1]._value
1719
+ result = dtimax - ts_pos
1720
+ assert result[1]._value == expected
1721
+
1722
+ expected = Timestamp.min._value - ts_neg[1]._value
1723
+ result = dtimin - ts_neg
1724
+ assert result[1]._value == expected
1725
+ msg = "Overflow in int64 addition"
1726
+ with pytest.raises(OverflowError, match=msg):
1727
+ dtimax - ts_neg
1728
+
1729
+ with pytest.raises(OverflowError, match=msg):
1730
+ dtimin - ts_pos
1731
+
1732
+ # Edge cases
1733
+ tmin = pd.to_datetime([Timestamp.min])
1734
+ t1 = tmin + Timedelta.max + Timedelta("1us")
1735
+ with pytest.raises(OverflowError, match=msg):
1736
+ t1 - tmin
1737
+
1738
+ tmax = pd.to_datetime([Timestamp.max])
1739
+ t2 = tmax + Timedelta.min - Timedelta("1us")
1740
+ with pytest.raises(OverflowError, match=msg):
1741
+ tmax - t2
1742
+
1743
+
1744
+ class TestTimestampSeriesArithmetic:
1745
+ def test_empty_series_add_sub(self, box_with_array):
1746
+ # GH#13844
1747
+ a = Series(dtype="M8[ns]")
1748
+ b = Series(dtype="m8[ns]")
1749
+ a = box_with_array(a)
1750
+ b = box_with_array(b)
1751
+ tm.assert_equal(a, a + b)
1752
+ tm.assert_equal(a, a - b)
1753
+ tm.assert_equal(a, b + a)
1754
+ msg = "cannot subtract"
1755
+ with pytest.raises(TypeError, match=msg):
1756
+ b - a
1757
+
1758
+ def test_operators_datetimelike(self):
1759
+ # ## timedelta64 ###
1760
+ td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
1761
+ td1.iloc[2] = np.nan
1762
+
1763
+ # ## datetime64 ###
1764
+ dt1 = Series(
1765
+ [
1766
+ Timestamp("20111230"),
1767
+ Timestamp("20120101"),
1768
+ Timestamp("20120103"),
1769
+ ]
1770
+ )
1771
+ dt1.iloc[2] = np.nan
1772
+ dt2 = Series(
1773
+ [
1774
+ Timestamp("20111231"),
1775
+ Timestamp("20120102"),
1776
+ Timestamp("20120104"),
1777
+ ]
1778
+ )
1779
+ dt1 - dt2
1780
+ dt2 - dt1
1781
+
1782
+ # datetime64 with timetimedelta
1783
+ dt1 + td1
1784
+ td1 + dt1
1785
+ dt1 - td1
1786
+
1787
+ # timetimedelta with datetime64
1788
+ td1 + dt1
1789
+ dt1 + td1
1790
+
1791
+ def test_dt64ser_sub_datetime_dtype(self, unit):
1792
+ ts = Timestamp(datetime(1993, 1, 7, 13, 30, 00))
1793
+ dt = datetime(1993, 6, 22, 13, 30)
1794
+ ser = Series([ts], dtype=f"M8[{unit}]")
1795
+ result = ser - dt
1796
+
1797
+ # the expected unit is the max of `unit` and the unit imputed to `dt`,
1798
+ # which is "us"
1799
+ exp_unit = tm.get_finest_unit(unit, "us")
1800
+ assert result.dtype == f"timedelta64[{exp_unit}]"
1801
+
1802
+ # -------------------------------------------------------------
1803
+ # TODO: This next block of tests came from tests.series.test_operators,
1804
+ # needs to be de-duplicated and parametrized over `box` classes
1805
+
1806
+ @pytest.mark.parametrize(
1807
+ "left, right, op_fail",
1808
+ [
1809
+ [
1810
+ [Timestamp("20111230"), Timestamp("20120101"), NaT],
1811
+ [Timestamp("20111231"), Timestamp("20120102"), Timestamp("20120104")],
1812
+ ["__sub__", "__rsub__"],
1813
+ ],
1814
+ [
1815
+ [Timestamp("20111230"), Timestamp("20120101"), NaT],
1816
+ [timedelta(minutes=5, seconds=3), timedelta(minutes=5, seconds=3), NaT],
1817
+ ["__add__", "__radd__", "__sub__"],
1818
+ ],
1819
+ [
1820
+ [
1821
+ Timestamp("20111230", tz="US/Eastern"),
1822
+ Timestamp("20111230", tz="US/Eastern"),
1823
+ NaT,
1824
+ ],
1825
+ [timedelta(minutes=5, seconds=3), NaT, timedelta(minutes=5, seconds=3)],
1826
+ ["__add__", "__radd__", "__sub__"],
1827
+ ],
1828
+ ],
1829
+ )
1830
+ def test_operators_datetimelike_invalid(
1831
+ self, left, right, op_fail, all_arithmetic_operators
1832
+ ):
1833
+ # these are all TypeError ops
1834
+ op_str = all_arithmetic_operators
1835
+ arg1 = Series(left)
1836
+ arg2 = Series(right)
1837
+ # check that we are getting a TypeError
1838
+ # with 'operate' (from core/ops.py) for the ops that are not
1839
+ # defined
1840
+ op = getattr(arg1, op_str, None)
1841
+ # Previously, _validate_for_numeric_binop in core/indexes/base.py
1842
+ # did this for us.
1843
+ if op_str not in op_fail:
1844
+ with pytest.raises(
1845
+ TypeError, match="operate|[cC]annot|unsupported operand"
1846
+ ):
1847
+ op(arg2)
1848
+ else:
1849
+ # Smoke test
1850
+ op(arg2)
1851
+
1852
+ def test_sub_single_tz(self, unit):
1853
+ # GH#12290
1854
+ s1 = Series([Timestamp("2016-02-10", tz="America/Sao_Paulo")]).dt.as_unit(unit)
1855
+ s2 = Series([Timestamp("2016-02-08", tz="America/Sao_Paulo")]).dt.as_unit(unit)
1856
+ result = s1 - s2
1857
+ expected = Series([Timedelta("2days")]).dt.as_unit(unit)
1858
+ tm.assert_series_equal(result, expected)
1859
+ result = s2 - s1
1860
+ expected = Series([Timedelta("-2days")]).dt.as_unit(unit)
1861
+ tm.assert_series_equal(result, expected)
1862
+
1863
+ def test_dt64tz_series_sub_dtitz(self):
1864
+ # GH#19071 subtracting tzaware DatetimeIndex from tzaware Series
1865
+ # (with same tz) raises, fixed by #19024
1866
+ dti = date_range("1999-09-30", periods=10, tz="US/Pacific")
1867
+ ser = Series(dti)
1868
+ expected = Series(TimedeltaIndex(["0days"] * 10))
1869
+
1870
+ res = dti - ser
1871
+ tm.assert_series_equal(res, expected)
1872
+ res = ser - dti
1873
+ tm.assert_series_equal(res, expected)
1874
+
1875
+ def test_sub_datetime_compat(self, unit):
1876
+ # see GH#14088
1877
+ ser = Series([datetime(2016, 8, 23, 12, tzinfo=pytz.utc), NaT]).dt.as_unit(unit)
1878
+ dt = datetime(2016, 8, 22, 12, tzinfo=pytz.utc)
1879
+ # The datetime object has "us" so we upcast lower units
1880
+ exp_unit = tm.get_finest_unit(unit, "us")
1881
+ exp = Series([Timedelta("1 days"), NaT]).dt.as_unit(exp_unit)
1882
+ result = ser - dt
1883
+ tm.assert_series_equal(result, exp)
1884
+ result2 = ser - Timestamp(dt)
1885
+ tm.assert_series_equal(result2, exp)
1886
+
1887
+ def test_dt64_series_add_mixed_tick_DateOffset(self):
1888
+ # GH#4532
1889
+ # operate with pd.offsets
1890
+ s = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")])
1891
+
1892
+ result = s + pd.offsets.Milli(5)
1893
+ result2 = pd.offsets.Milli(5) + s
1894
+ expected = Series(
1895
+ [Timestamp("20130101 9:01:00.005"), Timestamp("20130101 9:02:00.005")]
1896
+ )
1897
+ tm.assert_series_equal(result, expected)
1898
+ tm.assert_series_equal(result2, expected)
1899
+
1900
+ result = s + pd.offsets.Minute(5) + pd.offsets.Milli(5)
1901
+ expected = Series(
1902
+ [Timestamp("20130101 9:06:00.005"), Timestamp("20130101 9:07:00.005")]
1903
+ )
1904
+ tm.assert_series_equal(result, expected)
1905
+
1906
+ def test_datetime64_ops_nat(self, unit):
1907
+ # GH#11349
1908
+ datetime_series = Series([NaT, Timestamp("19900315")]).dt.as_unit(unit)
1909
+ nat_series_dtype_timestamp = Series([NaT, NaT], dtype=f"datetime64[{unit}]")
1910
+ single_nat_dtype_datetime = Series([NaT], dtype=f"datetime64[{unit}]")
1911
+
1912
+ # subtraction
1913
+ tm.assert_series_equal(-NaT + datetime_series, nat_series_dtype_timestamp)
1914
+ msg = "bad operand type for unary -: 'DatetimeArray'"
1915
+ with pytest.raises(TypeError, match=msg):
1916
+ -single_nat_dtype_datetime + datetime_series
1917
+
1918
+ tm.assert_series_equal(
1919
+ -NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp
1920
+ )
1921
+ with pytest.raises(TypeError, match=msg):
1922
+ -single_nat_dtype_datetime + nat_series_dtype_timestamp
1923
+
1924
+ # addition
1925
+ tm.assert_series_equal(
1926
+ nat_series_dtype_timestamp + NaT, nat_series_dtype_timestamp
1927
+ )
1928
+ tm.assert_series_equal(
1929
+ NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp
1930
+ )
1931
+
1932
+ tm.assert_series_equal(
1933
+ nat_series_dtype_timestamp + NaT, nat_series_dtype_timestamp
1934
+ )
1935
+ tm.assert_series_equal(
1936
+ NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp
1937
+ )
1938
+
1939
+ # -------------------------------------------------------------
1940
+ # Timezone-Centric Tests
1941
+
1942
+ def test_operators_datetimelike_with_timezones(self):
1943
+ tz = "US/Eastern"
1944
+ dt1 = Series(date_range("2000-01-01 09:00:00", periods=5, tz=tz), name="foo")
1945
+ dt2 = dt1.copy()
1946
+ dt2.iloc[2] = np.nan
1947
+
1948
+ td1 = Series(pd.timedelta_range("1 days 1 min", periods=5, freq="h"))
1949
+ td2 = td1.copy()
1950
+ td2.iloc[1] = np.nan
1951
+ assert td2._values.freq is None
1952
+
1953
+ result = dt1 + td1[0]
1954
+ exp = (dt1.dt.tz_localize(None) + td1[0]).dt.tz_localize(tz)
1955
+ tm.assert_series_equal(result, exp)
1956
+
1957
+ result = dt2 + td2[0]
1958
+ exp = (dt2.dt.tz_localize(None) + td2[0]).dt.tz_localize(tz)
1959
+ tm.assert_series_equal(result, exp)
1960
+
1961
+ # odd numpy behavior with scalar timedeltas
1962
+ result = td1[0] + dt1
1963
+ exp = (dt1.dt.tz_localize(None) + td1[0]).dt.tz_localize(tz)
1964
+ tm.assert_series_equal(result, exp)
1965
+
1966
+ result = td2[0] + dt2
1967
+ exp = (dt2.dt.tz_localize(None) + td2[0]).dt.tz_localize(tz)
1968
+ tm.assert_series_equal(result, exp)
1969
+
1970
+ result = dt1 - td1[0]
1971
+ exp = (dt1.dt.tz_localize(None) - td1[0]).dt.tz_localize(tz)
1972
+ tm.assert_series_equal(result, exp)
1973
+ msg = "(bad|unsupported) operand type for unary"
1974
+ with pytest.raises(TypeError, match=msg):
1975
+ td1[0] - dt1
1976
+
1977
+ result = dt2 - td2[0]
1978
+ exp = (dt2.dt.tz_localize(None) - td2[0]).dt.tz_localize(tz)
1979
+ tm.assert_series_equal(result, exp)
1980
+ with pytest.raises(TypeError, match=msg):
1981
+ td2[0] - dt2
1982
+
1983
+ result = dt1 + td1
1984
+ exp = (dt1.dt.tz_localize(None) + td1).dt.tz_localize(tz)
1985
+ tm.assert_series_equal(result, exp)
1986
+
1987
+ result = dt2 + td2
1988
+ exp = (dt2.dt.tz_localize(None) + td2).dt.tz_localize(tz)
1989
+ tm.assert_series_equal(result, exp)
1990
+
1991
+ result = dt1 - td1
1992
+ exp = (dt1.dt.tz_localize(None) - td1).dt.tz_localize(tz)
1993
+ tm.assert_series_equal(result, exp)
1994
+
1995
+ result = dt2 - td2
1996
+ exp = (dt2.dt.tz_localize(None) - td2).dt.tz_localize(tz)
1997
+ tm.assert_series_equal(result, exp)
1998
+ msg = "cannot (add|subtract)"
1999
+ with pytest.raises(TypeError, match=msg):
2000
+ td1 - dt1
2001
+ with pytest.raises(TypeError, match=msg):
2002
+ td2 - dt2
2003
+
2004
+
2005
+ class TestDatetimeIndexArithmetic:
2006
+ # -------------------------------------------------------------
2007
+ # Binary operations DatetimeIndex and TimedeltaIndex/array
2008
+
2009
+ def test_dti_add_tdi(self, tz_naive_fixture):
2010
+ # GH#17558
2011
+ tz = tz_naive_fixture
2012
+ dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
2013
+ tdi = pd.timedelta_range("0 days", periods=10)
2014
+ expected = date_range("2017-01-01", periods=10, tz=tz)
2015
+ expected = expected._with_freq(None)
2016
+
2017
+ # add with TimedeltaIndex
2018
+ result = dti + tdi
2019
+ tm.assert_index_equal(result, expected)
2020
+
2021
+ result = tdi + dti
2022
+ tm.assert_index_equal(result, expected)
2023
+
2024
+ # add with timedelta64 array
2025
+ result = dti + tdi.values
2026
+ tm.assert_index_equal(result, expected)
2027
+
2028
+ result = tdi.values + dti
2029
+ tm.assert_index_equal(result, expected)
2030
+
2031
+ def test_dti_iadd_tdi(self, tz_naive_fixture):
2032
+ # GH#17558
2033
+ tz = tz_naive_fixture
2034
+ dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
2035
+ tdi = pd.timedelta_range("0 days", periods=10)
2036
+ expected = date_range("2017-01-01", periods=10, tz=tz)
2037
+ expected = expected._with_freq(None)
2038
+
2039
+ # iadd with TimedeltaIndex
2040
+ result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
2041
+ result += tdi
2042
+ tm.assert_index_equal(result, expected)
2043
+
2044
+ result = pd.timedelta_range("0 days", periods=10)
2045
+ result += dti
2046
+ tm.assert_index_equal(result, expected)
2047
+
2048
+ # iadd with timedelta64 array
2049
+ result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
2050
+ result += tdi.values
2051
+ tm.assert_index_equal(result, expected)
2052
+
2053
+ result = pd.timedelta_range("0 days", periods=10)
2054
+ result += dti
2055
+ tm.assert_index_equal(result, expected)
2056
+
2057
+ def test_dti_sub_tdi(self, tz_naive_fixture):
2058
+ # GH#17558
2059
+ tz = tz_naive_fixture
2060
+ dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
2061
+ tdi = pd.timedelta_range("0 days", periods=10)
2062
+ expected = date_range("2017-01-01", periods=10, tz=tz, freq="-1D")
2063
+ expected = expected._with_freq(None)
2064
+
2065
+ # sub with TimedeltaIndex
2066
+ result = dti - tdi
2067
+ tm.assert_index_equal(result, expected)
2068
+
2069
+ msg = "cannot subtract .*TimedeltaArray"
2070
+ with pytest.raises(TypeError, match=msg):
2071
+ tdi - dti
2072
+
2073
+ # sub with timedelta64 array
2074
+ result = dti - tdi.values
2075
+ tm.assert_index_equal(result, expected)
2076
+
2077
+ msg = "cannot subtract a datelike from a TimedeltaArray"
2078
+ with pytest.raises(TypeError, match=msg):
2079
+ tdi.values - dti
2080
+
2081
+ def test_dti_isub_tdi(self, tz_naive_fixture, unit):
2082
+ # GH#17558
2083
+ tz = tz_naive_fixture
2084
+ dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10).as_unit(unit)
2085
+ tdi = pd.timedelta_range("0 days", periods=10, unit=unit)
2086
+ expected = date_range("2017-01-01", periods=10, tz=tz, freq="-1D", unit=unit)
2087
+ expected = expected._with_freq(None)
2088
+
2089
+ # isub with TimedeltaIndex
2090
+ result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10).as_unit(unit)
2091
+ result -= tdi
2092
+ tm.assert_index_equal(result, expected)
2093
+
2094
+ # DTA.__isub__ GH#43904
2095
+ dta = dti._data.copy()
2096
+ dta -= tdi
2097
+ tm.assert_datetime_array_equal(dta, expected._data)
2098
+
2099
+ out = dti._data.copy()
2100
+ np.subtract(out, tdi, out=out)
2101
+ tm.assert_datetime_array_equal(out, expected._data)
2102
+
2103
+ msg = "cannot subtract a datelike from a TimedeltaArray"
2104
+ with pytest.raises(TypeError, match=msg):
2105
+ tdi -= dti
2106
+
2107
+ # isub with timedelta64 array
2108
+ result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10).as_unit(unit)
2109
+ result -= tdi.values
2110
+ tm.assert_index_equal(result, expected)
2111
+
2112
+ with pytest.raises(TypeError, match=msg):
2113
+ tdi.values -= dti
2114
+
2115
+ with pytest.raises(TypeError, match=msg):
2116
+ tdi._values -= dti
2117
+
2118
+ # -------------------------------------------------------------
2119
+ # Binary Operations DatetimeIndex and datetime-like
2120
+ # TODO: A couple other tests belong in this section. Move them in
2121
+ # A PR where there isn't already a giant diff.
2122
+
2123
+ # -------------------------------------------------------------
2124
+
2125
+ def test_dta_add_sub_index(self, tz_naive_fixture):
2126
+ # Check that DatetimeArray defers to Index classes
2127
+ dti = date_range("20130101", periods=3, tz=tz_naive_fixture)
2128
+ dta = dti.array
2129
+ result = dta - dti
2130
+ expected = dti - dti
2131
+ tm.assert_index_equal(result, expected)
2132
+
2133
+ tdi = result
2134
+ result = dta + tdi
2135
+ expected = dti + tdi
2136
+ tm.assert_index_equal(result, expected)
2137
+
2138
+ result = dta - tdi
2139
+ expected = dti - tdi
2140
+ tm.assert_index_equal(result, expected)
2141
+
2142
+ def test_sub_dti_dti(self, unit):
2143
+ # previously performed setop (deprecated in 0.16.0), now changed to
2144
+ # return subtraction -> TimeDeltaIndex (GH ...)
2145
+
2146
+ dti = date_range("20130101", periods=3, unit=unit)
2147
+ dti_tz = date_range("20130101", periods=3, unit=unit).tz_localize("US/Eastern")
2148
+ expected = TimedeltaIndex([0, 0, 0]).as_unit(unit)
2149
+
2150
+ result = dti - dti
2151
+ tm.assert_index_equal(result, expected)
2152
+
2153
+ result = dti_tz - dti_tz
2154
+ tm.assert_index_equal(result, expected)
2155
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
2156
+ with pytest.raises(TypeError, match=msg):
2157
+ dti_tz - dti
2158
+
2159
+ with pytest.raises(TypeError, match=msg):
2160
+ dti - dti_tz
2161
+
2162
+ # isub
2163
+ dti -= dti
2164
+ tm.assert_index_equal(dti, expected)
2165
+
2166
+ # different length raises ValueError
2167
+ dti1 = date_range("20130101", periods=3, unit=unit)
2168
+ dti2 = date_range("20130101", periods=4, unit=unit)
2169
+ msg = "cannot add indices of unequal length"
2170
+ with pytest.raises(ValueError, match=msg):
2171
+ dti1 - dti2
2172
+
2173
+ # NaN propagation
2174
+ dti1 = DatetimeIndex(["2012-01-01", np.nan, "2012-01-03"]).as_unit(unit)
2175
+ dti2 = DatetimeIndex(["2012-01-02", "2012-01-03", np.nan]).as_unit(unit)
2176
+ expected = TimedeltaIndex(["1 days", np.nan, np.nan]).as_unit(unit)
2177
+ result = dti2 - dti1
2178
+ tm.assert_index_equal(result, expected)
2179
+
2180
+ # -------------------------------------------------------------------
2181
+ # TODO: Most of this block is moved from series or frame tests, needs
2182
+ # cleanup, box-parametrization, and de-duplication
2183
+
2184
+ @pytest.mark.parametrize("op", [operator.add, operator.sub])
2185
+ def test_timedelta64_equal_timedelta_supported_ops(self, op, box_with_array):
2186
+ ser = Series(
2187
+ [
2188
+ Timestamp("20130301"),
2189
+ Timestamp("20130228 23:00:00"),
2190
+ Timestamp("20130228 22:00:00"),
2191
+ Timestamp("20130228 21:00:00"),
2192
+ ]
2193
+ )
2194
+ obj = box_with_array(ser)
2195
+
2196
+ intervals = ["D", "h", "m", "s", "us"]
2197
+
2198
+ def timedelta64(*args):
2199
+ # see casting notes in NumPy gh-12927
2200
+ return np.sum(list(starmap(np.timedelta64, zip(args, intervals))))
2201
+
2202
+ for d, h, m, s, us in product(*([range(2)] * 5)):
2203
+ nptd = timedelta64(d, h, m, s, us)
2204
+ pytd = timedelta(days=d, hours=h, minutes=m, seconds=s, microseconds=us)
2205
+ lhs = op(obj, nptd)
2206
+ rhs = op(obj, pytd)
2207
+
2208
+ tm.assert_equal(lhs, rhs)
2209
+
2210
+ def test_ops_nat_mixed_datetime64_timedelta64(self):
2211
+ # GH#11349
2212
+ timedelta_series = Series([NaT, Timedelta("1s")])
2213
+ datetime_series = Series([NaT, Timestamp("19900315")])
2214
+ nat_series_dtype_timedelta = Series([NaT, NaT], dtype="timedelta64[ns]")
2215
+ nat_series_dtype_timestamp = Series([NaT, NaT], dtype="datetime64[ns]")
2216
+ single_nat_dtype_datetime = Series([NaT], dtype="datetime64[ns]")
2217
+ single_nat_dtype_timedelta = Series([NaT], dtype="timedelta64[ns]")
2218
+
2219
+ # subtraction
2220
+ tm.assert_series_equal(
2221
+ datetime_series - single_nat_dtype_datetime, nat_series_dtype_timedelta
2222
+ )
2223
+
2224
+ tm.assert_series_equal(
2225
+ datetime_series - single_nat_dtype_timedelta, nat_series_dtype_timestamp
2226
+ )
2227
+ tm.assert_series_equal(
2228
+ -single_nat_dtype_timedelta + datetime_series, nat_series_dtype_timestamp
2229
+ )
2230
+
2231
+ # without a Series wrapping the NaT, it is ambiguous
2232
+ # whether it is a datetime64 or timedelta64
2233
+ # defaults to interpreting it as timedelta64
2234
+ tm.assert_series_equal(
2235
+ nat_series_dtype_timestamp - single_nat_dtype_datetime,
2236
+ nat_series_dtype_timedelta,
2237
+ )
2238
+
2239
+ tm.assert_series_equal(
2240
+ nat_series_dtype_timestamp - single_nat_dtype_timedelta,
2241
+ nat_series_dtype_timestamp,
2242
+ )
2243
+ tm.assert_series_equal(
2244
+ -single_nat_dtype_timedelta + nat_series_dtype_timestamp,
2245
+ nat_series_dtype_timestamp,
2246
+ )
2247
+ msg = "cannot subtract a datelike"
2248
+ with pytest.raises(TypeError, match=msg):
2249
+ timedelta_series - single_nat_dtype_datetime
2250
+
2251
+ # addition
2252
+ tm.assert_series_equal(
2253
+ nat_series_dtype_timestamp + single_nat_dtype_timedelta,
2254
+ nat_series_dtype_timestamp,
2255
+ )
2256
+ tm.assert_series_equal(
2257
+ single_nat_dtype_timedelta + nat_series_dtype_timestamp,
2258
+ nat_series_dtype_timestamp,
2259
+ )
2260
+
2261
+ tm.assert_series_equal(
2262
+ nat_series_dtype_timestamp + single_nat_dtype_timedelta,
2263
+ nat_series_dtype_timestamp,
2264
+ )
2265
+ tm.assert_series_equal(
2266
+ single_nat_dtype_timedelta + nat_series_dtype_timestamp,
2267
+ nat_series_dtype_timestamp,
2268
+ )
2269
+
2270
+ tm.assert_series_equal(
2271
+ nat_series_dtype_timedelta + single_nat_dtype_datetime,
2272
+ nat_series_dtype_timestamp,
2273
+ )
2274
+ tm.assert_series_equal(
2275
+ single_nat_dtype_datetime + nat_series_dtype_timedelta,
2276
+ nat_series_dtype_timestamp,
2277
+ )
2278
+
2279
+ def test_ufunc_coercions(self, unit):
2280
+ idx = date_range("2011-01-01", periods=3, freq="2D", name="x", unit=unit)
2281
+
2282
+ delta = np.timedelta64(1, "D")
2283
+ exp = date_range("2011-01-02", periods=3, freq="2D", name="x", unit=unit)
2284
+ for result in [idx + delta, np.add(idx, delta)]:
2285
+ assert isinstance(result, DatetimeIndex)
2286
+ tm.assert_index_equal(result, exp)
2287
+ assert result.freq == "2D"
2288
+
2289
+ exp = date_range("2010-12-31", periods=3, freq="2D", name="x", unit=unit)
2290
+
2291
+ for result in [idx - delta, np.subtract(idx, delta)]:
2292
+ assert isinstance(result, DatetimeIndex)
2293
+ tm.assert_index_equal(result, exp)
2294
+ assert result.freq == "2D"
2295
+
2296
+ # When adding/subtracting an ndarray (which has no .freq), the result
2297
+ # does not infer freq
2298
+ idx = idx._with_freq(None)
2299
+ delta = np.array(
2300
+ [np.timedelta64(1, "D"), np.timedelta64(2, "D"), np.timedelta64(3, "D")]
2301
+ )
2302
+ exp = DatetimeIndex(
2303
+ ["2011-01-02", "2011-01-05", "2011-01-08"], name="x"
2304
+ ).as_unit(unit)
2305
+
2306
+ for result in [idx + delta, np.add(idx, delta)]:
2307
+ tm.assert_index_equal(result, exp)
2308
+ assert result.freq == exp.freq
2309
+
2310
+ exp = DatetimeIndex(
2311
+ ["2010-12-31", "2011-01-01", "2011-01-02"], name="x"
2312
+ ).as_unit(unit)
2313
+ for result in [idx - delta, np.subtract(idx, delta)]:
2314
+ assert isinstance(result, DatetimeIndex)
2315
+ tm.assert_index_equal(result, exp)
2316
+ assert result.freq == exp.freq
2317
+
2318
+ def test_dti_add_series(self, tz_naive_fixture, names):
2319
+ # GH#13905
2320
+ tz = tz_naive_fixture
2321
+ index = DatetimeIndex(
2322
+ ["2016-06-28 05:30", "2016-06-28 05:31"], tz=tz, name=names[0]
2323
+ ).as_unit("ns")
2324
+ ser = Series([Timedelta(seconds=5)] * 2, index=index, name=names[1])
2325
+ expected = Series(index + Timedelta(seconds=5), index=index, name=names[2])
2326
+
2327
+ # passing name arg isn't enough when names[2] is None
2328
+ expected.name = names[2]
2329
+ assert expected.dtype == index.dtype
2330
+ result = ser + index
2331
+ tm.assert_series_equal(result, expected)
2332
+ result2 = index + ser
2333
+ tm.assert_series_equal(result2, expected)
2334
+
2335
+ expected = index + Timedelta(seconds=5)
2336
+ result3 = ser.values + index
2337
+ tm.assert_index_equal(result3, expected)
2338
+ result4 = index + ser.values
2339
+ tm.assert_index_equal(result4, expected)
2340
+
2341
+ @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub])
2342
+ def test_dti_addsub_offset_arraylike(
2343
+ self, tz_naive_fixture, names, op, index_or_series
2344
+ ):
2345
+ # GH#18849, GH#19744
2346
+ other_box = index_or_series
2347
+
2348
+ tz = tz_naive_fixture
2349
+ dti = date_range("2017-01-01", periods=2, tz=tz, name=names[0])
2350
+ other = other_box([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)], name=names[1])
2351
+
2352
+ xbox = get_upcast_box(dti, other)
2353
+
2354
+ with tm.assert_produces_warning(PerformanceWarning):
2355
+ res = op(dti, other)
2356
+
2357
+ expected = DatetimeIndex(
2358
+ [op(dti[n], other[n]) for n in range(len(dti))], name=names[2], freq="infer"
2359
+ )
2360
+ expected = tm.box_expected(expected, xbox).astype(object)
2361
+ tm.assert_equal(res, expected)
2362
+
2363
+ @pytest.mark.parametrize("other_box", [pd.Index, np.array])
2364
+ def test_dti_addsub_object_arraylike(
2365
+ self, tz_naive_fixture, box_with_array, other_box
2366
+ ):
2367
+ tz = tz_naive_fixture
2368
+
2369
+ dti = date_range("2017-01-01", periods=2, tz=tz)
2370
+ dtarr = tm.box_expected(dti, box_with_array)
2371
+ other = other_box([pd.offsets.MonthEnd(), Timedelta(days=4)])
2372
+ xbox = get_upcast_box(dtarr, other)
2373
+
2374
+ expected = DatetimeIndex(["2017-01-31", "2017-01-06"], tz=tz_naive_fixture)
2375
+ expected = tm.box_expected(expected, xbox).astype(object)
2376
+
2377
+ with tm.assert_produces_warning(PerformanceWarning):
2378
+ result = dtarr + other
2379
+ tm.assert_equal(result, expected)
2380
+
2381
+ expected = DatetimeIndex(["2016-12-31", "2016-12-29"], tz=tz_naive_fixture)
2382
+ expected = tm.box_expected(expected, xbox).astype(object)
2383
+
2384
+ with tm.assert_produces_warning(PerformanceWarning):
2385
+ result = dtarr - other
2386
+ tm.assert_equal(result, expected)
2387
+
2388
+
2389
+ @pytest.mark.parametrize("years", [-1, 0, 1])
2390
+ @pytest.mark.parametrize("months", [-2, 0, 2])
2391
+ @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
2392
+ def test_shift_months(years, months, unit):
2393
+ dti = DatetimeIndex(
2394
+ [
2395
+ Timestamp("2000-01-05 00:15:00"),
2396
+ Timestamp("2000-01-31 00:23:00"),
2397
+ Timestamp("2000-01-01"),
2398
+ Timestamp("2000-02-29"),
2399
+ Timestamp("2000-12-31"),
2400
+ ]
2401
+ ).as_unit(unit)
2402
+ shifted = shift_months(dti.asi8, years * 12 + months, reso=dti._data._creso)
2403
+ shifted_dt64 = shifted.view(f"M8[{dti.unit}]")
2404
+ actual = DatetimeIndex(shifted_dt64)
2405
+
2406
+ raw = [x + pd.offsets.DateOffset(years=years, months=months) for x in dti]
2407
+ expected = DatetimeIndex(raw).as_unit(dti.unit)
2408
+ tm.assert_index_equal(actual, expected)
2409
+
2410
+
2411
+ def test_dt64arr_addsub_object_dtype_2d():
2412
+ # block-wise DataFrame operations will require operating on 2D
2413
+ # DatetimeArray/TimedeltaArray, so check that specifically.
2414
+ dti = date_range("1994-02-13", freq="2W", periods=4)
2415
+ dta = dti._data.reshape((4, 1))
2416
+
2417
+ other = np.array([[pd.offsets.Day(n)] for n in range(4)])
2418
+ assert other.shape == dta.shape
2419
+
2420
+ with tm.assert_produces_warning(PerformanceWarning):
2421
+ result = dta + other
2422
+ with tm.assert_produces_warning(PerformanceWarning):
2423
+ expected = (dta[:, 0] + other[:, 0]).reshape(-1, 1)
2424
+
2425
+ tm.assert_numpy_array_equal(result, expected)
2426
+
2427
+ with tm.assert_produces_warning(PerformanceWarning):
2428
+ # Case where we expect to get a TimedeltaArray back
2429
+ result2 = dta - dta.astype(object)
2430
+
2431
+ assert result2.shape == (4, 1)
2432
+ assert all(td._value == 0 for td in result2.ravel())
2433
+
2434
+
2435
+ def test_non_nano_dt64_addsub_np_nat_scalars():
2436
+ # GH 52295
2437
+ ser = Series([1233242342344, 232432434324, 332434242344], dtype="datetime64[ms]")
2438
+ result = ser - np.datetime64("nat", "ms")
2439
+ expected = Series([NaT] * 3, dtype="timedelta64[ms]")
2440
+ tm.assert_series_equal(result, expected)
2441
+
2442
+ result = ser + np.timedelta64("nat", "ms")
2443
+ expected = Series([NaT] * 3, dtype="datetime64[ms]")
2444
+ tm.assert_series_equal(result, expected)
2445
+
2446
+
2447
+ def test_non_nano_dt64_addsub_np_nat_scalars_unitless():
2448
+ # GH 52295
2449
+ # TODO: Can we default to the ser unit?
2450
+ ser = Series([1233242342344, 232432434324, 332434242344], dtype="datetime64[ms]")
2451
+ result = ser - np.datetime64("nat")
2452
+ expected = Series([NaT] * 3, dtype="timedelta64[ns]")
2453
+ tm.assert_series_equal(result, expected)
2454
+
2455
+ result = ser + np.timedelta64("nat")
2456
+ expected = Series([NaT] * 3, dtype="datetime64[ns]")
2457
+ tm.assert_series_equal(result, expected)
2458
+
2459
+
2460
+ def test_non_nano_dt64_addsub_np_nat_scalars_unsupported_unit():
2461
+ # GH 52295
2462
+ ser = Series([12332, 23243, 33243], dtype="datetime64[s]")
2463
+ result = ser - np.datetime64("nat", "D")
2464
+ expected = Series([NaT] * 3, dtype="timedelta64[s]")
2465
+ tm.assert_series_equal(result, expected)
2466
+
2467
+ result = ser + np.timedelta64("nat", "D")
2468
+ expected = Series([NaT] * 3, dtype="datetime64[s]")
2469
+ tm.assert_series_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_interval.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas.core.dtypes.common import is_list_like
7
+
8
+ import pandas as pd
9
+ from pandas import (
10
+ Categorical,
11
+ Index,
12
+ Interval,
13
+ IntervalIndex,
14
+ Period,
15
+ Series,
16
+ Timedelta,
17
+ Timestamp,
18
+ date_range,
19
+ period_range,
20
+ timedelta_range,
21
+ )
22
+ import pandas._testing as tm
23
+ from pandas.core.arrays import (
24
+ BooleanArray,
25
+ IntervalArray,
26
+ )
27
+ from pandas.tests.arithmetic.common import get_upcast_box
28
+
29
+
30
+ @pytest.fixture(
31
+ params=[
32
+ (Index([0, 2, 4, 4]), Index([1, 3, 5, 8])),
33
+ (Index([0.0, 1.0, 2.0, np.nan]), Index([1.0, 2.0, 3.0, np.nan])),
34
+ (
35
+ timedelta_range("0 days", periods=3).insert(3, pd.NaT),
36
+ timedelta_range("1 day", periods=3).insert(3, pd.NaT),
37
+ ),
38
+ (
39
+ date_range("20170101", periods=3).insert(3, pd.NaT),
40
+ date_range("20170102", periods=3).insert(3, pd.NaT),
41
+ ),
42
+ (
43
+ date_range("20170101", periods=3, tz="US/Eastern").insert(3, pd.NaT),
44
+ date_range("20170102", periods=3, tz="US/Eastern").insert(3, pd.NaT),
45
+ ),
46
+ ],
47
+ ids=lambda x: str(x[0].dtype),
48
+ )
49
+ def left_right_dtypes(request):
50
+ """
51
+ Fixture for building an IntervalArray from various dtypes
52
+ """
53
+ return request.param
54
+
55
+
56
+ @pytest.fixture
57
+ def interval_array(left_right_dtypes):
58
+ """
59
+ Fixture to generate an IntervalArray of various dtypes containing NA if possible
60
+ """
61
+ left, right = left_right_dtypes
62
+ return IntervalArray.from_arrays(left, right)
63
+
64
+
65
+ def create_categorical_intervals(left, right, closed="right"):
66
+ return Categorical(IntervalIndex.from_arrays(left, right, closed))
67
+
68
+
69
+ def create_series_intervals(left, right, closed="right"):
70
+ return Series(IntervalArray.from_arrays(left, right, closed))
71
+
72
+
73
+ def create_series_categorical_intervals(left, right, closed="right"):
74
+ return Series(Categorical(IntervalIndex.from_arrays(left, right, closed)))
75
+
76
+
77
+ class TestComparison:
78
+ @pytest.fixture(params=[operator.eq, operator.ne])
79
+ def op(self, request):
80
+ return request.param
81
+
82
+ @pytest.fixture(
83
+ params=[
84
+ IntervalArray.from_arrays,
85
+ IntervalIndex.from_arrays,
86
+ create_categorical_intervals,
87
+ create_series_intervals,
88
+ create_series_categorical_intervals,
89
+ ],
90
+ ids=[
91
+ "IntervalArray",
92
+ "IntervalIndex",
93
+ "Categorical[Interval]",
94
+ "Series[Interval]",
95
+ "Series[Categorical[Interval]]",
96
+ ],
97
+ )
98
+ def interval_constructor(self, request):
99
+ """
100
+ Fixture for all pandas native interval constructors.
101
+ To be used as the LHS of IntervalArray comparisons.
102
+ """
103
+ return request.param
104
+
105
+ def elementwise_comparison(self, op, interval_array, other):
106
+ """
107
+ Helper that performs elementwise comparisons between `array` and `other`
108
+ """
109
+ other = other if is_list_like(other) else [other] * len(interval_array)
110
+ expected = np.array([op(x, y) for x, y in zip(interval_array, other)])
111
+ if isinstance(other, Series):
112
+ return Series(expected, index=other.index)
113
+ return expected
114
+
115
+ def test_compare_scalar_interval(self, op, interval_array):
116
+ # matches first interval
117
+ other = interval_array[0]
118
+ result = op(interval_array, other)
119
+ expected = self.elementwise_comparison(op, interval_array, other)
120
+ tm.assert_numpy_array_equal(result, expected)
121
+
122
+ # matches on a single endpoint but not both
123
+ other = Interval(interval_array.left[0], interval_array.right[1])
124
+ result = op(interval_array, other)
125
+ expected = self.elementwise_comparison(op, interval_array, other)
126
+ tm.assert_numpy_array_equal(result, expected)
127
+
128
+ def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed):
129
+ interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
130
+ other = Interval(0, 1, closed=other_closed)
131
+
132
+ result = op(interval_array, other)
133
+ expected = self.elementwise_comparison(op, interval_array, other)
134
+ tm.assert_numpy_array_equal(result, expected)
135
+
136
+ def test_compare_scalar_na(self, op, interval_array, nulls_fixture, box_with_array):
137
+ box = box_with_array
138
+ obj = tm.box_expected(interval_array, box)
139
+ result = op(obj, nulls_fixture)
140
+
141
+ if nulls_fixture is pd.NA:
142
+ # GH#31882
143
+ exp = np.ones(interval_array.shape, dtype=bool)
144
+ expected = BooleanArray(exp, exp)
145
+ else:
146
+ expected = self.elementwise_comparison(op, interval_array, nulls_fixture)
147
+
148
+ if not (box is Index and nulls_fixture is pd.NA):
149
+ # don't cast expected from BooleanArray to ndarray[object]
150
+ xbox = get_upcast_box(obj, nulls_fixture, True)
151
+ expected = tm.box_expected(expected, xbox)
152
+
153
+ tm.assert_equal(result, expected)
154
+
155
+ rev = op(nulls_fixture, obj)
156
+ tm.assert_equal(rev, expected)
157
+
158
+ @pytest.mark.parametrize(
159
+ "other",
160
+ [
161
+ 0,
162
+ 1.0,
163
+ True,
164
+ "foo",
165
+ Timestamp("2017-01-01"),
166
+ Timestamp("2017-01-01", tz="US/Eastern"),
167
+ Timedelta("0 days"),
168
+ Period("2017-01-01", "D"),
169
+ ],
170
+ )
171
+ def test_compare_scalar_other(self, op, interval_array, other):
172
+ result = op(interval_array, other)
173
+ expected = self.elementwise_comparison(op, interval_array, other)
174
+ tm.assert_numpy_array_equal(result, expected)
175
+
176
+ def test_compare_list_like_interval(self, op, interval_array, interval_constructor):
177
+ # same endpoints
178
+ other = interval_constructor(interval_array.left, interval_array.right)
179
+ result = op(interval_array, other)
180
+ expected = self.elementwise_comparison(op, interval_array, other)
181
+ tm.assert_equal(result, expected)
182
+
183
+ # different endpoints
184
+ other = interval_constructor(
185
+ interval_array.left[::-1], interval_array.right[::-1]
186
+ )
187
+ result = op(interval_array, other)
188
+ expected = self.elementwise_comparison(op, interval_array, other)
189
+ tm.assert_equal(result, expected)
190
+
191
+ # all nan endpoints
192
+ other = interval_constructor([np.nan] * 4, [np.nan] * 4)
193
+ result = op(interval_array, other)
194
+ expected = self.elementwise_comparison(op, interval_array, other)
195
+ tm.assert_equal(result, expected)
196
+
197
+ def test_compare_list_like_interval_mixed_closed(
198
+ self, op, interval_constructor, closed, other_closed
199
+ ):
200
+ interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
201
+ other = interval_constructor(range(2), range(1, 3), closed=other_closed)
202
+
203
+ result = op(interval_array, other)
204
+ expected = self.elementwise_comparison(op, interval_array, other)
205
+ tm.assert_equal(result, expected)
206
+
207
+ @pytest.mark.parametrize(
208
+ "other",
209
+ [
210
+ (
211
+ Interval(0, 1),
212
+ Interval(Timedelta("1 day"), Timedelta("2 days")),
213
+ Interval(4, 5, "both"),
214
+ Interval(10, 20, "neither"),
215
+ ),
216
+ (0, 1.5, Timestamp("20170103"), np.nan),
217
+ (
218
+ Timestamp("20170102", tz="US/Eastern"),
219
+ Timedelta("2 days"),
220
+ "baz",
221
+ pd.NaT,
222
+ ),
223
+ ],
224
+ )
225
+ def test_compare_list_like_object(self, op, interval_array, other):
226
+ result = op(interval_array, other)
227
+ expected = self.elementwise_comparison(op, interval_array, other)
228
+ tm.assert_numpy_array_equal(result, expected)
229
+
230
+ def test_compare_list_like_nan(self, op, interval_array, nulls_fixture):
231
+ other = [nulls_fixture] * 4
232
+ result = op(interval_array, other)
233
+ expected = self.elementwise_comparison(op, interval_array, other)
234
+
235
+ tm.assert_equal(result, expected)
236
+
237
+ @pytest.mark.parametrize(
238
+ "other",
239
+ [
240
+ np.arange(4, dtype="int64"),
241
+ np.arange(4, dtype="float64"),
242
+ date_range("2017-01-01", periods=4),
243
+ date_range("2017-01-01", periods=4, tz="US/Eastern"),
244
+ timedelta_range("0 days", periods=4),
245
+ period_range("2017-01-01", periods=4, freq="D"),
246
+ Categorical(list("abab")),
247
+ Categorical(date_range("2017-01-01", periods=4)),
248
+ pd.array(list("abcd")),
249
+ pd.array(["foo", 3.14, None, object()], dtype=object),
250
+ ],
251
+ ids=lambda x: str(x.dtype),
252
+ )
253
+ def test_compare_list_like_other(self, op, interval_array, other):
254
+ result = op(interval_array, other)
255
+ expected = self.elementwise_comparison(op, interval_array, other)
256
+ tm.assert_numpy_array_equal(result, expected)
257
+
258
+ @pytest.mark.parametrize("length", [1, 3, 5])
259
+ @pytest.mark.parametrize("other_constructor", [IntervalArray, list])
260
+ def test_compare_length_mismatch_errors(self, op, other_constructor, length):
261
+ interval_array = IntervalArray.from_arrays(range(4), range(1, 5))
262
+ other = other_constructor([Interval(0, 1)] * length)
263
+ with pytest.raises(ValueError, match="Lengths must match to compare"):
264
+ op(interval_array, other)
265
+
266
+ @pytest.mark.parametrize(
267
+ "constructor, expected_type, assert_func",
268
+ [
269
+ (IntervalIndex, np.array, tm.assert_numpy_array_equal),
270
+ (Series, Series, tm.assert_series_equal),
271
+ ],
272
+ )
273
+ def test_index_series_compat(self, op, constructor, expected_type, assert_func):
274
+ # IntervalIndex/Series that rely on IntervalArray for comparisons
275
+ breaks = range(4)
276
+ index = constructor(IntervalIndex.from_breaks(breaks))
277
+
278
+ # scalar comparisons
279
+ other = index[0]
280
+ result = op(index, other)
281
+ expected = expected_type(self.elementwise_comparison(op, index, other))
282
+ assert_func(result, expected)
283
+
284
+ other = breaks[0]
285
+ result = op(index, other)
286
+ expected = expected_type(self.elementwise_comparison(op, index, other))
287
+ assert_func(result, expected)
288
+
289
+ # list-like comparisons
290
+ other = IntervalArray.from_breaks(breaks)
291
+ result = op(index, other)
292
+ expected = expected_type(self.elementwise_comparison(op, index, other))
293
+ assert_func(result, expected)
294
+
295
+ other = [index[0], breaks[0], "foo"]
296
+ result = op(index, other)
297
+ expected = expected_type(self.elementwise_comparison(op, index, other))
298
+ assert_func(result, expected)
299
+
300
+ @pytest.mark.parametrize("scalars", ["a", False, 1, 1.0, None])
301
+ def test_comparison_operations(self, scalars):
302
+ # GH #28981
303
+ expected = Series([False, False])
304
+ s = Series([Interval(0, 1), Interval(1, 2)], dtype="interval")
305
+ result = s == scalars
306
+ tm.assert_series_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_numeric.py ADDED
@@ -0,0 +1,1567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Arithmetic tests for DataFrame/Series/Index/Array classes that should
2
+ # behave identically.
3
+ # Specifically for numeric dtypes
4
+ from __future__ import annotations
5
+
6
+ from collections import abc
7
+ from datetime import timedelta
8
+ from decimal import Decimal
9
+ import operator
10
+
11
+ import numpy as np
12
+ import pytest
13
+
14
+ import pandas as pd
15
+ from pandas import (
16
+ Index,
17
+ RangeIndex,
18
+ Series,
19
+ Timedelta,
20
+ TimedeltaIndex,
21
+ array,
22
+ date_range,
23
+ )
24
+ import pandas._testing as tm
25
+ from pandas.core import ops
26
+ from pandas.core.computation import expressions as expr
27
+ from pandas.tests.arithmetic.common import (
28
+ assert_invalid_addsub_type,
29
+ assert_invalid_comparison,
30
+ )
31
+
32
+
33
+ @pytest.fixture(autouse=True, params=[0, 1000000], ids=["numexpr", "python"])
34
+ def switch_numexpr_min_elements(request, monkeypatch):
35
+ with monkeypatch.context() as m:
36
+ m.setattr(expr, "_MIN_ELEMENTS", request.param)
37
+ yield request.param
38
+
39
+
40
+ @pytest.fixture(params=[Index, Series, tm.to_array])
41
+ def box_pandas_1d_array(request):
42
+ """
43
+ Fixture to test behavior for Index, Series and tm.to_array classes
44
+ """
45
+ return request.param
46
+
47
+
48
+ @pytest.fixture(
49
+ params=[
50
+ # TODO: add more dtypes here
51
+ Index(np.arange(5, dtype="float64")),
52
+ Index(np.arange(5, dtype="int64")),
53
+ Index(np.arange(5, dtype="uint64")),
54
+ RangeIndex(5),
55
+ ],
56
+ ids=lambda x: type(x).__name__,
57
+ )
58
+ def numeric_idx(request):
59
+ """
60
+ Several types of numeric-dtypes Index objects
61
+ """
62
+ return request.param
63
+
64
+
65
+ @pytest.fixture(
66
+ params=[Index, Series, tm.to_array, np.array, list], ids=lambda x: x.__name__
67
+ )
68
+ def box_1d_array(request):
69
+ """
70
+ Fixture to test behavior for Index, Series, tm.to_array, numpy Array and list
71
+ classes
72
+ """
73
+ return request.param
74
+
75
+
76
+ def adjust_negative_zero(zero, expected):
77
+ """
78
+ Helper to adjust the expected result if we are dividing by -0.0
79
+ as opposed to 0.0
80
+ """
81
+ if np.signbit(np.array(zero)).any():
82
+ # All entries in the `zero` fixture should be either
83
+ # all-negative or no-negative.
84
+ assert np.signbit(np.array(zero)).all()
85
+
86
+ expected *= -1
87
+
88
+ return expected
89
+
90
+
91
+ def compare_op(series, other, op):
92
+ left = np.abs(series) if op in (ops.rpow, operator.pow) else series
93
+ right = np.abs(other) if op in (ops.rpow, operator.pow) else other
94
+
95
+ cython_or_numpy = op(left, right)
96
+ python = left.combine(right, op)
97
+ if isinstance(other, Series) and not other.index.equals(series.index):
98
+ python.index = python.index._with_freq(None)
99
+ tm.assert_series_equal(cython_or_numpy, python)
100
+
101
+
102
+ # TODO: remove this kludge once mypy stops giving false positives here
103
+ # List comprehension has incompatible type List[PandasObject]; expected List[RangeIndex]
104
+ # See GH#29725
105
+ _ldtypes = ["i1", "i2", "i4", "i8", "u1", "u2", "u4", "u8", "f2", "f4", "f8"]
106
+ lefts: list[Index | Series] = [RangeIndex(10, 40, 10)]
107
+ lefts.extend([Series([10, 20, 30], dtype=dtype) for dtype in _ldtypes])
108
+ lefts.extend([Index([10, 20, 30], dtype=dtype) for dtype in _ldtypes if dtype != "f2"])
109
+
110
+ # ------------------------------------------------------------------
111
+ # Comparisons
112
+
113
+
114
+ class TestNumericComparisons:
115
+ def test_operator_series_comparison_zerorank(self):
116
+ # GH#13006
117
+ result = np.float64(0) > Series([1, 2, 3])
118
+ expected = 0.0 > Series([1, 2, 3])
119
+ tm.assert_series_equal(result, expected)
120
+ result = Series([1, 2, 3]) < np.float64(0)
121
+ expected = Series([1, 2, 3]) < 0.0
122
+ tm.assert_series_equal(result, expected)
123
+ result = np.array([0, 1, 2])[0] > Series([0, 1, 2])
124
+ expected = 0.0 > Series([1, 2, 3])
125
+ tm.assert_series_equal(result, expected)
126
+
127
+ def test_df_numeric_cmp_dt64_raises(self, box_with_array, fixed_now_ts):
128
+ # GH#8932, GH#22163
129
+ ts = fixed_now_ts
130
+ obj = np.array(range(5))
131
+ obj = tm.box_expected(obj, box_with_array)
132
+
133
+ assert_invalid_comparison(obj, ts, box_with_array)
134
+
135
+ def test_compare_invalid(self):
136
+ # GH#8058
137
+ # ops testing
138
+ a = Series(np.random.default_rng(2).standard_normal(5), name=0)
139
+ b = Series(np.random.default_rng(2).standard_normal(5))
140
+ b.name = pd.Timestamp("2000-01-01")
141
+ tm.assert_series_equal(a / b, 1 / (b / a))
142
+
143
+ def test_numeric_cmp_string_numexpr_path(self, box_with_array, monkeypatch):
144
+ # GH#36377, GH#35700
145
+ box = box_with_array
146
+ xbox = box if box is not Index else np.ndarray
147
+
148
+ obj = Series(np.random.default_rng(2).standard_normal(51))
149
+ obj = tm.box_expected(obj, box, transpose=False)
150
+ with monkeypatch.context() as m:
151
+ m.setattr(expr, "_MIN_ELEMENTS", 50)
152
+ result = obj == "a"
153
+
154
+ expected = Series(np.zeros(51, dtype=bool))
155
+ expected = tm.box_expected(expected, xbox, transpose=False)
156
+ tm.assert_equal(result, expected)
157
+
158
+ with monkeypatch.context() as m:
159
+ m.setattr(expr, "_MIN_ELEMENTS", 50)
160
+ result = obj != "a"
161
+ tm.assert_equal(result, ~expected)
162
+
163
+ msg = "Invalid comparison between dtype=float64 and str"
164
+ with pytest.raises(TypeError, match=msg):
165
+ obj < "a"
166
+
167
+
168
+ # ------------------------------------------------------------------
169
+ # Numeric dtypes Arithmetic with Datetime/Timedelta Scalar
170
+
171
+
172
+ class TestNumericArraylikeArithmeticWithDatetimeLike:
173
+ @pytest.mark.parametrize("box_cls", [np.array, Index, Series])
174
+ @pytest.mark.parametrize(
175
+ "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype)
176
+ )
177
+ def test_mul_td64arr(self, left, box_cls):
178
+ # GH#22390
179
+ right = np.array([1, 2, 3], dtype="m8[s]")
180
+ right = box_cls(right)
181
+
182
+ expected = TimedeltaIndex(["10s", "40s", "90s"], dtype=right.dtype)
183
+
184
+ if isinstance(left, Series) or box_cls is Series:
185
+ expected = Series(expected)
186
+ assert expected.dtype == right.dtype
187
+
188
+ result = left * right
189
+ tm.assert_equal(result, expected)
190
+
191
+ result = right * left
192
+ tm.assert_equal(result, expected)
193
+
194
+ @pytest.mark.parametrize("box_cls", [np.array, Index, Series])
195
+ @pytest.mark.parametrize(
196
+ "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype)
197
+ )
198
+ def test_div_td64arr(self, left, box_cls):
199
+ # GH#22390
200
+ right = np.array([10, 40, 90], dtype="m8[s]")
201
+ right = box_cls(right)
202
+
203
+ expected = TimedeltaIndex(["1s", "2s", "3s"], dtype=right.dtype)
204
+ if isinstance(left, Series) or box_cls is Series:
205
+ expected = Series(expected)
206
+ assert expected.dtype == right.dtype
207
+
208
+ result = right / left
209
+ tm.assert_equal(result, expected)
210
+
211
+ result = right // left
212
+ tm.assert_equal(result, expected)
213
+
214
+ # (true_) needed for min-versions build 2022-12-26
215
+ msg = "ufunc '(true_)?divide' cannot use operands with types"
216
+ with pytest.raises(TypeError, match=msg):
217
+ left / right
218
+
219
+ msg = "ufunc 'floor_divide' cannot use operands with types"
220
+ with pytest.raises(TypeError, match=msg):
221
+ left // right
222
+
223
+ # TODO: also test Tick objects;
224
+ # see test_numeric_arr_rdiv_tdscalar for note on these failing
225
+ @pytest.mark.parametrize(
226
+ "scalar_td",
227
+ [
228
+ Timedelta(days=1),
229
+ Timedelta(days=1).to_timedelta64(),
230
+ Timedelta(days=1).to_pytimedelta(),
231
+ Timedelta(days=1).to_timedelta64().astype("timedelta64[s]"),
232
+ Timedelta(days=1).to_timedelta64().astype("timedelta64[ms]"),
233
+ ],
234
+ ids=lambda x: type(x).__name__,
235
+ )
236
+ def test_numeric_arr_mul_tdscalar(self, scalar_td, numeric_idx, box_with_array):
237
+ # GH#19333
238
+ box = box_with_array
239
+ index = numeric_idx
240
+ expected = TimedeltaIndex([Timedelta(days=n) for n in range(len(index))])
241
+ if isinstance(scalar_td, np.timedelta64):
242
+ dtype = scalar_td.dtype
243
+ expected = expected.astype(dtype)
244
+ elif type(scalar_td) is timedelta:
245
+ expected = expected.astype("m8[us]")
246
+
247
+ index = tm.box_expected(index, box)
248
+ expected = tm.box_expected(expected, box)
249
+
250
+ result = index * scalar_td
251
+ tm.assert_equal(result, expected)
252
+
253
+ commute = scalar_td * index
254
+ tm.assert_equal(commute, expected)
255
+
256
+ @pytest.mark.parametrize(
257
+ "scalar_td",
258
+ [
259
+ Timedelta(days=1),
260
+ Timedelta(days=1).to_timedelta64(),
261
+ Timedelta(days=1).to_pytimedelta(),
262
+ ],
263
+ ids=lambda x: type(x).__name__,
264
+ )
265
+ @pytest.mark.parametrize("dtype", [np.int64, np.float64])
266
+ def test_numeric_arr_mul_tdscalar_numexpr_path(
267
+ self, dtype, scalar_td, box_with_array
268
+ ):
269
+ # GH#44772 for the float64 case
270
+ box = box_with_array
271
+
272
+ arr_i8 = np.arange(2 * 10**4).astype(np.int64, copy=False)
273
+ arr = arr_i8.astype(dtype, copy=False)
274
+ obj = tm.box_expected(arr, box, transpose=False)
275
+
276
+ expected = arr_i8.view("timedelta64[D]").astype("timedelta64[ns]")
277
+ if type(scalar_td) is timedelta:
278
+ expected = expected.astype("timedelta64[us]")
279
+
280
+ expected = tm.box_expected(expected, box, transpose=False)
281
+
282
+ result = obj * scalar_td
283
+ tm.assert_equal(result, expected)
284
+
285
+ result = scalar_td * obj
286
+ tm.assert_equal(result, expected)
287
+
288
+ def test_numeric_arr_rdiv_tdscalar(self, three_days, numeric_idx, box_with_array):
289
+ box = box_with_array
290
+
291
+ index = numeric_idx[1:3]
292
+
293
+ expected = TimedeltaIndex(["3 Days", "36 Hours"])
294
+ if isinstance(three_days, np.timedelta64):
295
+ dtype = three_days.dtype
296
+ if dtype < np.dtype("m8[s]"):
297
+ # i.e. resolution is lower -> use lowest supported resolution
298
+ dtype = np.dtype("m8[s]")
299
+ expected = expected.astype(dtype)
300
+ elif type(three_days) is timedelta:
301
+ expected = expected.astype("m8[us]")
302
+ elif isinstance(
303
+ three_days,
304
+ (pd.offsets.Day, pd.offsets.Hour, pd.offsets.Minute, pd.offsets.Second),
305
+ ):
306
+ # closest reso is Second
307
+ expected = expected.astype("m8[s]")
308
+
309
+ index = tm.box_expected(index, box)
310
+ expected = tm.box_expected(expected, box)
311
+
312
+ result = three_days / index
313
+ tm.assert_equal(result, expected)
314
+
315
+ msg = "cannot use operands with types dtype"
316
+ with pytest.raises(TypeError, match=msg):
317
+ index / three_days
318
+
319
+ @pytest.mark.parametrize(
320
+ "other",
321
+ [
322
+ Timedelta(hours=31),
323
+ Timedelta(hours=31).to_pytimedelta(),
324
+ Timedelta(hours=31).to_timedelta64(),
325
+ Timedelta(hours=31).to_timedelta64().astype("m8[h]"),
326
+ np.timedelta64("NaT"),
327
+ np.timedelta64("NaT", "D"),
328
+ pd.offsets.Minute(3),
329
+ pd.offsets.Second(0),
330
+ # GH#28080 numeric+datetimelike should raise; Timestamp used
331
+ # to raise NullFrequencyError but that behavior was removed in 1.0
332
+ pd.Timestamp("2021-01-01", tz="Asia/Tokyo"),
333
+ pd.Timestamp("2021-01-01"),
334
+ pd.Timestamp("2021-01-01").to_pydatetime(),
335
+ pd.Timestamp("2021-01-01", tz="UTC").to_pydatetime(),
336
+ pd.Timestamp("2021-01-01").to_datetime64(),
337
+ np.datetime64("NaT", "ns"),
338
+ pd.NaT,
339
+ ],
340
+ ids=repr,
341
+ )
342
+ def test_add_sub_datetimedeltalike_invalid(
343
+ self, numeric_idx, other, box_with_array
344
+ ):
345
+ box = box_with_array
346
+
347
+ left = tm.box_expected(numeric_idx, box)
348
+ msg = "|".join(
349
+ [
350
+ "unsupported operand type",
351
+ "Addition/subtraction of integers and integer-arrays",
352
+ "Instead of adding/subtracting",
353
+ "cannot use operands with types dtype",
354
+ "Concatenation operation is not implemented for NumPy arrays",
355
+ "Cannot (add|subtract) NaT (to|from) ndarray",
356
+ # pd.array vs np.datetime64 case
357
+ r"operand type\(s\) all returned NotImplemented from __array_ufunc__",
358
+ "can only perform ops with numeric values",
359
+ "cannot subtract DatetimeArray from ndarray",
360
+ # pd.Timedelta(1) + Index([0, 1, 2])
361
+ "Cannot add or subtract Timedelta from integers",
362
+ ]
363
+ )
364
+ assert_invalid_addsub_type(left, other, msg)
365
+
366
+
367
+ # ------------------------------------------------------------------
368
+ # Arithmetic
369
+
370
+
371
+ class TestDivisionByZero:
372
+ def test_div_zero(self, zero, numeric_idx):
373
+ idx = numeric_idx
374
+
375
+ expected = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64)
376
+ # We only adjust for Index, because Series does not yet apply
377
+ # the adjustment correctly.
378
+ expected2 = adjust_negative_zero(zero, expected)
379
+
380
+ result = idx / zero
381
+ tm.assert_index_equal(result, expected2)
382
+ ser_compat = Series(idx).astype("i8") / np.array(zero).astype("i8")
383
+ tm.assert_series_equal(ser_compat, Series(expected))
384
+
385
+ def test_floordiv_zero(self, zero, numeric_idx):
386
+ idx = numeric_idx
387
+
388
+ expected = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64)
389
+ # We only adjust for Index, because Series does not yet apply
390
+ # the adjustment correctly.
391
+ expected2 = adjust_negative_zero(zero, expected)
392
+
393
+ result = idx // zero
394
+ tm.assert_index_equal(result, expected2)
395
+ ser_compat = Series(idx).astype("i8") // np.array(zero).astype("i8")
396
+ tm.assert_series_equal(ser_compat, Series(expected))
397
+
398
+ def test_mod_zero(self, zero, numeric_idx):
399
+ idx = numeric_idx
400
+
401
+ expected = Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64)
402
+ result = idx % zero
403
+ tm.assert_index_equal(result, expected)
404
+ ser_compat = Series(idx).astype("i8") % np.array(zero).astype("i8")
405
+ tm.assert_series_equal(ser_compat, Series(result))
406
+
407
+ def test_divmod_zero(self, zero, numeric_idx):
408
+ idx = numeric_idx
409
+
410
+ exleft = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64)
411
+ exright = Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64)
412
+ exleft = adjust_negative_zero(zero, exleft)
413
+
414
+ result = divmod(idx, zero)
415
+ tm.assert_index_equal(result[0], exleft)
416
+ tm.assert_index_equal(result[1], exright)
417
+
418
+ @pytest.mark.parametrize("op", [operator.truediv, operator.floordiv])
419
+ def test_div_negative_zero(self, zero, numeric_idx, op):
420
+ # Check that -1 / -0.0 returns np.inf, not -np.inf
421
+ if numeric_idx.dtype == np.uint64:
422
+ pytest.skip(f"Div by negative 0 not relevant for {numeric_idx.dtype}")
423
+ idx = numeric_idx - 3
424
+
425
+ expected = Index([-np.inf, -np.inf, -np.inf, np.nan, np.inf], dtype=np.float64)
426
+ expected = adjust_negative_zero(zero, expected)
427
+
428
+ result = op(idx, zero)
429
+ tm.assert_index_equal(result, expected)
430
+
431
+ # ------------------------------------------------------------------
432
+
433
+ @pytest.mark.parametrize("dtype1", [np.int64, np.float64, np.uint64])
434
+ def test_ser_div_ser(
435
+ self,
436
+ switch_numexpr_min_elements,
437
+ dtype1,
438
+ any_real_numpy_dtype,
439
+ ):
440
+ # no longer do integer div for any ops, but deal with the 0's
441
+ dtype2 = any_real_numpy_dtype
442
+
443
+ first = Series([3, 4, 5, 8], name="first").astype(dtype1)
444
+ second = Series([0, 0, 0, 3], name="second").astype(dtype2)
445
+
446
+ with np.errstate(all="ignore"):
447
+ expected = Series(
448
+ first.values.astype(np.float64) / second.values,
449
+ dtype="float64",
450
+ name=None,
451
+ )
452
+ expected.iloc[0:3] = np.inf
453
+ if first.dtype == "int64" and second.dtype == "float32":
454
+ # when using numexpr, the casting rules are slightly different
455
+ # and int64/float32 combo results in float32 instead of float64
456
+ if expr.USE_NUMEXPR and switch_numexpr_min_elements == 0:
457
+ expected = expected.astype("float32")
458
+
459
+ result = first / second
460
+ tm.assert_series_equal(result, expected)
461
+ assert not result.equals(second / first)
462
+
463
+ @pytest.mark.parametrize("dtype1", [np.int64, np.float64, np.uint64])
464
+ def test_ser_divmod_zero(self, dtype1, any_real_numpy_dtype):
465
+ # GH#26987
466
+ dtype2 = any_real_numpy_dtype
467
+ left = Series([1, 1]).astype(dtype1)
468
+ right = Series([0, 2]).astype(dtype2)
469
+
470
+ # GH#27321 pandas convention is to set 1 // 0 to np.inf, as opposed
471
+ # to numpy which sets to np.nan; patch `expected[0]` below
472
+ expected = left // right, left % right
473
+ expected = list(expected)
474
+ expected[0] = expected[0].astype(np.float64)
475
+ expected[0][0] = np.inf
476
+ result = divmod(left, right)
477
+
478
+ tm.assert_series_equal(result[0], expected[0])
479
+ tm.assert_series_equal(result[1], expected[1])
480
+
481
+ # rdivmod case
482
+ result = divmod(left.values, right)
483
+ tm.assert_series_equal(result[0], expected[0])
484
+ tm.assert_series_equal(result[1], expected[1])
485
+
486
+ def test_ser_divmod_inf(self):
487
+ left = Series([np.inf, 1.0])
488
+ right = Series([np.inf, 2.0])
489
+
490
+ expected = left // right, left % right
491
+ result = divmod(left, right)
492
+
493
+ tm.assert_series_equal(result[0], expected[0])
494
+ tm.assert_series_equal(result[1], expected[1])
495
+
496
+ # rdivmod case
497
+ result = divmod(left.values, right)
498
+ tm.assert_series_equal(result[0], expected[0])
499
+ tm.assert_series_equal(result[1], expected[1])
500
+
501
+ def test_rdiv_zero_compat(self):
502
+ # GH#8674
503
+ zero_array = np.array([0] * 5)
504
+ data = np.random.default_rng(2).standard_normal(5)
505
+ expected = Series([0.0] * 5)
506
+
507
+ result = zero_array / Series(data)
508
+ tm.assert_series_equal(result, expected)
509
+
510
+ result = Series(zero_array) / data
511
+ tm.assert_series_equal(result, expected)
512
+
513
+ result = Series(zero_array) / Series(data)
514
+ tm.assert_series_equal(result, expected)
515
+
516
+ def test_div_zero_inf_signs(self):
517
+ # GH#9144, inf signing
518
+ ser = Series([-1, 0, 1], name="first")
519
+ expected = Series([-np.inf, np.nan, np.inf], name="first")
520
+
521
+ result = ser / 0
522
+ tm.assert_series_equal(result, expected)
523
+
524
+ def test_rdiv_zero(self):
525
+ # GH#9144
526
+ ser = Series([-1, 0, 1], name="first")
527
+ expected = Series([0.0, np.nan, 0.0], name="first")
528
+
529
+ result = 0 / ser
530
+ tm.assert_series_equal(result, expected)
531
+
532
+ def test_floordiv_div(self):
533
+ # GH#9144
534
+ ser = Series([-1, 0, 1], name="first")
535
+
536
+ result = ser // 0
537
+ expected = Series([-np.inf, np.nan, np.inf], name="first")
538
+ tm.assert_series_equal(result, expected)
539
+
540
+ def test_df_div_zero_df(self):
541
+ # integer div, but deal with the 0's (GH#9144)
542
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
543
+ result = df / df
544
+
545
+ first = Series([1.0, 1.0, 1.0, 1.0])
546
+ second = Series([np.nan, np.nan, np.nan, 1])
547
+ expected = pd.DataFrame({"first": first, "second": second})
548
+ tm.assert_frame_equal(result, expected)
549
+
550
+ def test_df_div_zero_array(self):
551
+ # integer div, but deal with the 0's (GH#9144)
552
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
553
+
554
+ first = Series([1.0, 1.0, 1.0, 1.0])
555
+ second = Series([np.nan, np.nan, np.nan, 1])
556
+ expected = pd.DataFrame({"first": first, "second": second})
557
+
558
+ with np.errstate(all="ignore"):
559
+ arr = df.values.astype("float") / df.values
560
+ result = pd.DataFrame(arr, index=df.index, columns=df.columns)
561
+ tm.assert_frame_equal(result, expected)
562
+
563
+ def test_df_div_zero_int(self):
564
+ # integer div, but deal with the 0's (GH#9144)
565
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
566
+
567
+ result = df / 0
568
+ expected = pd.DataFrame(np.inf, index=df.index, columns=df.columns)
569
+ expected.iloc[0:3, 1] = np.nan
570
+ tm.assert_frame_equal(result, expected)
571
+
572
+ # numpy has a slightly different (wrong) treatment
573
+ with np.errstate(all="ignore"):
574
+ arr = df.values.astype("float64") / 0
575
+ result2 = pd.DataFrame(arr, index=df.index, columns=df.columns)
576
+ tm.assert_frame_equal(result2, expected)
577
+
578
+ def test_df_div_zero_series_does_not_commute(self):
579
+ # integer div, but deal with the 0's (GH#9144)
580
+ df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
581
+ ser = df[0]
582
+ res = ser / df
583
+ res2 = df / ser
584
+ assert not res.fillna(0).equals(res2.fillna(0))
585
+
586
+ # ------------------------------------------------------------------
587
+ # Mod By Zero
588
+
589
+ def test_df_mod_zero_df(self, using_array_manager):
590
+ # GH#3590, modulo as ints
591
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
592
+ # this is technically wrong, as the integer portion is coerced to float
593
+ first = Series([0, 0, 0, 0])
594
+ if not using_array_manager:
595
+ # INFO(ArrayManager) BlockManager doesn't preserve dtype per column
596
+ # while ArrayManager performs op column-wisedoes and thus preserves
597
+ # dtype if possible
598
+ first = first.astype("float64")
599
+ second = Series([np.nan, np.nan, np.nan, 0])
600
+ expected = pd.DataFrame({"first": first, "second": second})
601
+ result = df % df
602
+ tm.assert_frame_equal(result, expected)
603
+
604
+ # GH#38939 If we dont pass copy=False, df is consolidated and
605
+ # result["first"] is float64 instead of int64
606
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]}, copy=False)
607
+ first = Series([0, 0, 0, 0], dtype="int64")
608
+ second = Series([np.nan, np.nan, np.nan, 0])
609
+ expected = pd.DataFrame({"first": first, "second": second})
610
+ result = df % df
611
+ tm.assert_frame_equal(result, expected)
612
+
613
+ def test_df_mod_zero_array(self):
614
+ # GH#3590, modulo as ints
615
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
616
+
617
+ # this is technically wrong, as the integer portion is coerced to float
618
+ # ###
619
+ first = Series([0, 0, 0, 0], dtype="float64")
620
+ second = Series([np.nan, np.nan, np.nan, 0])
621
+ expected = pd.DataFrame({"first": first, "second": second})
622
+
623
+ # numpy has a slightly different (wrong) treatment
624
+ with np.errstate(all="ignore"):
625
+ arr = df.values % df.values
626
+ result2 = pd.DataFrame(arr, index=df.index, columns=df.columns, dtype="float64")
627
+ result2.iloc[0:3, 1] = np.nan
628
+ tm.assert_frame_equal(result2, expected)
629
+
630
+ def test_df_mod_zero_int(self):
631
+ # GH#3590, modulo as ints
632
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
633
+
634
+ result = df % 0
635
+ expected = pd.DataFrame(np.nan, index=df.index, columns=df.columns)
636
+ tm.assert_frame_equal(result, expected)
637
+
638
+ # numpy has a slightly different (wrong) treatment
639
+ with np.errstate(all="ignore"):
640
+ arr = df.values.astype("float64") % 0
641
+ result2 = pd.DataFrame(arr, index=df.index, columns=df.columns)
642
+ tm.assert_frame_equal(result2, expected)
643
+
644
+ def test_df_mod_zero_series_does_not_commute(self):
645
+ # GH#3590, modulo as ints
646
+ # not commutative with series
647
+ df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
648
+ ser = df[0]
649
+ res = ser % df
650
+ res2 = df % ser
651
+ assert not res.fillna(0).equals(res2.fillna(0))
652
+
653
+
654
+ class TestMultiplicationDivision:
655
+ # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__
656
+ # for non-timestamp/timedelta/period dtypes
657
+
658
+ def test_divide_decimal(self, box_with_array):
659
+ # resolves issue GH#9787
660
+ box = box_with_array
661
+ ser = Series([Decimal(10)])
662
+ expected = Series([Decimal(5)])
663
+
664
+ ser = tm.box_expected(ser, box)
665
+ expected = tm.box_expected(expected, box)
666
+
667
+ result = ser / Decimal(2)
668
+
669
+ tm.assert_equal(result, expected)
670
+
671
+ result = ser // Decimal(2)
672
+ tm.assert_equal(result, expected)
673
+
674
+ def test_div_equiv_binop(self):
675
+ # Test Series.div as well as Series.__div__
676
+ # float/integer issue
677
+ # GH#7785
678
+ first = Series([1, 0], name="first")
679
+ second = Series([-0.01, -0.02], name="second")
680
+ expected = Series([-0.01, -np.inf])
681
+
682
+ result = second.div(first)
683
+ tm.assert_series_equal(result, expected, check_names=False)
684
+
685
+ result = second / first
686
+ tm.assert_series_equal(result, expected)
687
+
688
+ def test_div_int(self, numeric_idx):
689
+ idx = numeric_idx
690
+ result = idx / 1
691
+ expected = idx.astype("float64")
692
+ tm.assert_index_equal(result, expected)
693
+
694
+ result = idx / 2
695
+ expected = Index(idx.values / 2)
696
+ tm.assert_index_equal(result, expected)
697
+
698
+ @pytest.mark.parametrize("op", [operator.mul, ops.rmul, operator.floordiv])
699
+ def test_mul_int_identity(self, op, numeric_idx, box_with_array):
700
+ idx = numeric_idx
701
+ idx = tm.box_expected(idx, box_with_array)
702
+
703
+ result = op(idx, 1)
704
+ tm.assert_equal(result, idx)
705
+
706
+ def test_mul_int_array(self, numeric_idx):
707
+ idx = numeric_idx
708
+ didx = idx * idx
709
+
710
+ result = idx * np.array(5, dtype="int64")
711
+ tm.assert_index_equal(result, idx * 5)
712
+
713
+ arr_dtype = "uint64" if idx.dtype == np.uint64 else "int64"
714
+ result = idx * np.arange(5, dtype=arr_dtype)
715
+ tm.assert_index_equal(result, didx)
716
+
717
+ def test_mul_int_series(self, numeric_idx):
718
+ idx = numeric_idx
719
+ didx = idx * idx
720
+
721
+ arr_dtype = "uint64" if idx.dtype == np.uint64 else "int64"
722
+ result = idx * Series(np.arange(5, dtype=arr_dtype))
723
+ tm.assert_series_equal(result, Series(didx))
724
+
725
+ def test_mul_float_series(self, numeric_idx):
726
+ idx = numeric_idx
727
+ rng5 = np.arange(5, dtype="float64")
728
+
729
+ result = idx * Series(rng5 + 0.1)
730
+ expected = Series(rng5 * (rng5 + 0.1))
731
+ tm.assert_series_equal(result, expected)
732
+
733
+ def test_mul_index(self, numeric_idx):
734
+ idx = numeric_idx
735
+
736
+ result = idx * idx
737
+ tm.assert_index_equal(result, idx**2)
738
+
739
+ def test_mul_datelike_raises(self, numeric_idx):
740
+ idx = numeric_idx
741
+ msg = "cannot perform __rmul__ with this index type"
742
+ with pytest.raises(TypeError, match=msg):
743
+ idx * date_range("20130101", periods=5)
744
+
745
+ def test_mul_size_mismatch_raises(self, numeric_idx):
746
+ idx = numeric_idx
747
+ msg = "operands could not be broadcast together"
748
+ with pytest.raises(ValueError, match=msg):
749
+ idx * idx[0:3]
750
+ with pytest.raises(ValueError, match=msg):
751
+ idx * np.array([1, 2])
752
+
753
+ @pytest.mark.parametrize("op", [operator.pow, ops.rpow])
754
+ def test_pow_float(self, op, numeric_idx, box_with_array):
755
+ # test power calculations both ways, GH#14973
756
+ box = box_with_array
757
+ idx = numeric_idx
758
+ expected = Index(op(idx.values, 2.0))
759
+
760
+ idx = tm.box_expected(idx, box)
761
+ expected = tm.box_expected(expected, box)
762
+
763
+ result = op(idx, 2.0)
764
+ tm.assert_equal(result, expected)
765
+
766
+ def test_modulo(self, numeric_idx, box_with_array):
767
+ # GH#9244
768
+ box = box_with_array
769
+ idx = numeric_idx
770
+ expected = Index(idx.values % 2)
771
+
772
+ idx = tm.box_expected(idx, box)
773
+ expected = tm.box_expected(expected, box)
774
+
775
+ result = idx % 2
776
+ tm.assert_equal(result, expected)
777
+
778
+ def test_divmod_scalar(self, numeric_idx):
779
+ idx = numeric_idx
780
+
781
+ result = divmod(idx, 2)
782
+ with np.errstate(all="ignore"):
783
+ div, mod = divmod(idx.values, 2)
784
+
785
+ expected = Index(div), Index(mod)
786
+ for r, e in zip(result, expected):
787
+ tm.assert_index_equal(r, e)
788
+
789
+ def test_divmod_ndarray(self, numeric_idx):
790
+ idx = numeric_idx
791
+ other = np.ones(idx.values.shape, dtype=idx.values.dtype) * 2
792
+
793
+ result = divmod(idx, other)
794
+ with np.errstate(all="ignore"):
795
+ div, mod = divmod(idx.values, other)
796
+
797
+ expected = Index(div), Index(mod)
798
+ for r, e in zip(result, expected):
799
+ tm.assert_index_equal(r, e)
800
+
801
+ def test_divmod_series(self, numeric_idx):
802
+ idx = numeric_idx
803
+ other = np.ones(idx.values.shape, dtype=idx.values.dtype) * 2
804
+
805
+ result = divmod(idx, Series(other))
806
+ with np.errstate(all="ignore"):
807
+ div, mod = divmod(idx.values, other)
808
+
809
+ expected = Series(div), Series(mod)
810
+ for r, e in zip(result, expected):
811
+ tm.assert_series_equal(r, e)
812
+
813
+ @pytest.mark.parametrize("other", [np.nan, 7, -23, 2.718, -3.14, np.inf])
814
+ def test_ops_np_scalar(self, other):
815
+ vals = np.random.default_rng(2).standard_normal((5, 3))
816
+ f = lambda x: pd.DataFrame(
817
+ x, index=list("ABCDE"), columns=["jim", "joe", "jolie"]
818
+ )
819
+
820
+ df = f(vals)
821
+
822
+ tm.assert_frame_equal(df / np.array(other), f(vals / other))
823
+ tm.assert_frame_equal(np.array(other) * df, f(vals * other))
824
+ tm.assert_frame_equal(df + np.array(other), f(vals + other))
825
+ tm.assert_frame_equal(np.array(other) - df, f(other - vals))
826
+
827
+ # TODO: This came from series.test.test_operators, needs cleanup
828
+ def test_operators_frame(self):
829
+ # rpow does not work with DataFrame
830
+ ts = Series(
831
+ np.arange(10, dtype=np.float64),
832
+ index=date_range("2020-01-01", periods=10),
833
+ name="ts",
834
+ )
835
+ ts.name = "ts"
836
+
837
+ df = pd.DataFrame({"A": ts})
838
+
839
+ tm.assert_series_equal(ts + ts, ts + df["A"], check_names=False)
840
+ tm.assert_series_equal(ts**ts, ts ** df["A"], check_names=False)
841
+ tm.assert_series_equal(ts < ts, ts < df["A"], check_names=False)
842
+ tm.assert_series_equal(ts / ts, ts / df["A"], check_names=False)
843
+
844
+ # TODO: this came from tests.series.test_analytics, needs cleanup and
845
+ # de-duplication with test_modulo above
846
+ def test_modulo2(self):
847
+ with np.errstate(all="ignore"):
848
+ # GH#3590, modulo as ints
849
+ p = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
850
+ result = p["first"] % p["second"]
851
+ expected = Series(p["first"].values % p["second"].values, dtype="float64")
852
+ expected.iloc[0:3] = np.nan
853
+ tm.assert_series_equal(result, expected)
854
+
855
+ result = p["first"] % 0
856
+ expected = Series(np.nan, index=p.index, name="first")
857
+ tm.assert_series_equal(result, expected)
858
+
859
+ p = p.astype("float64")
860
+ result = p["first"] % p["second"]
861
+ expected = Series(p["first"].values % p["second"].values)
862
+ tm.assert_series_equal(result, expected)
863
+
864
+ p = p.astype("float64")
865
+ result = p["first"] % p["second"]
866
+ result2 = p["second"] % p["first"]
867
+ assert not result.equals(result2)
868
+
869
+ def test_modulo_zero_int(self):
870
+ # GH#9144
871
+ with np.errstate(all="ignore"):
872
+ s = Series([0, 1])
873
+
874
+ result = s % 0
875
+ expected = Series([np.nan, np.nan])
876
+ tm.assert_series_equal(result, expected)
877
+
878
+ result = 0 % s
879
+ expected = Series([np.nan, 0.0])
880
+ tm.assert_series_equal(result, expected)
881
+
882
+
883
+ class TestAdditionSubtraction:
884
+ # __add__, __sub__, __radd__, __rsub__, __iadd__, __isub__
885
+ # for non-timestamp/timedelta/period dtypes
886
+
887
+ @pytest.mark.parametrize(
888
+ "first, second, expected",
889
+ [
890
+ (
891
+ Series([1, 2, 3], index=list("ABC"), name="x"),
892
+ Series([2, 2, 2], index=list("ABD"), name="x"),
893
+ Series([3.0, 4.0, np.nan, np.nan], index=list("ABCD"), name="x"),
894
+ ),
895
+ (
896
+ Series([1, 2, 3], index=list("ABC"), name="x"),
897
+ Series([2, 2, 2, 2], index=list("ABCD"), name="x"),
898
+ Series([3, 4, 5, np.nan], index=list("ABCD"), name="x"),
899
+ ),
900
+ ],
901
+ )
902
+ def test_add_series(self, first, second, expected):
903
+ # GH#1134
904
+ tm.assert_series_equal(first + second, expected)
905
+ tm.assert_series_equal(second + first, expected)
906
+
907
+ @pytest.mark.parametrize(
908
+ "first, second, expected",
909
+ [
910
+ (
911
+ pd.DataFrame({"x": [1, 2, 3]}, index=list("ABC")),
912
+ pd.DataFrame({"x": [2, 2, 2]}, index=list("ABD")),
913
+ pd.DataFrame({"x": [3.0, 4.0, np.nan, np.nan]}, index=list("ABCD")),
914
+ ),
915
+ (
916
+ pd.DataFrame({"x": [1, 2, 3]}, index=list("ABC")),
917
+ pd.DataFrame({"x": [2, 2, 2, 2]}, index=list("ABCD")),
918
+ pd.DataFrame({"x": [3, 4, 5, np.nan]}, index=list("ABCD")),
919
+ ),
920
+ ],
921
+ )
922
+ def test_add_frames(self, first, second, expected):
923
+ # GH#1134
924
+ tm.assert_frame_equal(first + second, expected)
925
+ tm.assert_frame_equal(second + first, expected)
926
+
927
+ # TODO: This came from series.test.test_operators, needs cleanup
928
+ def test_series_frame_radd_bug(self, fixed_now_ts):
929
+ # GH#353
930
+ vals = Series([str(i) for i in range(5)])
931
+ result = "foo_" + vals
932
+ expected = vals.map(lambda x: "foo_" + x)
933
+ tm.assert_series_equal(result, expected)
934
+
935
+ frame = pd.DataFrame({"vals": vals})
936
+ result = "foo_" + frame
937
+ expected = pd.DataFrame({"vals": vals.map(lambda x: "foo_" + x)})
938
+ tm.assert_frame_equal(result, expected)
939
+
940
+ ts = Series(
941
+ np.arange(10, dtype=np.float64),
942
+ index=date_range("2020-01-01", periods=10),
943
+ name="ts",
944
+ )
945
+
946
+ # really raise this time
947
+ fix_now = fixed_now_ts.to_pydatetime()
948
+ msg = "|".join(
949
+ [
950
+ "unsupported operand type",
951
+ # wrong error message, see https://github.com/numpy/numpy/issues/18832
952
+ "Concatenation operation",
953
+ ]
954
+ )
955
+ with pytest.raises(TypeError, match=msg):
956
+ fix_now + ts
957
+
958
+ with pytest.raises(TypeError, match=msg):
959
+ ts + fix_now
960
+
961
+ # TODO: This came from series.test.test_operators, needs cleanup
962
+ def test_datetime64_with_index(self):
963
+ # arithmetic integer ops with an index
964
+ ser = Series(np.random.default_rng(2).standard_normal(5))
965
+ expected = ser - ser.index.to_series()
966
+ result = ser - ser.index
967
+ tm.assert_series_equal(result, expected)
968
+
969
+ # GH#4629
970
+ # arithmetic datetime64 ops with an index
971
+ ser = Series(
972
+ date_range("20130101", periods=5),
973
+ index=date_range("20130101", periods=5),
974
+ )
975
+ expected = ser - ser.index.to_series()
976
+ result = ser - ser.index
977
+ tm.assert_series_equal(result, expected)
978
+
979
+ msg = "cannot subtract PeriodArray from DatetimeArray"
980
+ with pytest.raises(TypeError, match=msg):
981
+ # GH#18850
982
+ result = ser - ser.index.to_period()
983
+
984
+ df = pd.DataFrame(
985
+ np.random.default_rng(2).standard_normal((5, 2)),
986
+ index=date_range("20130101", periods=5),
987
+ )
988
+ df["date"] = pd.Timestamp("20130102")
989
+ df["expected"] = df["date"] - df.index.to_series()
990
+ df["result"] = df["date"] - df.index
991
+ tm.assert_series_equal(df["result"], df["expected"], check_names=False)
992
+
993
+ # TODO: taken from tests.frame.test_operators, needs cleanup
994
+ def test_frame_operators(self, float_frame):
995
+ frame = float_frame
996
+
997
+ garbage = np.random.default_rng(2).random(4)
998
+ colSeries = Series(garbage, index=np.array(frame.columns))
999
+
1000
+ idSum = frame + frame
1001
+ seriesSum = frame + colSeries
1002
+
1003
+ for col, series in idSum.items():
1004
+ for idx, val in series.items():
1005
+ origVal = frame[col][idx] * 2
1006
+ if not np.isnan(val):
1007
+ assert val == origVal
1008
+ else:
1009
+ assert np.isnan(origVal)
1010
+
1011
+ for col, series in seriesSum.items():
1012
+ for idx, val in series.items():
1013
+ origVal = frame[col][idx] + colSeries[col]
1014
+ if not np.isnan(val):
1015
+ assert val == origVal
1016
+ else:
1017
+ assert np.isnan(origVal)
1018
+
1019
+ def test_frame_operators_col_align(self, float_frame):
1020
+ frame2 = pd.DataFrame(float_frame, columns=["D", "C", "B", "A"])
1021
+ added = frame2 + frame2
1022
+ expected = frame2 * 2
1023
+ tm.assert_frame_equal(added, expected)
1024
+
1025
+ def test_frame_operators_none_to_nan(self):
1026
+ df = pd.DataFrame({"a": ["a", None, "b"]})
1027
+ tm.assert_frame_equal(df + df, pd.DataFrame({"a": ["aa", np.nan, "bb"]}))
1028
+
1029
+ @pytest.mark.parametrize("dtype", ("float", "int64"))
1030
+ def test_frame_operators_empty_like(self, dtype):
1031
+ # Test for issue #10181
1032
+ frames = [
1033
+ pd.DataFrame(dtype=dtype),
1034
+ pd.DataFrame(columns=["A"], dtype=dtype),
1035
+ pd.DataFrame(index=[0], dtype=dtype),
1036
+ ]
1037
+ for df in frames:
1038
+ assert (df + df).equals(df)
1039
+ tm.assert_frame_equal(df + df, df)
1040
+
1041
+ @pytest.mark.parametrize(
1042
+ "func",
1043
+ [lambda x: x * 2, lambda x: x[::2], lambda x: 5],
1044
+ ids=["multiply", "slice", "constant"],
1045
+ )
1046
+ def test_series_operators_arithmetic(self, all_arithmetic_functions, func):
1047
+ op = all_arithmetic_functions
1048
+ series = Series(
1049
+ np.arange(10, dtype=np.float64),
1050
+ index=date_range("2020-01-01", periods=10),
1051
+ name="ts",
1052
+ )
1053
+ other = func(series)
1054
+ compare_op(series, other, op)
1055
+
1056
+ @pytest.mark.parametrize(
1057
+ "func", [lambda x: x + 1, lambda x: 5], ids=["add", "constant"]
1058
+ )
1059
+ def test_series_operators_compare(self, comparison_op, func):
1060
+ op = comparison_op
1061
+ series = Series(
1062
+ np.arange(10, dtype=np.float64),
1063
+ index=date_range("2020-01-01", periods=10),
1064
+ name="ts",
1065
+ )
1066
+ other = func(series)
1067
+ compare_op(series, other, op)
1068
+
1069
+ @pytest.mark.parametrize(
1070
+ "func",
1071
+ [lambda x: x * 2, lambda x: x[::2], lambda x: 5],
1072
+ ids=["multiply", "slice", "constant"],
1073
+ )
1074
+ def test_divmod(self, func):
1075
+ series = Series(
1076
+ np.arange(10, dtype=np.float64),
1077
+ index=date_range("2020-01-01", periods=10),
1078
+ name="ts",
1079
+ )
1080
+ other = func(series)
1081
+ results = divmod(series, other)
1082
+ if isinstance(other, abc.Iterable) and len(series) != len(other):
1083
+ # if the lengths don't match, this is the test where we use
1084
+ # `tser[::2]`. Pad every other value in `other_np` with nan.
1085
+ other_np = []
1086
+ for n in other:
1087
+ other_np.append(n)
1088
+ other_np.append(np.nan)
1089
+ else:
1090
+ other_np = other
1091
+ other_np = np.asarray(other_np)
1092
+ with np.errstate(all="ignore"):
1093
+ expecteds = divmod(series.values, np.asarray(other_np))
1094
+
1095
+ for result, expected in zip(results, expecteds):
1096
+ # check the values, name, and index separately
1097
+ tm.assert_almost_equal(np.asarray(result), expected)
1098
+
1099
+ assert result.name == series.name
1100
+ tm.assert_index_equal(result.index, series.index._with_freq(None))
1101
+
1102
+ def test_series_divmod_zero(self):
1103
+ # Check that divmod uses pandas convention for division by zero,
1104
+ # which does not match numpy.
1105
+ # pandas convention has
1106
+ # 1/0 == np.inf
1107
+ # -1/0 == -np.inf
1108
+ # 1/-0.0 == -np.inf
1109
+ # -1/-0.0 == np.inf
1110
+ tser = Series(
1111
+ np.arange(1, 11, dtype=np.float64),
1112
+ index=date_range("2020-01-01", periods=10),
1113
+ name="ts",
1114
+ )
1115
+ other = tser * 0
1116
+
1117
+ result = divmod(tser, other)
1118
+ exp1 = Series([np.inf] * len(tser), index=tser.index, name="ts")
1119
+ exp2 = Series([np.nan] * len(tser), index=tser.index, name="ts")
1120
+ tm.assert_series_equal(result[0], exp1)
1121
+ tm.assert_series_equal(result[1], exp2)
1122
+
1123
+
1124
+ class TestUFuncCompat:
1125
+ # TODO: add more dtypes
1126
+ @pytest.mark.parametrize("holder", [Index, RangeIndex, Series])
1127
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
1128
+ def test_ufunc_compat(self, holder, dtype):
1129
+ box = Series if holder is Series else Index
1130
+
1131
+ if holder is RangeIndex:
1132
+ if dtype != np.int64:
1133
+ pytest.skip(f"dtype {dtype} not relevant for RangeIndex")
1134
+ idx = RangeIndex(0, 5, name="foo")
1135
+ else:
1136
+ idx = holder(np.arange(5, dtype=dtype), name="foo")
1137
+ result = np.sin(idx)
1138
+ expected = box(np.sin(np.arange(5, dtype=dtype)), name="foo")
1139
+ tm.assert_equal(result, expected)
1140
+
1141
+ # TODO: add more dtypes
1142
+ @pytest.mark.parametrize("holder", [Index, Series])
1143
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
1144
+ def test_ufunc_coercions(self, holder, dtype):
1145
+ idx = holder([1, 2, 3, 4, 5], dtype=dtype, name="x")
1146
+ box = Series if holder is Series else Index
1147
+
1148
+ result = np.sqrt(idx)
1149
+ assert result.dtype == "f8" and isinstance(result, box)
1150
+ exp = Index(np.sqrt(np.array([1, 2, 3, 4, 5], dtype=np.float64)), name="x")
1151
+ exp = tm.box_expected(exp, box)
1152
+ tm.assert_equal(result, exp)
1153
+
1154
+ result = np.divide(idx, 2.0)
1155
+ assert result.dtype == "f8" and isinstance(result, box)
1156
+ exp = Index([0.5, 1.0, 1.5, 2.0, 2.5], dtype=np.float64, name="x")
1157
+ exp = tm.box_expected(exp, box)
1158
+ tm.assert_equal(result, exp)
1159
+
1160
+ # _evaluate_numeric_binop
1161
+ result = idx + 2.0
1162
+ assert result.dtype == "f8" and isinstance(result, box)
1163
+ exp = Index([3.0, 4.0, 5.0, 6.0, 7.0], dtype=np.float64, name="x")
1164
+ exp = tm.box_expected(exp, box)
1165
+ tm.assert_equal(result, exp)
1166
+
1167
+ result = idx - 2.0
1168
+ assert result.dtype == "f8" and isinstance(result, box)
1169
+ exp = Index([-1.0, 0.0, 1.0, 2.0, 3.0], dtype=np.float64, name="x")
1170
+ exp = tm.box_expected(exp, box)
1171
+ tm.assert_equal(result, exp)
1172
+
1173
+ result = idx * 1.0
1174
+ assert result.dtype == "f8" and isinstance(result, box)
1175
+ exp = Index([1.0, 2.0, 3.0, 4.0, 5.0], dtype=np.float64, name="x")
1176
+ exp = tm.box_expected(exp, box)
1177
+ tm.assert_equal(result, exp)
1178
+
1179
+ result = idx / 2.0
1180
+ assert result.dtype == "f8" and isinstance(result, box)
1181
+ exp = Index([0.5, 1.0, 1.5, 2.0, 2.5], dtype=np.float64, name="x")
1182
+ exp = tm.box_expected(exp, box)
1183
+ tm.assert_equal(result, exp)
1184
+
1185
+ # TODO: add more dtypes
1186
+ @pytest.mark.parametrize("holder", [Index, Series])
1187
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
1188
+ def test_ufunc_multiple_return_values(self, holder, dtype):
1189
+ obj = holder([1, 2, 3], dtype=dtype, name="x")
1190
+ box = Series if holder is Series else Index
1191
+
1192
+ result = np.modf(obj)
1193
+ assert isinstance(result, tuple)
1194
+ exp1 = Index([0.0, 0.0, 0.0], dtype=np.float64, name="x")
1195
+ exp2 = Index([1.0, 2.0, 3.0], dtype=np.float64, name="x")
1196
+ tm.assert_equal(result[0], tm.box_expected(exp1, box))
1197
+ tm.assert_equal(result[1], tm.box_expected(exp2, box))
1198
+
1199
+ def test_ufunc_at(self):
1200
+ s = Series([0, 1, 2], index=[1, 2, 3], name="x")
1201
+ np.add.at(s, [0, 2], 10)
1202
+ expected = Series([10, 1, 12], index=[1, 2, 3], name="x")
1203
+ tm.assert_series_equal(s, expected)
1204
+
1205
+
1206
+ class TestObjectDtypeEquivalence:
1207
+ # Tests that arithmetic operations match operations executed elementwise
1208
+
1209
+ @pytest.mark.parametrize("dtype", [None, object])
1210
+ def test_numarr_with_dtype_add_nan(self, dtype, box_with_array):
1211
+ box = box_with_array
1212
+ ser = Series([1, 2, 3], dtype=dtype)
1213
+ expected = Series([np.nan, np.nan, np.nan], dtype=dtype)
1214
+
1215
+ ser = tm.box_expected(ser, box)
1216
+ expected = tm.box_expected(expected, box)
1217
+
1218
+ result = np.nan + ser
1219
+ tm.assert_equal(result, expected)
1220
+
1221
+ result = ser + np.nan
1222
+ tm.assert_equal(result, expected)
1223
+
1224
+ @pytest.mark.parametrize("dtype", [None, object])
1225
+ def test_numarr_with_dtype_add_int(self, dtype, box_with_array):
1226
+ box = box_with_array
1227
+ ser = Series([1, 2, 3], dtype=dtype)
1228
+ expected = Series([2, 3, 4], dtype=dtype)
1229
+
1230
+ ser = tm.box_expected(ser, box)
1231
+ expected = tm.box_expected(expected, box)
1232
+
1233
+ result = 1 + ser
1234
+ tm.assert_equal(result, expected)
1235
+
1236
+ result = ser + 1
1237
+ tm.assert_equal(result, expected)
1238
+
1239
+ # TODO: moved from tests.series.test_operators; needs cleanup
1240
+ @pytest.mark.parametrize(
1241
+ "op",
1242
+ [operator.add, operator.sub, operator.mul, operator.truediv, operator.floordiv],
1243
+ )
1244
+ def test_operators_reverse_object(self, op):
1245
+ # GH#56
1246
+ arr = Series(
1247
+ np.random.default_rng(2).standard_normal(10),
1248
+ index=np.arange(10),
1249
+ dtype=object,
1250
+ )
1251
+
1252
+ result = op(1.0, arr)
1253
+ expected = op(1.0, arr.astype(float))
1254
+ tm.assert_series_equal(result.astype(float), expected)
1255
+
1256
+
1257
+ class TestNumericArithmeticUnsorted:
1258
+ # Tests in this class have been moved from type-specific test modules
1259
+ # but not yet sorted, parametrized, and de-duplicated
1260
+ @pytest.mark.parametrize(
1261
+ "op",
1262
+ [
1263
+ operator.add,
1264
+ operator.sub,
1265
+ operator.mul,
1266
+ operator.floordiv,
1267
+ operator.truediv,
1268
+ ],
1269
+ )
1270
+ @pytest.mark.parametrize(
1271
+ "idx1",
1272
+ [
1273
+ RangeIndex(0, 10, 1),
1274
+ RangeIndex(0, 20, 2),
1275
+ RangeIndex(-10, 10, 2),
1276
+ RangeIndex(5, -5, -1),
1277
+ ],
1278
+ )
1279
+ @pytest.mark.parametrize(
1280
+ "idx2",
1281
+ [
1282
+ RangeIndex(0, 10, 1),
1283
+ RangeIndex(0, 20, 2),
1284
+ RangeIndex(-10, 10, 2),
1285
+ RangeIndex(5, -5, -1),
1286
+ ],
1287
+ )
1288
+ def test_binops_index(self, op, idx1, idx2):
1289
+ idx1 = idx1._rename("foo")
1290
+ idx2 = idx2._rename("bar")
1291
+ result = op(idx1, idx2)
1292
+ expected = op(Index(idx1.to_numpy()), Index(idx2.to_numpy()))
1293
+ tm.assert_index_equal(result, expected, exact="equiv")
1294
+
1295
+ @pytest.mark.parametrize(
1296
+ "op",
1297
+ [
1298
+ operator.add,
1299
+ operator.sub,
1300
+ operator.mul,
1301
+ operator.floordiv,
1302
+ operator.truediv,
1303
+ ],
1304
+ )
1305
+ @pytest.mark.parametrize(
1306
+ "idx",
1307
+ [
1308
+ RangeIndex(0, 10, 1),
1309
+ RangeIndex(0, 20, 2),
1310
+ RangeIndex(-10, 10, 2),
1311
+ RangeIndex(5, -5, -1),
1312
+ ],
1313
+ )
1314
+ @pytest.mark.parametrize("scalar", [-1, 1, 2])
1315
+ def test_binops_index_scalar(self, op, idx, scalar):
1316
+ result = op(idx, scalar)
1317
+ expected = op(Index(idx.to_numpy()), scalar)
1318
+ tm.assert_index_equal(result, expected, exact="equiv")
1319
+
1320
+ @pytest.mark.parametrize("idx1", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
1321
+ @pytest.mark.parametrize("idx2", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
1322
+ def test_binops_index_pow(self, idx1, idx2):
1323
+ # numpy does not allow powers of negative integers so test separately
1324
+ # https://github.com/numpy/numpy/pull/8127
1325
+ idx1 = idx1._rename("foo")
1326
+ idx2 = idx2._rename("bar")
1327
+ result = pow(idx1, idx2)
1328
+ expected = pow(Index(idx1.to_numpy()), Index(idx2.to_numpy()))
1329
+ tm.assert_index_equal(result, expected, exact="equiv")
1330
+
1331
+ @pytest.mark.parametrize("idx", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
1332
+ @pytest.mark.parametrize("scalar", [1, 2])
1333
+ def test_binops_index_scalar_pow(self, idx, scalar):
1334
+ # numpy does not allow powers of negative integers so test separately
1335
+ # https://github.com/numpy/numpy/pull/8127
1336
+ result = pow(idx, scalar)
1337
+ expected = pow(Index(idx.to_numpy()), scalar)
1338
+ tm.assert_index_equal(result, expected, exact="equiv")
1339
+
1340
+ # TODO: divmod?
1341
+ @pytest.mark.parametrize(
1342
+ "op",
1343
+ [
1344
+ operator.add,
1345
+ operator.sub,
1346
+ operator.mul,
1347
+ operator.floordiv,
1348
+ operator.truediv,
1349
+ operator.pow,
1350
+ operator.mod,
1351
+ ],
1352
+ )
1353
+ def test_arithmetic_with_frame_or_series(self, op):
1354
+ # check that we return NotImplemented when operating with Series
1355
+ # or DataFrame
1356
+ index = RangeIndex(5)
1357
+ other = Series(np.random.default_rng(2).standard_normal(5))
1358
+
1359
+ expected = op(Series(index), other)
1360
+ result = op(index, other)
1361
+ tm.assert_series_equal(result, expected)
1362
+
1363
+ other = pd.DataFrame(np.random.default_rng(2).standard_normal((2, 5)))
1364
+ expected = op(pd.DataFrame([index, index]), other)
1365
+ result = op(index, other)
1366
+ tm.assert_frame_equal(result, expected)
1367
+
1368
+ def test_numeric_compat2(self):
1369
+ # validate that we are handling the RangeIndex overrides to numeric ops
1370
+ # and returning RangeIndex where possible
1371
+
1372
+ idx = RangeIndex(0, 10, 2)
1373
+
1374
+ result = idx * 2
1375
+ expected = RangeIndex(0, 20, 4)
1376
+ tm.assert_index_equal(result, expected, exact=True)
1377
+
1378
+ result = idx + 2
1379
+ expected = RangeIndex(2, 12, 2)
1380
+ tm.assert_index_equal(result, expected, exact=True)
1381
+
1382
+ result = idx - 2
1383
+ expected = RangeIndex(-2, 8, 2)
1384
+ tm.assert_index_equal(result, expected, exact=True)
1385
+
1386
+ result = idx / 2
1387
+ expected = RangeIndex(0, 5, 1).astype("float64")
1388
+ tm.assert_index_equal(result, expected, exact=True)
1389
+
1390
+ result = idx / 4
1391
+ expected = RangeIndex(0, 10, 2) / 4
1392
+ tm.assert_index_equal(result, expected, exact=True)
1393
+
1394
+ result = idx // 1
1395
+ expected = idx
1396
+ tm.assert_index_equal(result, expected, exact=True)
1397
+
1398
+ # __mul__
1399
+ result = idx * idx
1400
+ expected = Index(idx.values * idx.values)
1401
+ tm.assert_index_equal(result, expected, exact=True)
1402
+
1403
+ # __pow__
1404
+ idx = RangeIndex(0, 1000, 2)
1405
+ result = idx**2
1406
+ expected = Index(idx._values) ** 2
1407
+ tm.assert_index_equal(Index(result.values), expected, exact=True)
1408
+
1409
+ @pytest.mark.parametrize(
1410
+ "idx, div, expected",
1411
+ [
1412
+ # TODO: add more dtypes
1413
+ (RangeIndex(0, 1000, 2), 2, RangeIndex(0, 500, 1)),
1414
+ (RangeIndex(-99, -201, -3), -3, RangeIndex(33, 67, 1)),
1415
+ (
1416
+ RangeIndex(0, 1000, 1),
1417
+ 2,
1418
+ Index(RangeIndex(0, 1000, 1)._values) // 2,
1419
+ ),
1420
+ (
1421
+ RangeIndex(0, 100, 1),
1422
+ 2.0,
1423
+ Index(RangeIndex(0, 100, 1)._values) // 2.0,
1424
+ ),
1425
+ (RangeIndex(0), 50, RangeIndex(0)),
1426
+ (RangeIndex(2, 4, 2), 3, RangeIndex(0, 1, 1)),
1427
+ (RangeIndex(-5, -10, -6), 4, RangeIndex(-2, -1, 1)),
1428
+ (RangeIndex(-100, -200, 3), 2, RangeIndex(0)),
1429
+ ],
1430
+ )
1431
+ def test_numeric_compat2_floordiv(self, idx, div, expected):
1432
+ # __floordiv__
1433
+ tm.assert_index_equal(idx // div, expected, exact=True)
1434
+
1435
+ @pytest.mark.parametrize("dtype", [np.int64, np.float64])
1436
+ @pytest.mark.parametrize("delta", [1, 0, -1])
1437
+ def test_addsub_arithmetic(self, dtype, delta):
1438
+ # GH#8142
1439
+ delta = dtype(delta)
1440
+ index = Index([10, 11, 12], dtype=dtype)
1441
+ result = index + delta
1442
+ expected = Index(index.values + delta, dtype=dtype)
1443
+ tm.assert_index_equal(result, expected)
1444
+
1445
+ # this subtraction used to fail
1446
+ result = index - delta
1447
+ expected = Index(index.values - delta, dtype=dtype)
1448
+ tm.assert_index_equal(result, expected)
1449
+
1450
+ tm.assert_index_equal(index + index, 2 * index)
1451
+ tm.assert_index_equal(index - index, 0 * index)
1452
+ assert not (index - index).empty
1453
+
1454
+ def test_pow_nan_with_zero(self, box_with_array):
1455
+ left = Index([np.nan, np.nan, np.nan])
1456
+ right = Index([0, 0, 0])
1457
+ expected = Index([1.0, 1.0, 1.0])
1458
+
1459
+ left = tm.box_expected(left, box_with_array)
1460
+ right = tm.box_expected(right, box_with_array)
1461
+ expected = tm.box_expected(expected, box_with_array)
1462
+
1463
+ result = left**right
1464
+ tm.assert_equal(result, expected)
1465
+
1466
+
1467
+ def test_fill_value_inf_masking():
1468
+ # GH #27464 make sure we mask 0/1 with Inf and not NaN
1469
+ df = pd.DataFrame({"A": [0, 1, 2], "B": [1.1, None, 1.1]})
1470
+
1471
+ other = pd.DataFrame({"A": [1.1, 1.2, 1.3]}, index=[0, 2, 3])
1472
+
1473
+ result = df.rfloordiv(other, fill_value=1)
1474
+
1475
+ expected = pd.DataFrame(
1476
+ {"A": [np.inf, 1.0, 0.0, 1.0], "B": [0.0, np.nan, 0.0, np.nan]}
1477
+ )
1478
+ tm.assert_frame_equal(result, expected)
1479
+
1480
+
1481
+ def test_dataframe_div_silenced():
1482
+ # GH#26793
1483
+ pdf1 = pd.DataFrame(
1484
+ {
1485
+ "A": np.arange(10),
1486
+ "B": [np.nan, 1, 2, 3, 4] * 2,
1487
+ "C": [np.nan] * 10,
1488
+ "D": np.arange(10),
1489
+ },
1490
+ index=list("abcdefghij"),
1491
+ columns=list("ABCD"),
1492
+ )
1493
+ pdf2 = pd.DataFrame(
1494
+ np.random.default_rng(2).standard_normal((10, 4)),
1495
+ index=list("abcdefghjk"),
1496
+ columns=list("ABCX"),
1497
+ )
1498
+ with tm.assert_produces_warning(None):
1499
+ pdf1.div(pdf2, fill_value=0)
1500
+
1501
+
1502
+ @pytest.mark.parametrize(
1503
+ "data, expected_data",
1504
+ [([0, 1, 2], [0, 2, 4])],
1505
+ )
1506
+ def test_integer_array_add_list_like(
1507
+ box_pandas_1d_array, box_1d_array, data, expected_data
1508
+ ):
1509
+ # GH22606 Verify operators with IntegerArray and list-likes
1510
+ arr = array(data, dtype="Int64")
1511
+ container = box_pandas_1d_array(arr)
1512
+ left = container + box_1d_array(data)
1513
+ right = box_1d_array(data) + container
1514
+
1515
+ if Series in [box_1d_array, box_pandas_1d_array]:
1516
+ cls = Series
1517
+ elif Index in [box_1d_array, box_pandas_1d_array]:
1518
+ cls = Index
1519
+ else:
1520
+ cls = array
1521
+
1522
+ expected = cls(expected_data, dtype="Int64")
1523
+
1524
+ tm.assert_equal(left, expected)
1525
+ tm.assert_equal(right, expected)
1526
+
1527
+
1528
+ def test_sub_multiindex_swapped_levels():
1529
+ # GH 9952
1530
+ df = pd.DataFrame(
1531
+ {"a": np.random.default_rng(2).standard_normal(6)},
1532
+ index=pd.MultiIndex.from_product(
1533
+ [["a", "b"], [0, 1, 2]], names=["levA", "levB"]
1534
+ ),
1535
+ )
1536
+ df2 = df.copy()
1537
+ df2.index = df2.index.swaplevel(0, 1)
1538
+ result = df - df2
1539
+ expected = pd.DataFrame([0.0] * 6, columns=["a"], index=df.index)
1540
+ tm.assert_frame_equal(result, expected)
1541
+
1542
+
1543
+ @pytest.mark.parametrize("power", [1, 2, 5])
1544
+ @pytest.mark.parametrize("string_size", [0, 1, 2, 5])
1545
+ def test_empty_str_comparison(power, string_size):
1546
+ # GH 37348
1547
+ a = np.array(range(10**power))
1548
+ right = pd.DataFrame(a, dtype=np.int64)
1549
+ left = " " * string_size
1550
+
1551
+ result = right == left
1552
+ expected = pd.DataFrame(np.zeros(right.shape, dtype=bool))
1553
+ tm.assert_frame_equal(result, expected)
1554
+
1555
+
1556
+ def test_series_add_sub_with_UInt64():
1557
+ # GH 22023
1558
+ series1 = Series([1, 2, 3])
1559
+ series2 = Series([2, 1, 3], dtype="UInt64")
1560
+
1561
+ result = series1 + series2
1562
+ expected = Series([3, 3, 6], dtype="Float64")
1563
+ tm.assert_series_equal(result, expected)
1564
+
1565
+ result = series1 - series2
1566
+ expected = Series([-1, 1, 0], dtype="Float64")
1567
+ tm.assert_series_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_object.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Arithmetic tests for DataFrame/Series/Index/Array classes that should
2
+ # behave identically.
3
+ # Specifically for object dtype
4
+ import datetime
5
+ from decimal import Decimal
6
+ import operator
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from pandas._config import using_pyarrow_string_dtype
12
+
13
+ import pandas.util._test_decorators as td
14
+
15
+ import pandas as pd
16
+ from pandas import (
17
+ Series,
18
+ Timestamp,
19
+ option_context,
20
+ )
21
+ import pandas._testing as tm
22
+ from pandas.core import ops
23
+
24
+ # ------------------------------------------------------------------
25
+ # Comparisons
26
+
27
+
28
+ class TestObjectComparisons:
29
+ def test_comparison_object_numeric_nas(self, comparison_op):
30
+ ser = Series(np.random.default_rng(2).standard_normal(10), dtype=object)
31
+ shifted = ser.shift(2)
32
+
33
+ func = comparison_op
34
+
35
+ result = func(ser, shifted)
36
+ expected = func(ser.astype(float), shifted.astype(float))
37
+ tm.assert_series_equal(result, expected)
38
+
39
+ @pytest.mark.parametrize(
40
+ "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
41
+ )
42
+ def test_object_comparisons(self, infer_string):
43
+ with option_context("future.infer_string", infer_string):
44
+ ser = Series(["a", "b", np.nan, "c", "a"])
45
+
46
+ result = ser == "a"
47
+ expected = Series([True, False, False, False, True])
48
+ tm.assert_series_equal(result, expected)
49
+
50
+ result = ser < "a"
51
+ expected = Series([False, False, False, False, False])
52
+ tm.assert_series_equal(result, expected)
53
+
54
+ result = ser != "a"
55
+ expected = -(ser == "a")
56
+ tm.assert_series_equal(result, expected)
57
+
58
+ @pytest.mark.parametrize("dtype", [None, object])
59
+ def test_more_na_comparisons(self, dtype):
60
+ left = Series(["a", np.nan, "c"], dtype=dtype)
61
+ right = Series(["a", np.nan, "d"], dtype=dtype)
62
+
63
+ result = left == right
64
+ expected = Series([True, False, False])
65
+ tm.assert_series_equal(result, expected)
66
+
67
+ result = left != right
68
+ expected = Series([False, True, True])
69
+ tm.assert_series_equal(result, expected)
70
+
71
+ result = left == np.nan
72
+ expected = Series([False, False, False])
73
+ tm.assert_series_equal(result, expected)
74
+
75
+ result = left != np.nan
76
+ expected = Series([True, True, True])
77
+ tm.assert_series_equal(result, expected)
78
+
79
+
80
+ # ------------------------------------------------------------------
81
+ # Arithmetic
82
+
83
+
84
+ class TestArithmetic:
85
+ def test_add_period_to_array_of_offset(self):
86
+ # GH#50162
87
+ per = pd.Period("2012-1-1", freq="D")
88
+ pi = pd.period_range("2012-1-1", periods=10, freq="D")
89
+ idx = per - pi
90
+
91
+ expected = pd.Index([x + per for x in idx], dtype=object)
92
+ result = idx + per
93
+ tm.assert_index_equal(result, expected)
94
+
95
+ result = per + idx
96
+ tm.assert_index_equal(result, expected)
97
+
98
+ # TODO: parametrize
99
+ def test_pow_ops_object(self):
100
+ # GH#22922
101
+ # pow is weird with masking & 1, so testing here
102
+ a = Series([1, np.nan, 1, np.nan], dtype=object)
103
+ b = Series([1, np.nan, np.nan, 1], dtype=object)
104
+ result = a**b
105
+ expected = Series(a.values**b.values, dtype=object)
106
+ tm.assert_series_equal(result, expected)
107
+
108
+ result = b**a
109
+ expected = Series(b.values**a.values, dtype=object)
110
+
111
+ tm.assert_series_equal(result, expected)
112
+
113
+ @pytest.mark.parametrize("op", [operator.add, ops.radd])
114
+ @pytest.mark.parametrize("other", ["category", "Int64"])
115
+ def test_add_extension_scalar(self, other, box_with_array, op):
116
+ # GH#22378
117
+ # Check that scalars satisfying is_extension_array_dtype(obj)
118
+ # do not incorrectly try to dispatch to an ExtensionArray operation
119
+
120
+ arr = Series(["a", "b", "c"])
121
+ expected = Series([op(x, other) for x in arr])
122
+
123
+ arr = tm.box_expected(arr, box_with_array)
124
+ expected = tm.box_expected(expected, box_with_array)
125
+
126
+ result = op(arr, other)
127
+ tm.assert_equal(result, expected)
128
+
129
+ def test_objarr_add_str(self, box_with_array):
130
+ ser = Series(["x", np.nan, "x"])
131
+ expected = Series(["xa", np.nan, "xa"])
132
+
133
+ ser = tm.box_expected(ser, box_with_array)
134
+ expected = tm.box_expected(expected, box_with_array)
135
+
136
+ result = ser + "a"
137
+ tm.assert_equal(result, expected)
138
+
139
+ def test_objarr_radd_str(self, box_with_array):
140
+ ser = Series(["x", np.nan, "x"])
141
+ expected = Series(["ax", np.nan, "ax"])
142
+
143
+ ser = tm.box_expected(ser, box_with_array)
144
+ expected = tm.box_expected(expected, box_with_array)
145
+
146
+ result = "a" + ser
147
+ tm.assert_equal(result, expected)
148
+
149
+ @pytest.mark.parametrize(
150
+ "data",
151
+ [
152
+ [1, 2, 3],
153
+ [1.1, 2.2, 3.3],
154
+ [Timestamp("2011-01-01"), Timestamp("2011-01-02"), pd.NaT],
155
+ ["x", "y", 1],
156
+ ],
157
+ )
158
+ @pytest.mark.parametrize("dtype", [None, object])
159
+ def test_objarr_radd_str_invalid(self, dtype, data, box_with_array):
160
+ ser = Series(data, dtype=dtype)
161
+
162
+ ser = tm.box_expected(ser, box_with_array)
163
+ msg = "|".join(
164
+ [
165
+ "can only concatenate str",
166
+ "did not contain a loop with signature matching types",
167
+ "unsupported operand type",
168
+ "must be str",
169
+ ]
170
+ )
171
+ with pytest.raises(TypeError, match=msg):
172
+ "foo_" + ser
173
+
174
+ @pytest.mark.parametrize("op", [operator.add, ops.radd, operator.sub, ops.rsub])
175
+ def test_objarr_add_invalid(self, op, box_with_array):
176
+ # invalid ops
177
+ box = box_with_array
178
+
179
+ obj_ser = Series(list("abc"), dtype=object, name="objects")
180
+
181
+ obj_ser = tm.box_expected(obj_ser, box)
182
+ msg = "|".join(
183
+ [
184
+ "can only concatenate str",
185
+ "unsupported operand type",
186
+ "must be str",
187
+ "has no kernel",
188
+ ]
189
+ )
190
+ with pytest.raises(Exception, match=msg):
191
+ op(obj_ser, 1)
192
+ with pytest.raises(Exception, match=msg):
193
+ op(obj_ser, np.array(1, dtype=np.int64))
194
+
195
+ # TODO: Moved from tests.series.test_operators; needs cleanup
196
+ def test_operators_na_handling(self):
197
+ ser = Series(["foo", "bar", "baz", np.nan])
198
+ result = "prefix_" + ser
199
+ expected = Series(["prefix_foo", "prefix_bar", "prefix_baz", np.nan])
200
+ tm.assert_series_equal(result, expected)
201
+
202
+ result = ser + "_suffix"
203
+ expected = Series(["foo_suffix", "bar_suffix", "baz_suffix", np.nan])
204
+ tm.assert_series_equal(result, expected)
205
+
206
+ # TODO: parametrize over box
207
+ @pytest.mark.parametrize("dtype", [None, object])
208
+ def test_series_with_dtype_radd_timedelta(self, dtype):
209
+ # note this test is _not_ aimed at timedelta64-dtyped Series
210
+ # as of 2.0 we retain object dtype when ser.dtype == object
211
+ ser = Series(
212
+ [pd.Timedelta("1 days"), pd.Timedelta("2 days"), pd.Timedelta("3 days")],
213
+ dtype=dtype,
214
+ )
215
+ expected = Series(
216
+ [pd.Timedelta("4 days"), pd.Timedelta("5 days"), pd.Timedelta("6 days")],
217
+ dtype=dtype,
218
+ )
219
+
220
+ result = pd.Timedelta("3 days") + ser
221
+ tm.assert_series_equal(result, expected)
222
+
223
+ result = ser + pd.Timedelta("3 days")
224
+ tm.assert_series_equal(result, expected)
225
+
226
+ # TODO: cleanup & parametrize over box
227
+ def test_mixed_timezone_series_ops_object(self):
228
+ # GH#13043
229
+ ser = Series(
230
+ [
231
+ Timestamp("2015-01-01", tz="US/Eastern"),
232
+ Timestamp("2015-01-01", tz="Asia/Tokyo"),
233
+ ],
234
+ name="xxx",
235
+ )
236
+ assert ser.dtype == object
237
+
238
+ exp = Series(
239
+ [
240
+ Timestamp("2015-01-02", tz="US/Eastern"),
241
+ Timestamp("2015-01-02", tz="Asia/Tokyo"),
242
+ ],
243
+ name="xxx",
244
+ )
245
+ tm.assert_series_equal(ser + pd.Timedelta("1 days"), exp)
246
+ tm.assert_series_equal(pd.Timedelta("1 days") + ser, exp)
247
+
248
+ # object series & object series
249
+ ser2 = Series(
250
+ [
251
+ Timestamp("2015-01-03", tz="US/Eastern"),
252
+ Timestamp("2015-01-05", tz="Asia/Tokyo"),
253
+ ],
254
+ name="xxx",
255
+ )
256
+ assert ser2.dtype == object
257
+ exp = Series(
258
+ [pd.Timedelta("2 days"), pd.Timedelta("4 days")], name="xxx", dtype=object
259
+ )
260
+ tm.assert_series_equal(ser2 - ser, exp)
261
+ tm.assert_series_equal(ser - ser2, -exp)
262
+
263
+ ser = Series(
264
+ [pd.Timedelta("01:00:00"), pd.Timedelta("02:00:00")],
265
+ name="xxx",
266
+ dtype=object,
267
+ )
268
+ assert ser.dtype == object
269
+
270
+ exp = Series(
271
+ [pd.Timedelta("01:30:00"), pd.Timedelta("02:30:00")],
272
+ name="xxx",
273
+ dtype=object,
274
+ )
275
+ tm.assert_series_equal(ser + pd.Timedelta("00:30:00"), exp)
276
+ tm.assert_series_equal(pd.Timedelta("00:30:00") + ser, exp)
277
+
278
+ # TODO: cleanup & parametrize over box
279
+ def test_iadd_preserves_name(self):
280
+ # GH#17067, GH#19723 __iadd__ and __isub__ should preserve index name
281
+ ser = Series([1, 2, 3])
282
+ ser.index.name = "foo"
283
+
284
+ ser.index += 1
285
+ assert ser.index.name == "foo"
286
+
287
+ ser.index -= 1
288
+ assert ser.index.name == "foo"
289
+
290
+ def test_add_string(self):
291
+ # from bug report
292
+ index = pd.Index(["a", "b", "c"])
293
+ index2 = index + "foo"
294
+
295
+ assert "a" not in index2
296
+ assert "afoo" in index2
297
+
298
+ def test_iadd_string(self):
299
+ index = pd.Index(["a", "b", "c"])
300
+ # doesn't fail test unless there is a check before `+=`
301
+ assert "a" in index
302
+
303
+ index += "_x"
304
+ assert "a_x" in index
305
+
306
+ @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="add doesn't work")
307
+ def test_add(self):
308
+ index = pd.Index([str(i) for i in range(10)])
309
+ expected = pd.Index(index.values * 2)
310
+ tm.assert_index_equal(index + index, expected)
311
+ tm.assert_index_equal(index + index.tolist(), expected)
312
+ tm.assert_index_equal(index.tolist() + index, expected)
313
+
314
+ # test add and radd
315
+ index = pd.Index(list("abc"))
316
+ expected = pd.Index(["a1", "b1", "c1"])
317
+ tm.assert_index_equal(index + "1", expected)
318
+ expected = pd.Index(["1a", "1b", "1c"])
319
+ tm.assert_index_equal("1" + index, expected)
320
+
321
+ def test_sub_fail(self, using_infer_string):
322
+ index = pd.Index([str(i) for i in range(10)])
323
+
324
+ if using_infer_string:
325
+ import pyarrow as pa
326
+
327
+ err = pa.lib.ArrowNotImplementedError
328
+ msg = "has no kernel"
329
+ else:
330
+ err = TypeError
331
+ msg = "unsupported operand type|Cannot broadcast"
332
+ with pytest.raises(err, match=msg):
333
+ index - "a"
334
+ with pytest.raises(err, match=msg):
335
+ index - index
336
+ with pytest.raises(err, match=msg):
337
+ index - index.tolist()
338
+ with pytest.raises(err, match=msg):
339
+ index.tolist() - index
340
+
341
+ def test_sub_object(self):
342
+ # GH#19369
343
+ index = pd.Index([Decimal(1), Decimal(2)])
344
+ expected = pd.Index([Decimal(0), Decimal(1)])
345
+
346
+ result = index - Decimal(1)
347
+ tm.assert_index_equal(result, expected)
348
+
349
+ result = index - pd.Index([Decimal(1), Decimal(1)])
350
+ tm.assert_index_equal(result, expected)
351
+
352
+ msg = "unsupported operand type"
353
+ with pytest.raises(TypeError, match=msg):
354
+ index - "foo"
355
+
356
+ with pytest.raises(TypeError, match=msg):
357
+ index - np.array([2, "foo"], dtype=object)
358
+
359
+ def test_rsub_object(self, fixed_now_ts):
360
+ # GH#19369
361
+ index = pd.Index([Decimal(1), Decimal(2)])
362
+ expected = pd.Index([Decimal(1), Decimal(0)])
363
+
364
+ result = Decimal(2) - index
365
+ tm.assert_index_equal(result, expected)
366
+
367
+ result = np.array([Decimal(2), Decimal(2)]) - index
368
+ tm.assert_index_equal(result, expected)
369
+
370
+ msg = "unsupported operand type"
371
+ with pytest.raises(TypeError, match=msg):
372
+ "foo" - index
373
+
374
+ with pytest.raises(TypeError, match=msg):
375
+ np.array([True, fixed_now_ts]) - index
376
+
377
+
378
+ class MyIndex(pd.Index):
379
+ # Simple index subclass that tracks ops calls.
380
+
381
+ _calls: int
382
+
383
+ @classmethod
384
+ def _simple_new(cls, values, name=None, dtype=None):
385
+ result = object.__new__(cls)
386
+ result._data = values
387
+ result._name = name
388
+ result._calls = 0
389
+ result._reset_identity()
390
+
391
+ return result
392
+
393
+ def __add__(self, other):
394
+ self._calls += 1
395
+ return self._simple_new(self._data)
396
+
397
+ def __radd__(self, other):
398
+ return self.__add__(other)
399
+
400
+
401
+ @pytest.mark.parametrize(
402
+ "other",
403
+ [
404
+ [datetime.timedelta(1), datetime.timedelta(2)],
405
+ [datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 2)],
406
+ [pd.Period("2000"), pd.Period("2001")],
407
+ ["a", "b"],
408
+ ],
409
+ ids=["timedelta", "datetime", "period", "object"],
410
+ )
411
+ def test_index_ops_defer_to_unknown_subclasses(other):
412
+ # https://github.com/pandas-dev/pandas/issues/31109
413
+ values = np.array(
414
+ [datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)], dtype=object
415
+ )
416
+ a = MyIndex._simple_new(values)
417
+ other = pd.Index(other)
418
+ result = other + a
419
+ assert isinstance(result, MyIndex)
420
+ assert a._calls == 1
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_period.py ADDED
@@ -0,0 +1,1675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Arithmetic tests for DataFrame/Series/Index/Array classes that should
2
+ # behave identically.
3
+ # Specifically for Period dtype
4
+ import operator
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas._libs.tslibs import (
10
+ IncompatibleFrequency,
11
+ Period,
12
+ Timestamp,
13
+ to_offset,
14
+ )
15
+ from pandas.errors import PerformanceWarning
16
+
17
+ import pandas as pd
18
+ from pandas import (
19
+ PeriodIndex,
20
+ Series,
21
+ Timedelta,
22
+ TimedeltaIndex,
23
+ period_range,
24
+ )
25
+ import pandas._testing as tm
26
+ from pandas.core import ops
27
+ from pandas.core.arrays import TimedeltaArray
28
+ from pandas.tests.arithmetic.common import (
29
+ assert_invalid_addsub_type,
30
+ assert_invalid_comparison,
31
+ get_upcast_box,
32
+ )
33
+
34
+ _common_mismatch = [
35
+ pd.offsets.YearBegin(2),
36
+ pd.offsets.MonthBegin(1),
37
+ pd.offsets.Minute(),
38
+ ]
39
+
40
+
41
+ @pytest.fixture(
42
+ params=[
43
+ Timedelta(minutes=30).to_pytimedelta(),
44
+ np.timedelta64(30, "s"),
45
+ Timedelta(seconds=30),
46
+ ]
47
+ + _common_mismatch
48
+ )
49
+ def not_hourly(request):
50
+ """
51
+ Several timedelta-like and DateOffset instances that are _not_
52
+ compatible with Hourly frequencies.
53
+ """
54
+ return request.param
55
+
56
+
57
+ @pytest.fixture(
58
+ params=[
59
+ np.timedelta64(365, "D"),
60
+ Timedelta(days=365).to_pytimedelta(),
61
+ Timedelta(days=365),
62
+ ]
63
+ + _common_mismatch
64
+ )
65
+ def mismatched_freq(request):
66
+ """
67
+ Several timedelta-like and DateOffset instances that are _not_
68
+ compatible with Monthly or Annual frequencies.
69
+ """
70
+ return request.param
71
+
72
+
73
+ # ------------------------------------------------------------------
74
+ # Comparisons
75
+
76
+
77
+ class TestPeriodArrayLikeComparisons:
78
+ # Comparison tests for PeriodDtype vectors fully parametrized over
79
+ # DataFrame/Series/PeriodIndex/PeriodArray. Ideally all comparison
80
+ # tests will eventually end up here.
81
+
82
+ @pytest.mark.parametrize("other", ["2017", Period("2017", freq="D")])
83
+ def test_eq_scalar(self, other, box_with_array):
84
+ idx = PeriodIndex(["2017", "2017", "2018"], freq="D")
85
+ idx = tm.box_expected(idx, box_with_array)
86
+ xbox = get_upcast_box(idx, other, True)
87
+
88
+ expected = np.array([True, True, False])
89
+ expected = tm.box_expected(expected, xbox)
90
+
91
+ result = idx == other
92
+
93
+ tm.assert_equal(result, expected)
94
+
95
+ def test_compare_zerodim(self, box_with_array):
96
+ # GH#26689 make sure we unbox zero-dimensional arrays
97
+
98
+ pi = period_range("2000", periods=4)
99
+ other = np.array(pi.to_numpy()[0])
100
+
101
+ pi = tm.box_expected(pi, box_with_array)
102
+ xbox = get_upcast_box(pi, other, True)
103
+
104
+ result = pi <= other
105
+ expected = np.array([True, False, False, False])
106
+ expected = tm.box_expected(expected, xbox)
107
+ tm.assert_equal(result, expected)
108
+
109
+ @pytest.mark.parametrize(
110
+ "scalar",
111
+ [
112
+ "foo",
113
+ Timestamp("2021-01-01"),
114
+ Timedelta(days=4),
115
+ 9,
116
+ 9.5,
117
+ 2000, # specifically don't consider 2000 to match Period("2000", "D")
118
+ False,
119
+ None,
120
+ ],
121
+ )
122
+ def test_compare_invalid_scalar(self, box_with_array, scalar):
123
+ # GH#28980
124
+ # comparison with scalar that cannot be interpreted as a Period
125
+ pi = period_range("2000", periods=4)
126
+ parr = tm.box_expected(pi, box_with_array)
127
+ assert_invalid_comparison(parr, scalar, box_with_array)
128
+
129
+ @pytest.mark.parametrize(
130
+ "other",
131
+ [
132
+ pd.date_range("2000", periods=4).array,
133
+ pd.timedelta_range("1D", periods=4).array,
134
+ np.arange(4),
135
+ np.arange(4).astype(np.float64),
136
+ list(range(4)),
137
+ # match Period semantics by not treating integers as Periods
138
+ [2000, 2001, 2002, 2003],
139
+ np.arange(2000, 2004),
140
+ np.arange(2000, 2004).astype(object),
141
+ pd.Index([2000, 2001, 2002, 2003]),
142
+ ],
143
+ )
144
+ def test_compare_invalid_listlike(self, box_with_array, other):
145
+ pi = period_range("2000", periods=4)
146
+ parr = tm.box_expected(pi, box_with_array)
147
+ assert_invalid_comparison(parr, other, box_with_array)
148
+
149
+ @pytest.mark.parametrize("other_box", [list, np.array, lambda x: x.astype(object)])
150
+ def test_compare_object_dtype(self, box_with_array, other_box):
151
+ pi = period_range("2000", periods=5)
152
+ parr = tm.box_expected(pi, box_with_array)
153
+
154
+ other = other_box(pi)
155
+ xbox = get_upcast_box(parr, other, True)
156
+
157
+ expected = np.array([True, True, True, True, True])
158
+ expected = tm.box_expected(expected, xbox)
159
+
160
+ result = parr == other
161
+ tm.assert_equal(result, expected)
162
+ result = parr <= other
163
+ tm.assert_equal(result, expected)
164
+ result = parr >= other
165
+ tm.assert_equal(result, expected)
166
+
167
+ result = parr != other
168
+ tm.assert_equal(result, ~expected)
169
+ result = parr < other
170
+ tm.assert_equal(result, ~expected)
171
+ result = parr > other
172
+ tm.assert_equal(result, ~expected)
173
+
174
+ other = other_box(pi[::-1])
175
+
176
+ expected = np.array([False, False, True, False, False])
177
+ expected = tm.box_expected(expected, xbox)
178
+ result = parr == other
179
+ tm.assert_equal(result, expected)
180
+
181
+ expected = np.array([True, True, True, False, False])
182
+ expected = tm.box_expected(expected, xbox)
183
+ result = parr <= other
184
+ tm.assert_equal(result, expected)
185
+
186
+ expected = np.array([False, False, True, True, True])
187
+ expected = tm.box_expected(expected, xbox)
188
+ result = parr >= other
189
+ tm.assert_equal(result, expected)
190
+
191
+ expected = np.array([True, True, False, True, True])
192
+ expected = tm.box_expected(expected, xbox)
193
+ result = parr != other
194
+ tm.assert_equal(result, expected)
195
+
196
+ expected = np.array([True, True, False, False, False])
197
+ expected = tm.box_expected(expected, xbox)
198
+ result = parr < other
199
+ tm.assert_equal(result, expected)
200
+
201
+ expected = np.array([False, False, False, True, True])
202
+ expected = tm.box_expected(expected, xbox)
203
+ result = parr > other
204
+ tm.assert_equal(result, expected)
205
+
206
+
207
+ class TestPeriodIndexComparisons:
208
+ # TODO: parameterize over boxes
209
+
210
+ def test_pi_cmp_period(self):
211
+ idx = period_range("2007-01", periods=20, freq="M")
212
+ per = idx[10]
213
+
214
+ result = idx < per
215
+ exp = idx.values < idx.values[10]
216
+ tm.assert_numpy_array_equal(result, exp)
217
+
218
+ # Tests Period.__richcmp__ against ndarray[object, ndim=2]
219
+ result = idx.values.reshape(10, 2) < per
220
+ tm.assert_numpy_array_equal(result, exp.reshape(10, 2))
221
+
222
+ # Tests Period.__richcmp__ against ndarray[object, ndim=0]
223
+ result = idx < np.array(per)
224
+ tm.assert_numpy_array_equal(result, exp)
225
+
226
+ # TODO: moved from test_datetime64; de-duplicate with version below
227
+ def test_parr_cmp_period_scalar2(self, box_with_array):
228
+ pi = period_range("2000-01-01", periods=10, freq="D")
229
+
230
+ val = pi[3]
231
+ expected = [x > val for x in pi]
232
+
233
+ ser = tm.box_expected(pi, box_with_array)
234
+ xbox = get_upcast_box(ser, val, True)
235
+
236
+ expected = tm.box_expected(expected, xbox)
237
+ result = ser > val
238
+ tm.assert_equal(result, expected)
239
+
240
+ val = pi[5]
241
+ result = ser > val
242
+ expected = [x > val for x in pi]
243
+ expected = tm.box_expected(expected, xbox)
244
+ tm.assert_equal(result, expected)
245
+
246
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
247
+ def test_parr_cmp_period_scalar(self, freq, box_with_array):
248
+ # GH#13200
249
+ base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq)
250
+ base = tm.box_expected(base, box_with_array)
251
+ per = Period("2011-02", freq=freq)
252
+ xbox = get_upcast_box(base, per, True)
253
+
254
+ exp = np.array([False, True, False, False])
255
+ exp = tm.box_expected(exp, xbox)
256
+ tm.assert_equal(base == per, exp)
257
+ tm.assert_equal(per == base, exp)
258
+
259
+ exp = np.array([True, False, True, True])
260
+ exp = tm.box_expected(exp, xbox)
261
+ tm.assert_equal(base != per, exp)
262
+ tm.assert_equal(per != base, exp)
263
+
264
+ exp = np.array([False, False, True, True])
265
+ exp = tm.box_expected(exp, xbox)
266
+ tm.assert_equal(base > per, exp)
267
+ tm.assert_equal(per < base, exp)
268
+
269
+ exp = np.array([True, False, False, False])
270
+ exp = tm.box_expected(exp, xbox)
271
+ tm.assert_equal(base < per, exp)
272
+ tm.assert_equal(per > base, exp)
273
+
274
+ exp = np.array([False, True, True, True])
275
+ exp = tm.box_expected(exp, xbox)
276
+ tm.assert_equal(base >= per, exp)
277
+ tm.assert_equal(per <= base, exp)
278
+
279
+ exp = np.array([True, True, False, False])
280
+ exp = tm.box_expected(exp, xbox)
281
+ tm.assert_equal(base <= per, exp)
282
+ tm.assert_equal(per >= base, exp)
283
+
284
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
285
+ def test_parr_cmp_pi(self, freq, box_with_array):
286
+ # GH#13200
287
+ base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq)
288
+ base = tm.box_expected(base, box_with_array)
289
+
290
+ # TODO: could also box idx?
291
+ idx = PeriodIndex(["2011-02", "2011-01", "2011-03", "2011-05"], freq=freq)
292
+
293
+ xbox = get_upcast_box(base, idx, True)
294
+
295
+ exp = np.array([False, False, True, False])
296
+ exp = tm.box_expected(exp, xbox)
297
+ tm.assert_equal(base == idx, exp)
298
+
299
+ exp = np.array([True, True, False, True])
300
+ exp = tm.box_expected(exp, xbox)
301
+ tm.assert_equal(base != idx, exp)
302
+
303
+ exp = np.array([False, True, False, False])
304
+ exp = tm.box_expected(exp, xbox)
305
+ tm.assert_equal(base > idx, exp)
306
+
307
+ exp = np.array([True, False, False, True])
308
+ exp = tm.box_expected(exp, xbox)
309
+ tm.assert_equal(base < idx, exp)
310
+
311
+ exp = np.array([False, True, True, False])
312
+ exp = tm.box_expected(exp, xbox)
313
+ tm.assert_equal(base >= idx, exp)
314
+
315
+ exp = np.array([True, False, True, True])
316
+ exp = tm.box_expected(exp, xbox)
317
+ tm.assert_equal(base <= idx, exp)
318
+
319
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
320
+ def test_parr_cmp_pi_mismatched_freq(self, freq, box_with_array):
321
+ # GH#13200
322
+ # different base freq
323
+ base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq)
324
+ base = tm.box_expected(base, box_with_array)
325
+
326
+ msg = rf"Invalid comparison between dtype=period\[{freq}\] and Period"
327
+ with pytest.raises(TypeError, match=msg):
328
+ base <= Period("2011", freq="Y")
329
+
330
+ with pytest.raises(TypeError, match=msg):
331
+ Period("2011", freq="Y") >= base
332
+
333
+ # TODO: Could parametrize over boxes for idx?
334
+ idx = PeriodIndex(["2011", "2012", "2013", "2014"], freq="Y")
335
+ rev_msg = r"Invalid comparison between dtype=period\[Y-DEC\] and PeriodArray"
336
+ idx_msg = rev_msg if box_with_array in [tm.to_array, pd.array] else msg
337
+ with pytest.raises(TypeError, match=idx_msg):
338
+ base <= idx
339
+
340
+ # Different frequency
341
+ msg = rf"Invalid comparison between dtype=period\[{freq}\] and Period"
342
+ with pytest.raises(TypeError, match=msg):
343
+ base <= Period("2011", freq="4M")
344
+
345
+ with pytest.raises(TypeError, match=msg):
346
+ Period("2011", freq="4M") >= base
347
+
348
+ idx = PeriodIndex(["2011", "2012", "2013", "2014"], freq="4M")
349
+ rev_msg = r"Invalid comparison between dtype=period\[4M\] and PeriodArray"
350
+ idx_msg = rev_msg if box_with_array in [tm.to_array, pd.array] else msg
351
+ with pytest.raises(TypeError, match=idx_msg):
352
+ base <= idx
353
+
354
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
355
+ def test_pi_cmp_nat(self, freq):
356
+ idx1 = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-05"], freq=freq)
357
+ per = idx1[1]
358
+
359
+ result = idx1 > per
360
+ exp = np.array([False, False, False, True])
361
+ tm.assert_numpy_array_equal(result, exp)
362
+ result = per < idx1
363
+ tm.assert_numpy_array_equal(result, exp)
364
+
365
+ result = idx1 == pd.NaT
366
+ exp = np.array([False, False, False, False])
367
+ tm.assert_numpy_array_equal(result, exp)
368
+ result = pd.NaT == idx1
369
+ tm.assert_numpy_array_equal(result, exp)
370
+
371
+ result = idx1 != pd.NaT
372
+ exp = np.array([True, True, True, True])
373
+ tm.assert_numpy_array_equal(result, exp)
374
+ result = pd.NaT != idx1
375
+ tm.assert_numpy_array_equal(result, exp)
376
+
377
+ idx2 = PeriodIndex(["2011-02", "2011-01", "2011-04", "NaT"], freq=freq)
378
+ result = idx1 < idx2
379
+ exp = np.array([True, False, False, False])
380
+ tm.assert_numpy_array_equal(result, exp)
381
+
382
+ result = idx1 == idx2
383
+ exp = np.array([False, False, False, False])
384
+ tm.assert_numpy_array_equal(result, exp)
385
+
386
+ result = idx1 != idx2
387
+ exp = np.array([True, True, True, True])
388
+ tm.assert_numpy_array_equal(result, exp)
389
+
390
+ result = idx1 == idx1
391
+ exp = np.array([True, True, False, True])
392
+ tm.assert_numpy_array_equal(result, exp)
393
+
394
+ result = idx1 != idx1
395
+ exp = np.array([False, False, True, False])
396
+ tm.assert_numpy_array_equal(result, exp)
397
+
398
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
399
+ def test_pi_cmp_nat_mismatched_freq_raises(self, freq):
400
+ idx1 = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-05"], freq=freq)
401
+
402
+ diff = PeriodIndex(["2011-02", "2011-01", "2011-04", "NaT"], freq="4M")
403
+ msg = rf"Invalid comparison between dtype=period\[{freq}\] and PeriodArray"
404
+ with pytest.raises(TypeError, match=msg):
405
+ idx1 > diff
406
+
407
+ result = idx1 == diff
408
+ expected = np.array([False, False, False, False], dtype=bool)
409
+ tm.assert_numpy_array_equal(result, expected)
410
+
411
+ # TODO: De-duplicate with test_pi_cmp_nat
412
+ @pytest.mark.parametrize("dtype", [object, None])
413
+ def test_comp_nat(self, dtype):
414
+ left = PeriodIndex([Period("2011-01-01"), pd.NaT, Period("2011-01-03")])
415
+ right = PeriodIndex([pd.NaT, pd.NaT, Period("2011-01-03")])
416
+
417
+ if dtype is not None:
418
+ left = left.astype(dtype)
419
+ right = right.astype(dtype)
420
+
421
+ result = left == right
422
+ expected = np.array([False, False, True])
423
+ tm.assert_numpy_array_equal(result, expected)
424
+
425
+ result = left != right
426
+ expected = np.array([True, True, False])
427
+ tm.assert_numpy_array_equal(result, expected)
428
+
429
+ expected = np.array([False, False, False])
430
+ tm.assert_numpy_array_equal(left == pd.NaT, expected)
431
+ tm.assert_numpy_array_equal(pd.NaT == right, expected)
432
+
433
+ expected = np.array([True, True, True])
434
+ tm.assert_numpy_array_equal(left != pd.NaT, expected)
435
+ tm.assert_numpy_array_equal(pd.NaT != left, expected)
436
+
437
+ expected = np.array([False, False, False])
438
+ tm.assert_numpy_array_equal(left < pd.NaT, expected)
439
+ tm.assert_numpy_array_equal(pd.NaT > left, expected)
440
+
441
+
442
+ class TestPeriodSeriesComparisons:
443
+ def test_cmp_series_period_series_mixed_freq(self):
444
+ # GH#13200
445
+ base = Series(
446
+ [
447
+ Period("2011", freq="Y"),
448
+ Period("2011-02", freq="M"),
449
+ Period("2013", freq="Y"),
450
+ Period("2011-04", freq="M"),
451
+ ]
452
+ )
453
+
454
+ ser = Series(
455
+ [
456
+ Period("2012", freq="Y"),
457
+ Period("2011-01", freq="M"),
458
+ Period("2013", freq="Y"),
459
+ Period("2011-05", freq="M"),
460
+ ]
461
+ )
462
+
463
+ exp = Series([False, False, True, False])
464
+ tm.assert_series_equal(base == ser, exp)
465
+
466
+ exp = Series([True, True, False, True])
467
+ tm.assert_series_equal(base != ser, exp)
468
+
469
+ exp = Series([False, True, False, False])
470
+ tm.assert_series_equal(base > ser, exp)
471
+
472
+ exp = Series([True, False, False, True])
473
+ tm.assert_series_equal(base < ser, exp)
474
+
475
+ exp = Series([False, True, True, False])
476
+ tm.assert_series_equal(base >= ser, exp)
477
+
478
+ exp = Series([True, False, True, True])
479
+ tm.assert_series_equal(base <= ser, exp)
480
+
481
+
482
+ class TestPeriodIndexSeriesComparisonConsistency:
483
+ """Test PeriodIndex and Period Series Ops consistency"""
484
+
485
+ # TODO: needs parametrization+de-duplication
486
+
487
+ def _check(self, values, func, expected):
488
+ # Test PeriodIndex and Period Series Ops consistency
489
+
490
+ idx = PeriodIndex(values)
491
+ result = func(idx)
492
+
493
+ # check that we don't pass an unwanted type to tm.assert_equal
494
+ assert isinstance(expected, (pd.Index, np.ndarray))
495
+ tm.assert_equal(result, expected)
496
+
497
+ s = Series(values)
498
+ result = func(s)
499
+
500
+ exp = Series(expected, name=values.name)
501
+ tm.assert_series_equal(result, exp)
502
+
503
+ def test_pi_comp_period(self):
504
+ idx = PeriodIndex(
505
+ ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
506
+ )
507
+ per = idx[2]
508
+
509
+ f = lambda x: x == per
510
+ exp = np.array([False, False, True, False], dtype=np.bool_)
511
+ self._check(idx, f, exp)
512
+ f = lambda x: per == x
513
+ self._check(idx, f, exp)
514
+
515
+ f = lambda x: x != per
516
+ exp = np.array([True, True, False, True], dtype=np.bool_)
517
+ self._check(idx, f, exp)
518
+ f = lambda x: per != x
519
+ self._check(idx, f, exp)
520
+
521
+ f = lambda x: per >= x
522
+ exp = np.array([True, True, True, False], dtype=np.bool_)
523
+ self._check(idx, f, exp)
524
+
525
+ f = lambda x: x > per
526
+ exp = np.array([False, False, False, True], dtype=np.bool_)
527
+ self._check(idx, f, exp)
528
+
529
+ f = lambda x: per >= x
530
+ exp = np.array([True, True, True, False], dtype=np.bool_)
531
+ self._check(idx, f, exp)
532
+
533
+ def test_pi_comp_period_nat(self):
534
+ idx = PeriodIndex(
535
+ ["2011-01", "NaT", "2011-03", "2011-04"], freq="M", name="idx"
536
+ )
537
+ per = idx[2]
538
+
539
+ f = lambda x: x == per
540
+ exp = np.array([False, False, True, False], dtype=np.bool_)
541
+ self._check(idx, f, exp)
542
+ f = lambda x: per == x
543
+ self._check(idx, f, exp)
544
+
545
+ f = lambda x: x == pd.NaT
546
+ exp = np.array([False, False, False, False], dtype=np.bool_)
547
+ self._check(idx, f, exp)
548
+ f = lambda x: pd.NaT == x
549
+ self._check(idx, f, exp)
550
+
551
+ f = lambda x: x != per
552
+ exp = np.array([True, True, False, True], dtype=np.bool_)
553
+ self._check(idx, f, exp)
554
+ f = lambda x: per != x
555
+ self._check(idx, f, exp)
556
+
557
+ f = lambda x: x != pd.NaT
558
+ exp = np.array([True, True, True, True], dtype=np.bool_)
559
+ self._check(idx, f, exp)
560
+ f = lambda x: pd.NaT != x
561
+ self._check(idx, f, exp)
562
+
563
+ f = lambda x: per >= x
564
+ exp = np.array([True, False, True, False], dtype=np.bool_)
565
+ self._check(idx, f, exp)
566
+
567
+ f = lambda x: x < per
568
+ exp = np.array([True, False, False, False], dtype=np.bool_)
569
+ self._check(idx, f, exp)
570
+
571
+ f = lambda x: x > pd.NaT
572
+ exp = np.array([False, False, False, False], dtype=np.bool_)
573
+ self._check(idx, f, exp)
574
+
575
+ f = lambda x: pd.NaT >= x
576
+ exp = np.array([False, False, False, False], dtype=np.bool_)
577
+ self._check(idx, f, exp)
578
+
579
+
580
+ # ------------------------------------------------------------------
581
+ # Arithmetic
582
+
583
+
584
+ class TestPeriodFrameArithmetic:
585
+ def test_ops_frame_period(self):
586
+ # GH#13043
587
+ df = pd.DataFrame(
588
+ {
589
+ "A": [Period("2015-01", freq="M"), Period("2015-02", freq="M")],
590
+ "B": [Period("2014-01", freq="M"), Period("2014-02", freq="M")],
591
+ }
592
+ )
593
+ assert df["A"].dtype == "Period[M]"
594
+ assert df["B"].dtype == "Period[M]"
595
+
596
+ p = Period("2015-03", freq="M")
597
+ off = p.freq
598
+ # dtype will be object because of original dtype
599
+ exp = pd.DataFrame(
600
+ {
601
+ "A": np.array([2 * off, 1 * off], dtype=object),
602
+ "B": np.array([14 * off, 13 * off], dtype=object),
603
+ }
604
+ )
605
+ tm.assert_frame_equal(p - df, exp)
606
+ tm.assert_frame_equal(df - p, -1 * exp)
607
+
608
+ df2 = pd.DataFrame(
609
+ {
610
+ "A": [Period("2015-05", freq="M"), Period("2015-06", freq="M")],
611
+ "B": [Period("2015-05", freq="M"), Period("2015-06", freq="M")],
612
+ }
613
+ )
614
+ assert df2["A"].dtype == "Period[M]"
615
+ assert df2["B"].dtype == "Period[M]"
616
+
617
+ exp = pd.DataFrame(
618
+ {
619
+ "A": np.array([4 * off, 4 * off], dtype=object),
620
+ "B": np.array([16 * off, 16 * off], dtype=object),
621
+ }
622
+ )
623
+ tm.assert_frame_equal(df2 - df, exp)
624
+ tm.assert_frame_equal(df - df2, -1 * exp)
625
+
626
+
627
+ class TestPeriodIndexArithmetic:
628
+ # ---------------------------------------------------------------
629
+ # __add__/__sub__ with PeriodIndex
630
+ # PeriodIndex + other is defined for integers and timedelta-like others
631
+ # PeriodIndex - other is defined for integers, timedelta-like others,
632
+ # and PeriodIndex (with matching freq)
633
+
634
+ def test_parr_add_iadd_parr_raises(self, box_with_array):
635
+ rng = period_range("1/1/2000", freq="D", periods=5)
636
+ other = period_range("1/6/2000", freq="D", periods=5)
637
+ # TODO: parametrize over boxes for other?
638
+
639
+ rng = tm.box_expected(rng, box_with_array)
640
+ # An earlier implementation of PeriodIndex addition performed
641
+ # a set operation (union). This has since been changed to
642
+ # raise a TypeError. See GH#14164 and GH#13077 for historical
643
+ # reference.
644
+ msg = r"unsupported operand type\(s\) for \+: .* and .*"
645
+ with pytest.raises(TypeError, match=msg):
646
+ rng + other
647
+
648
+ with pytest.raises(TypeError, match=msg):
649
+ rng += other
650
+
651
+ def test_pi_sub_isub_pi(self):
652
+ # GH#20049
653
+ # For historical reference see GH#14164, GH#13077.
654
+ # PeriodIndex subtraction originally performed set difference,
655
+ # then changed to raise TypeError before being implemented in GH#20049
656
+ rng = period_range("1/1/2000", freq="D", periods=5)
657
+ other = period_range("1/6/2000", freq="D", periods=5)
658
+
659
+ off = rng.freq
660
+ expected = pd.Index([-5 * off] * 5)
661
+ result = rng - other
662
+ tm.assert_index_equal(result, expected)
663
+
664
+ rng -= other
665
+ tm.assert_index_equal(rng, expected)
666
+
667
+ def test_pi_sub_pi_with_nat(self):
668
+ rng = period_range("1/1/2000", freq="D", periods=5)
669
+ other = rng[1:].insert(0, pd.NaT)
670
+ assert other[1:].equals(rng[1:])
671
+
672
+ result = rng - other
673
+ off = rng.freq
674
+ expected = pd.Index([pd.NaT, 0 * off, 0 * off, 0 * off, 0 * off])
675
+ tm.assert_index_equal(result, expected)
676
+
677
+ def test_parr_sub_pi_mismatched_freq(self, box_with_array, box_with_array2):
678
+ rng = period_range("1/1/2000", freq="D", periods=5)
679
+ other = period_range("1/6/2000", freq="h", periods=5)
680
+
681
+ rng = tm.box_expected(rng, box_with_array)
682
+ other = tm.box_expected(other, box_with_array2)
683
+ msg = r"Input has different freq=[hD] from PeriodArray\(freq=[Dh]\)"
684
+ with pytest.raises(IncompatibleFrequency, match=msg):
685
+ rng - other
686
+
687
+ @pytest.mark.parametrize("n", [1, 2, 3, 4])
688
+ def test_sub_n_gt_1_ticks(self, tick_classes, n):
689
+ # GH 23878
690
+ p1_d = "19910905"
691
+ p2_d = "19920406"
692
+ p1 = PeriodIndex([p1_d], freq=tick_classes(n))
693
+ p2 = PeriodIndex([p2_d], freq=tick_classes(n))
694
+
695
+ expected = PeriodIndex([p2_d], freq=p2.freq.base) - PeriodIndex(
696
+ [p1_d], freq=p1.freq.base
697
+ )
698
+
699
+ tm.assert_index_equal((p2 - p1), expected)
700
+
701
+ @pytest.mark.parametrize("n", [1, 2, 3, 4])
702
+ @pytest.mark.parametrize(
703
+ "offset, kwd_name",
704
+ [
705
+ (pd.offsets.YearEnd, "month"),
706
+ (pd.offsets.QuarterEnd, "startingMonth"),
707
+ (pd.offsets.MonthEnd, None),
708
+ (pd.offsets.Week, "weekday"),
709
+ ],
710
+ )
711
+ def test_sub_n_gt_1_offsets(self, offset, kwd_name, n):
712
+ # GH 23878
713
+ kwds = {kwd_name: 3} if kwd_name is not None else {}
714
+ p1_d = "19910905"
715
+ p2_d = "19920406"
716
+ freq = offset(n, normalize=False, **kwds)
717
+ p1 = PeriodIndex([p1_d], freq=freq)
718
+ p2 = PeriodIndex([p2_d], freq=freq)
719
+
720
+ result = p2 - p1
721
+ expected = PeriodIndex([p2_d], freq=freq.base) - PeriodIndex(
722
+ [p1_d], freq=freq.base
723
+ )
724
+
725
+ tm.assert_index_equal(result, expected)
726
+
727
+ # -------------------------------------------------------------
728
+ # Invalid Operations
729
+
730
+ @pytest.mark.parametrize(
731
+ "other",
732
+ [
733
+ # datetime scalars
734
+ Timestamp("2016-01-01"),
735
+ Timestamp("2016-01-01").to_pydatetime(),
736
+ Timestamp("2016-01-01").to_datetime64(),
737
+ # datetime-like arrays
738
+ pd.date_range("2016-01-01", periods=3, freq="h"),
739
+ pd.date_range("2016-01-01", periods=3, tz="Europe/Brussels"),
740
+ pd.date_range("2016-01-01", periods=3, freq="s")._data,
741
+ pd.date_range("2016-01-01", periods=3, tz="Asia/Tokyo")._data,
742
+ # Miscellaneous invalid types
743
+ 3.14,
744
+ np.array([2.0, 3.0, 4.0]),
745
+ ],
746
+ )
747
+ def test_parr_add_sub_invalid(self, other, box_with_array):
748
+ # GH#23215
749
+ rng = period_range("1/1/2000", freq="D", periods=3)
750
+ rng = tm.box_expected(rng, box_with_array)
751
+
752
+ msg = "|".join(
753
+ [
754
+ r"(:?cannot add PeriodArray and .*)",
755
+ r"(:?cannot subtract .* from (:?a\s)?.*)",
756
+ r"(:?unsupported operand type\(s\) for \+: .* and .*)",
757
+ r"unsupported operand type\(s\) for [+-]: .* and .*",
758
+ ]
759
+ )
760
+ assert_invalid_addsub_type(rng, other, msg)
761
+ with pytest.raises(TypeError, match=msg):
762
+ rng + other
763
+ with pytest.raises(TypeError, match=msg):
764
+ other + rng
765
+ with pytest.raises(TypeError, match=msg):
766
+ rng - other
767
+ with pytest.raises(TypeError, match=msg):
768
+ other - rng
769
+
770
+ # -----------------------------------------------------------------
771
+ # __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64]
772
+
773
+ def test_pi_add_sub_td64_array_non_tick_raises(self):
774
+ rng = period_range("1/1/2000", freq="Q", periods=3)
775
+ tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
776
+ tdarr = tdi.values
777
+
778
+ msg = r"Cannot add or subtract timedelta64\[ns\] dtype from period\[Q-DEC\]"
779
+ with pytest.raises(TypeError, match=msg):
780
+ rng + tdarr
781
+ with pytest.raises(TypeError, match=msg):
782
+ tdarr + rng
783
+
784
+ with pytest.raises(TypeError, match=msg):
785
+ rng - tdarr
786
+ msg = r"cannot subtract PeriodArray from TimedeltaArray"
787
+ with pytest.raises(TypeError, match=msg):
788
+ tdarr - rng
789
+
790
+ def test_pi_add_sub_td64_array_tick(self):
791
+ # PeriodIndex + Timedelta-like is allowed only with
792
+ # tick-like frequencies
793
+ rng = period_range("1/1/2000", freq="90D", periods=3)
794
+ tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
795
+ tdarr = tdi.values
796
+
797
+ expected = period_range("12/31/1999", freq="90D", periods=3)
798
+ result = rng + tdi
799
+ tm.assert_index_equal(result, expected)
800
+ result = rng + tdarr
801
+ tm.assert_index_equal(result, expected)
802
+ result = tdi + rng
803
+ tm.assert_index_equal(result, expected)
804
+ result = tdarr + rng
805
+ tm.assert_index_equal(result, expected)
806
+
807
+ expected = period_range("1/2/2000", freq="90D", periods=3)
808
+
809
+ result = rng - tdi
810
+ tm.assert_index_equal(result, expected)
811
+ result = rng - tdarr
812
+ tm.assert_index_equal(result, expected)
813
+
814
+ msg = r"cannot subtract .* from .*"
815
+ with pytest.raises(TypeError, match=msg):
816
+ tdarr - rng
817
+
818
+ with pytest.raises(TypeError, match=msg):
819
+ tdi - rng
820
+
821
+ @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "h"])
822
+ @pytest.mark.parametrize("tdi_freq", [None, "h"])
823
+ def test_parr_sub_td64array(self, box_with_array, tdi_freq, pi_freq):
824
+ box = box_with_array
825
+ xbox = box if box not in [pd.array, tm.to_array] else pd.Index
826
+
827
+ tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq)
828
+ dti = Timestamp("2018-03-07 17:16:40") + tdi
829
+ pi = dti.to_period(pi_freq)
830
+
831
+ # TODO: parametrize over box for pi?
832
+ td64obj = tm.box_expected(tdi, box)
833
+
834
+ if pi_freq == "h":
835
+ result = pi - td64obj
836
+ expected = (pi.to_timestamp("s") - tdi).to_period(pi_freq)
837
+ expected = tm.box_expected(expected, xbox)
838
+ tm.assert_equal(result, expected)
839
+
840
+ # Subtract from scalar
841
+ result = pi[0] - td64obj
842
+ expected = (pi[0].to_timestamp("s") - tdi).to_period(pi_freq)
843
+ expected = tm.box_expected(expected, box)
844
+ tm.assert_equal(result, expected)
845
+
846
+ elif pi_freq == "D":
847
+ # Tick, but non-compatible
848
+ msg = (
849
+ "Cannot add/subtract timedelta-like from PeriodArray that is "
850
+ "not an integer multiple of the PeriodArray's freq."
851
+ )
852
+ with pytest.raises(IncompatibleFrequency, match=msg):
853
+ pi - td64obj
854
+
855
+ with pytest.raises(IncompatibleFrequency, match=msg):
856
+ pi[0] - td64obj
857
+
858
+ else:
859
+ # With non-Tick freq, we could not add timedelta64 array regardless
860
+ # of what its resolution is
861
+ msg = "Cannot add or subtract timedelta64"
862
+ with pytest.raises(TypeError, match=msg):
863
+ pi - td64obj
864
+ with pytest.raises(TypeError, match=msg):
865
+ pi[0] - td64obj
866
+
867
+ # -----------------------------------------------------------------
868
+ # operations with array/Index of DateOffset objects
869
+
870
+ @pytest.mark.parametrize("box", [np.array, pd.Index])
871
+ def test_pi_add_offset_array(self, box):
872
+ # GH#18849
873
+ pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")])
874
+ offs = box(
875
+ [
876
+ pd.offsets.QuarterEnd(n=1, startingMonth=12),
877
+ pd.offsets.QuarterEnd(n=-2, startingMonth=12),
878
+ ]
879
+ )
880
+ expected = PeriodIndex([Period("2015Q2"), Period("2015Q4")]).astype(object)
881
+
882
+ with tm.assert_produces_warning(PerformanceWarning):
883
+ res = pi + offs
884
+ tm.assert_index_equal(res, expected)
885
+
886
+ with tm.assert_produces_warning(PerformanceWarning):
887
+ res2 = offs + pi
888
+ tm.assert_index_equal(res2, expected)
889
+
890
+ unanchored = np.array([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)])
891
+ # addition/subtraction ops with incompatible offsets should issue
892
+ # a PerformanceWarning and _then_ raise a TypeError.
893
+ msg = r"Input cannot be converted to Period\(freq=Q-DEC\)"
894
+ with pytest.raises(IncompatibleFrequency, match=msg):
895
+ with tm.assert_produces_warning(PerformanceWarning):
896
+ pi + unanchored
897
+ with pytest.raises(IncompatibleFrequency, match=msg):
898
+ with tm.assert_produces_warning(PerformanceWarning):
899
+ unanchored + pi
900
+
901
+ @pytest.mark.parametrize("box", [np.array, pd.Index])
902
+ def test_pi_sub_offset_array(self, box):
903
+ # GH#18824
904
+ pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")])
905
+ other = box(
906
+ [
907
+ pd.offsets.QuarterEnd(n=1, startingMonth=12),
908
+ pd.offsets.QuarterEnd(n=-2, startingMonth=12),
909
+ ]
910
+ )
911
+
912
+ expected = PeriodIndex([pi[n] - other[n] for n in range(len(pi))])
913
+ expected = expected.astype(object)
914
+
915
+ with tm.assert_produces_warning(PerformanceWarning):
916
+ res = pi - other
917
+ tm.assert_index_equal(res, expected)
918
+
919
+ anchored = box([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])
920
+
921
+ # addition/subtraction ops with anchored offsets should issue
922
+ # a PerformanceWarning and _then_ raise a TypeError.
923
+ msg = r"Input has different freq=-1M from Period\(freq=Q-DEC\)"
924
+ with pytest.raises(IncompatibleFrequency, match=msg):
925
+ with tm.assert_produces_warning(PerformanceWarning):
926
+ pi - anchored
927
+ with pytest.raises(IncompatibleFrequency, match=msg):
928
+ with tm.assert_produces_warning(PerformanceWarning):
929
+ anchored - pi
930
+
931
+ def test_pi_add_iadd_int(self, one):
932
+ # Variants of `one` for #19012
933
+ rng = period_range("2000-01-01 09:00", freq="h", periods=10)
934
+ result = rng + one
935
+ expected = period_range("2000-01-01 10:00", freq="h", periods=10)
936
+ tm.assert_index_equal(result, expected)
937
+ rng += one
938
+ tm.assert_index_equal(rng, expected)
939
+
940
+ def test_pi_sub_isub_int(self, one):
941
+ """
942
+ PeriodIndex.__sub__ and __isub__ with several representations of
943
+ the integer 1, e.g. int, np.int64, np.uint8, ...
944
+ """
945
+ rng = period_range("2000-01-01 09:00", freq="h", periods=10)
946
+ result = rng - one
947
+ expected = period_range("2000-01-01 08:00", freq="h", periods=10)
948
+ tm.assert_index_equal(result, expected)
949
+ rng -= one
950
+ tm.assert_index_equal(rng, expected)
951
+
952
+ @pytest.mark.parametrize("five", [5, np.array(5, dtype=np.int64)])
953
+ def test_pi_sub_intlike(self, five):
954
+ rng = period_range("2007-01", periods=50)
955
+
956
+ result = rng - five
957
+ exp = rng + (-five)
958
+ tm.assert_index_equal(result, exp)
959
+
960
+ def test_pi_add_sub_int_array_freqn_gt1(self):
961
+ # GH#47209 test adding array of ints when freq.n > 1 matches
962
+ # scalar behavior
963
+ pi = period_range("2016-01-01", periods=10, freq="2D")
964
+ arr = np.arange(10)
965
+ result = pi + arr
966
+ expected = pd.Index([x + y for x, y in zip(pi, arr)])
967
+ tm.assert_index_equal(result, expected)
968
+
969
+ result = pi - arr
970
+ expected = pd.Index([x - y for x, y in zip(pi, arr)])
971
+ tm.assert_index_equal(result, expected)
972
+
973
+ def test_pi_sub_isub_offset(self):
974
+ # offset
975
+ # DateOffset
976
+ rng = period_range("2014", "2024", freq="Y")
977
+ result = rng - pd.offsets.YearEnd(5)
978
+ expected = period_range("2009", "2019", freq="Y")
979
+ tm.assert_index_equal(result, expected)
980
+ rng -= pd.offsets.YearEnd(5)
981
+ tm.assert_index_equal(rng, expected)
982
+
983
+ rng = period_range("2014-01", "2016-12", freq="M")
984
+ result = rng - pd.offsets.MonthEnd(5)
985
+ expected = period_range("2013-08", "2016-07", freq="M")
986
+ tm.assert_index_equal(result, expected)
987
+
988
+ rng -= pd.offsets.MonthEnd(5)
989
+ tm.assert_index_equal(rng, expected)
990
+
991
+ @pytest.mark.parametrize("transpose", [True, False])
992
+ def test_pi_add_offset_n_gt1(self, box_with_array, transpose):
993
+ # GH#23215
994
+ # add offset to PeriodIndex with freq.n > 1
995
+
996
+ per = Period("2016-01", freq="2M")
997
+ pi = PeriodIndex([per])
998
+
999
+ expected = PeriodIndex(["2016-03"], freq="2M")
1000
+
1001
+ pi = tm.box_expected(pi, box_with_array, transpose=transpose)
1002
+ expected = tm.box_expected(expected, box_with_array, transpose=transpose)
1003
+
1004
+ result = pi + per.freq
1005
+ tm.assert_equal(result, expected)
1006
+
1007
+ result = per.freq + pi
1008
+ tm.assert_equal(result, expected)
1009
+
1010
+ def test_pi_add_offset_n_gt1_not_divisible(self, box_with_array):
1011
+ # GH#23215
1012
+ # PeriodIndex with freq.n > 1 add offset with offset.n % freq.n != 0
1013
+ pi = PeriodIndex(["2016-01"], freq="2M")
1014
+ expected = PeriodIndex(["2016-04"], freq="2M")
1015
+
1016
+ pi = tm.box_expected(pi, box_with_array)
1017
+ expected = tm.box_expected(expected, box_with_array)
1018
+
1019
+ result = pi + to_offset("3ME")
1020
+ tm.assert_equal(result, expected)
1021
+
1022
+ result = to_offset("3ME") + pi
1023
+ tm.assert_equal(result, expected)
1024
+
1025
+ # ---------------------------------------------------------------
1026
+ # __add__/__sub__ with integer arrays
1027
+
1028
+ @pytest.mark.parametrize("int_holder", [np.array, pd.Index])
1029
+ @pytest.mark.parametrize("op", [operator.add, ops.radd])
1030
+ def test_pi_add_intarray(self, int_holder, op):
1031
+ # GH#19959
1032
+ pi = PeriodIndex([Period("2015Q1"), Period("NaT")])
1033
+ other = int_holder([4, -1])
1034
+
1035
+ result = op(pi, other)
1036
+ expected = PeriodIndex([Period("2016Q1"), Period("NaT")])
1037
+ tm.assert_index_equal(result, expected)
1038
+
1039
+ @pytest.mark.parametrize("int_holder", [np.array, pd.Index])
1040
+ def test_pi_sub_intarray(self, int_holder):
1041
+ # GH#19959
1042
+ pi = PeriodIndex([Period("2015Q1"), Period("NaT")])
1043
+ other = int_holder([4, -1])
1044
+
1045
+ result = pi - other
1046
+ expected = PeriodIndex([Period("2014Q1"), Period("NaT")])
1047
+ tm.assert_index_equal(result, expected)
1048
+
1049
+ msg = r"bad operand type for unary -: 'PeriodArray'"
1050
+ with pytest.raises(TypeError, match=msg):
1051
+ other - pi
1052
+
1053
+ # ---------------------------------------------------------------
1054
+ # Timedelta-like (timedelta, timedelta64, Timedelta, Tick)
1055
+ # TODO: Some of these are misnomers because of non-Tick DateOffsets
1056
+
1057
+ def test_parr_add_timedeltalike_minute_gt1(self, three_days, box_with_array):
1058
+ # GH#23031 adding a time-delta-like offset to a PeriodArray that has
1059
+ # minute frequency with n != 1. A more general case is tested below
1060
+ # in test_pi_add_timedeltalike_tick_gt1, but here we write out the
1061
+ # expected result more explicitly.
1062
+ other = three_days
1063
+ rng = period_range("2014-05-01", periods=3, freq="2D")
1064
+ rng = tm.box_expected(rng, box_with_array)
1065
+
1066
+ expected = PeriodIndex(["2014-05-04", "2014-05-06", "2014-05-08"], freq="2D")
1067
+ expected = tm.box_expected(expected, box_with_array)
1068
+
1069
+ result = rng + other
1070
+ tm.assert_equal(result, expected)
1071
+
1072
+ result = other + rng
1073
+ tm.assert_equal(result, expected)
1074
+
1075
+ # subtraction
1076
+ expected = PeriodIndex(["2014-04-28", "2014-04-30", "2014-05-02"], freq="2D")
1077
+ expected = tm.box_expected(expected, box_with_array)
1078
+ result = rng - other
1079
+ tm.assert_equal(result, expected)
1080
+
1081
+ msg = "|".join(
1082
+ [
1083
+ r"bad operand type for unary -: 'PeriodArray'",
1084
+ r"cannot subtract PeriodArray from timedelta64\[[hD]\]",
1085
+ ]
1086
+ )
1087
+ with pytest.raises(TypeError, match=msg):
1088
+ other - rng
1089
+
1090
+ @pytest.mark.parametrize("freqstr", ["5ns", "5us", "5ms", "5s", "5min", "5h", "5d"])
1091
+ def test_parr_add_timedeltalike_tick_gt1(self, three_days, freqstr, box_with_array):
1092
+ # GH#23031 adding a time-delta-like offset to a PeriodArray that has
1093
+ # tick-like frequency with n != 1
1094
+ other = three_days
1095
+ rng = period_range("2014-05-01", periods=6, freq=freqstr)
1096
+ first = rng[0]
1097
+ rng = tm.box_expected(rng, box_with_array)
1098
+
1099
+ expected = period_range(first + other, periods=6, freq=freqstr)
1100
+ expected = tm.box_expected(expected, box_with_array)
1101
+
1102
+ result = rng + other
1103
+ tm.assert_equal(result, expected)
1104
+
1105
+ result = other + rng
1106
+ tm.assert_equal(result, expected)
1107
+
1108
+ # subtraction
1109
+ expected = period_range(first - other, periods=6, freq=freqstr)
1110
+ expected = tm.box_expected(expected, box_with_array)
1111
+ result = rng - other
1112
+ tm.assert_equal(result, expected)
1113
+ msg = "|".join(
1114
+ [
1115
+ r"bad operand type for unary -: 'PeriodArray'",
1116
+ r"cannot subtract PeriodArray from timedelta64\[[hD]\]",
1117
+ ]
1118
+ )
1119
+ with pytest.raises(TypeError, match=msg):
1120
+ other - rng
1121
+
1122
+ def test_pi_add_iadd_timedeltalike_daily(self, three_days):
1123
+ # Tick
1124
+ other = three_days
1125
+ rng = period_range("2014-05-01", "2014-05-15", freq="D")
1126
+ expected = period_range("2014-05-04", "2014-05-18", freq="D")
1127
+
1128
+ result = rng + other
1129
+ tm.assert_index_equal(result, expected)
1130
+
1131
+ rng += other
1132
+ tm.assert_index_equal(rng, expected)
1133
+
1134
+ def test_pi_sub_isub_timedeltalike_daily(self, three_days):
1135
+ # Tick-like 3 Days
1136
+ other = three_days
1137
+ rng = period_range("2014-05-01", "2014-05-15", freq="D")
1138
+ expected = period_range("2014-04-28", "2014-05-12", freq="D")
1139
+
1140
+ result = rng - other
1141
+ tm.assert_index_equal(result, expected)
1142
+
1143
+ rng -= other
1144
+ tm.assert_index_equal(rng, expected)
1145
+
1146
+ def test_parr_add_sub_timedeltalike_freq_mismatch_daily(
1147
+ self, not_daily, box_with_array
1148
+ ):
1149
+ other = not_daily
1150
+ rng = period_range("2014-05-01", "2014-05-15", freq="D")
1151
+ rng = tm.box_expected(rng, box_with_array)
1152
+
1153
+ msg = "|".join(
1154
+ [
1155
+ # non-timedelta-like DateOffset
1156
+ "Input has different freq(=.+)? from Period.*?\\(freq=D\\)",
1157
+ # timedelta/td64/Timedelta but not a multiple of 24H
1158
+ "Cannot add/subtract timedelta-like from PeriodArray that is "
1159
+ "not an integer multiple of the PeriodArray's freq.",
1160
+ ]
1161
+ )
1162
+ with pytest.raises(IncompatibleFrequency, match=msg):
1163
+ rng + other
1164
+ with pytest.raises(IncompatibleFrequency, match=msg):
1165
+ rng += other
1166
+ with pytest.raises(IncompatibleFrequency, match=msg):
1167
+ rng - other
1168
+ with pytest.raises(IncompatibleFrequency, match=msg):
1169
+ rng -= other
1170
+
1171
+ def test_pi_add_iadd_timedeltalike_hourly(self, two_hours):
1172
+ other = two_hours
1173
+ rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h")
1174
+ expected = period_range("2014-01-01 12:00", "2014-01-05 12:00", freq="h")
1175
+
1176
+ result = rng + other
1177
+ tm.assert_index_equal(result, expected)
1178
+
1179
+ rng += other
1180
+ tm.assert_index_equal(rng, expected)
1181
+
1182
+ def test_parr_add_timedeltalike_mismatched_freq_hourly(
1183
+ self, not_hourly, box_with_array
1184
+ ):
1185
+ other = not_hourly
1186
+ rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h")
1187
+ rng = tm.box_expected(rng, box_with_array)
1188
+ msg = "|".join(
1189
+ [
1190
+ # non-timedelta-like DateOffset
1191
+ "Input has different freq(=.+)? from Period.*?\\(freq=h\\)",
1192
+ # timedelta/td64/Timedelta but not a multiple of 24H
1193
+ "Cannot add/subtract timedelta-like from PeriodArray that is "
1194
+ "not an integer multiple of the PeriodArray's freq.",
1195
+ ]
1196
+ )
1197
+
1198
+ with pytest.raises(IncompatibleFrequency, match=msg):
1199
+ rng + other
1200
+
1201
+ with pytest.raises(IncompatibleFrequency, match=msg):
1202
+ rng += other
1203
+
1204
+ def test_pi_sub_isub_timedeltalike_hourly(self, two_hours):
1205
+ other = two_hours
1206
+ rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h")
1207
+ expected = period_range("2014-01-01 08:00", "2014-01-05 08:00", freq="h")
1208
+
1209
+ result = rng - other
1210
+ tm.assert_index_equal(result, expected)
1211
+
1212
+ rng -= other
1213
+ tm.assert_index_equal(rng, expected)
1214
+
1215
+ def test_add_iadd_timedeltalike_annual(self):
1216
+ # offset
1217
+ # DateOffset
1218
+ rng = period_range("2014", "2024", freq="Y")
1219
+ result = rng + pd.offsets.YearEnd(5)
1220
+ expected = period_range("2019", "2029", freq="Y")
1221
+ tm.assert_index_equal(result, expected)
1222
+ rng += pd.offsets.YearEnd(5)
1223
+ tm.assert_index_equal(rng, expected)
1224
+
1225
+ def test_pi_add_sub_timedeltalike_freq_mismatch_annual(self, mismatched_freq):
1226
+ other = mismatched_freq
1227
+ rng = period_range("2014", "2024", freq="Y")
1228
+ msg = "Input has different freq(=.+)? from Period.*?\\(freq=Y-DEC\\)"
1229
+ with pytest.raises(IncompatibleFrequency, match=msg):
1230
+ rng + other
1231
+ with pytest.raises(IncompatibleFrequency, match=msg):
1232
+ rng += other
1233
+ with pytest.raises(IncompatibleFrequency, match=msg):
1234
+ rng - other
1235
+ with pytest.raises(IncompatibleFrequency, match=msg):
1236
+ rng -= other
1237
+
1238
+ def test_pi_add_iadd_timedeltalike_M(self):
1239
+ rng = period_range("2014-01", "2016-12", freq="M")
1240
+ expected = period_range("2014-06", "2017-05", freq="M")
1241
+
1242
+ result = rng + pd.offsets.MonthEnd(5)
1243
+ tm.assert_index_equal(result, expected)
1244
+
1245
+ rng += pd.offsets.MonthEnd(5)
1246
+ tm.assert_index_equal(rng, expected)
1247
+
1248
+ def test_pi_add_sub_timedeltalike_freq_mismatch_monthly(self, mismatched_freq):
1249
+ other = mismatched_freq
1250
+ rng = period_range("2014-01", "2016-12", freq="M")
1251
+ msg = "Input has different freq(=.+)? from Period.*?\\(freq=M\\)"
1252
+ with pytest.raises(IncompatibleFrequency, match=msg):
1253
+ rng + other
1254
+ with pytest.raises(IncompatibleFrequency, match=msg):
1255
+ rng += other
1256
+ with pytest.raises(IncompatibleFrequency, match=msg):
1257
+ rng - other
1258
+ with pytest.raises(IncompatibleFrequency, match=msg):
1259
+ rng -= other
1260
+
1261
+ @pytest.mark.parametrize("transpose", [True, False])
1262
+ def test_parr_add_sub_td64_nat(self, box_with_array, transpose):
1263
+ # GH#23320 special handling for timedelta64("NaT")
1264
+ pi = period_range("1994-04-01", periods=9, freq="19D")
1265
+ other = np.timedelta64("NaT")
1266
+ expected = PeriodIndex(["NaT"] * 9, freq="19D")
1267
+
1268
+ obj = tm.box_expected(pi, box_with_array, transpose=transpose)
1269
+ expected = tm.box_expected(expected, box_with_array, transpose=transpose)
1270
+
1271
+ result = obj + other
1272
+ tm.assert_equal(result, expected)
1273
+ result = other + obj
1274
+ tm.assert_equal(result, expected)
1275
+ result = obj - other
1276
+ tm.assert_equal(result, expected)
1277
+ msg = r"cannot subtract .* from .*"
1278
+ with pytest.raises(TypeError, match=msg):
1279
+ other - obj
1280
+
1281
+ @pytest.mark.parametrize(
1282
+ "other",
1283
+ [
1284
+ np.array(["NaT"] * 9, dtype="m8[ns]"),
1285
+ TimedeltaArray._from_sequence(["NaT"] * 9, dtype="m8[ns]"),
1286
+ ],
1287
+ )
1288
+ def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other):
1289
+ pi = period_range("1994-04-01", periods=9, freq="19D")
1290
+ expected = PeriodIndex(["NaT"] * 9, freq="19D")
1291
+
1292
+ obj = tm.box_expected(pi, box_with_array)
1293
+ expected = tm.box_expected(expected, box_with_array)
1294
+
1295
+ result = obj + other
1296
+ tm.assert_equal(result, expected)
1297
+ result = other + obj
1298
+ tm.assert_equal(result, expected)
1299
+ result = obj - other
1300
+ tm.assert_equal(result, expected)
1301
+ msg = r"cannot subtract .* from .*"
1302
+ with pytest.raises(TypeError, match=msg):
1303
+ other - obj
1304
+
1305
+ # some but not *all* NaT
1306
+ other = other.copy()
1307
+ other[0] = np.timedelta64(0, "ns")
1308
+ expected = PeriodIndex([pi[0]] + ["NaT"] * 8, freq="19D")
1309
+ expected = tm.box_expected(expected, box_with_array)
1310
+
1311
+ result = obj + other
1312
+ tm.assert_equal(result, expected)
1313
+ result = other + obj
1314
+ tm.assert_equal(result, expected)
1315
+ result = obj - other
1316
+ tm.assert_equal(result, expected)
1317
+ with pytest.raises(TypeError, match=msg):
1318
+ other - obj
1319
+
1320
+ # ---------------------------------------------------------------
1321
+ # Unsorted
1322
+
1323
+ def test_parr_add_sub_index(self):
1324
+ # Check that PeriodArray defers to Index on arithmetic ops
1325
+ pi = period_range("2000-12-31", periods=3)
1326
+ parr = pi.array
1327
+
1328
+ result = parr - pi
1329
+ expected = pi - pi
1330
+ tm.assert_index_equal(result, expected)
1331
+
1332
+ def test_parr_add_sub_object_array(self):
1333
+ pi = period_range("2000-12-31", periods=3, freq="D")
1334
+ parr = pi.array
1335
+
1336
+ other = np.array([Timedelta(days=1), pd.offsets.Day(2), 3])
1337
+
1338
+ with tm.assert_produces_warning(PerformanceWarning):
1339
+ result = parr + other
1340
+
1341
+ expected = PeriodIndex(
1342
+ ["2001-01-01", "2001-01-03", "2001-01-05"], freq="D"
1343
+ )._data.astype(object)
1344
+ tm.assert_equal(result, expected)
1345
+
1346
+ with tm.assert_produces_warning(PerformanceWarning):
1347
+ result = parr - other
1348
+
1349
+ expected = PeriodIndex(["2000-12-30"] * 3, freq="D")._data.astype(object)
1350
+ tm.assert_equal(result, expected)
1351
+
1352
+ def test_period_add_timestamp_raises(self, box_with_array):
1353
+ # GH#17983
1354
+ ts = Timestamp("2017")
1355
+ per = Period("2017", freq="M")
1356
+
1357
+ arr = pd.Index([per], dtype="Period[M]")
1358
+ arr = tm.box_expected(arr, box_with_array)
1359
+
1360
+ msg = "cannot add PeriodArray and Timestamp"
1361
+ with pytest.raises(TypeError, match=msg):
1362
+ arr + ts
1363
+ with pytest.raises(TypeError, match=msg):
1364
+ ts + arr
1365
+ msg = "cannot add PeriodArray and DatetimeArray"
1366
+ with pytest.raises(TypeError, match=msg):
1367
+ arr + Series([ts])
1368
+ with pytest.raises(TypeError, match=msg):
1369
+ Series([ts]) + arr
1370
+ with pytest.raises(TypeError, match=msg):
1371
+ arr + pd.Index([ts])
1372
+ with pytest.raises(TypeError, match=msg):
1373
+ pd.Index([ts]) + arr
1374
+
1375
+ if box_with_array is pd.DataFrame:
1376
+ msg = "cannot add PeriodArray and DatetimeArray"
1377
+ else:
1378
+ msg = r"unsupported operand type\(s\) for \+: 'Period' and 'DatetimeArray"
1379
+ with pytest.raises(TypeError, match=msg):
1380
+ arr + pd.DataFrame([ts])
1381
+ if box_with_array is pd.DataFrame:
1382
+ msg = "cannot add PeriodArray and DatetimeArray"
1383
+ else:
1384
+ msg = r"unsupported operand type\(s\) for \+: 'DatetimeArray' and 'Period'"
1385
+ with pytest.raises(TypeError, match=msg):
1386
+ pd.DataFrame([ts]) + arr
1387
+
1388
+
1389
+ class TestPeriodSeriesArithmetic:
1390
+ def test_parr_add_timedeltalike_scalar(self, three_days, box_with_array):
1391
+ # GH#13043
1392
+ ser = Series(
1393
+ [Period("2015-01-01", freq="D"), Period("2015-01-02", freq="D")],
1394
+ name="xxx",
1395
+ )
1396
+ assert ser.dtype == "Period[D]"
1397
+
1398
+ expected = Series(
1399
+ [Period("2015-01-04", freq="D"), Period("2015-01-05", freq="D")],
1400
+ name="xxx",
1401
+ )
1402
+
1403
+ obj = tm.box_expected(ser, box_with_array)
1404
+ if box_with_array is pd.DataFrame:
1405
+ assert (obj.dtypes == "Period[D]").all()
1406
+
1407
+ expected = tm.box_expected(expected, box_with_array)
1408
+
1409
+ result = obj + three_days
1410
+ tm.assert_equal(result, expected)
1411
+
1412
+ result = three_days + obj
1413
+ tm.assert_equal(result, expected)
1414
+
1415
+ def test_ops_series_period(self):
1416
+ # GH#13043
1417
+ ser = Series(
1418
+ [Period("2015-01-01", freq="D"), Period("2015-01-02", freq="D")],
1419
+ name="xxx",
1420
+ )
1421
+ assert ser.dtype == "Period[D]"
1422
+
1423
+ per = Period("2015-01-10", freq="D")
1424
+ off = per.freq
1425
+ # dtype will be object because of original dtype
1426
+ expected = Series([9 * off, 8 * off], name="xxx", dtype=object)
1427
+ tm.assert_series_equal(per - ser, expected)
1428
+ tm.assert_series_equal(ser - per, -1 * expected)
1429
+
1430
+ s2 = Series(
1431
+ [Period("2015-01-05", freq="D"), Period("2015-01-04", freq="D")],
1432
+ name="xxx",
1433
+ )
1434
+ assert s2.dtype == "Period[D]"
1435
+
1436
+ expected = Series([4 * off, 2 * off], name="xxx", dtype=object)
1437
+ tm.assert_series_equal(s2 - ser, expected)
1438
+ tm.assert_series_equal(ser - s2, -1 * expected)
1439
+
1440
+
1441
+ class TestPeriodIndexSeriesMethods:
1442
+ """Test PeriodIndex and Period Series Ops consistency"""
1443
+
1444
+ def _check(self, values, func, expected):
1445
+ idx = PeriodIndex(values)
1446
+ result = func(idx)
1447
+ tm.assert_equal(result, expected)
1448
+
1449
+ ser = Series(values)
1450
+ result = func(ser)
1451
+
1452
+ exp = Series(expected, name=values.name)
1453
+ tm.assert_series_equal(result, exp)
1454
+
1455
+ def test_pi_ops(self):
1456
+ idx = PeriodIndex(
1457
+ ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
1458
+ )
1459
+
1460
+ expected = PeriodIndex(
1461
+ ["2011-03", "2011-04", "2011-05", "2011-06"], freq="M", name="idx"
1462
+ )
1463
+
1464
+ self._check(idx, lambda x: x + 2, expected)
1465
+ self._check(idx, lambda x: 2 + x, expected)
1466
+
1467
+ self._check(idx + 2, lambda x: x - 2, idx)
1468
+
1469
+ result = idx - Period("2011-01", freq="M")
1470
+ off = idx.freq
1471
+ exp = pd.Index([0 * off, 1 * off, 2 * off, 3 * off], name="idx")
1472
+ tm.assert_index_equal(result, exp)
1473
+
1474
+ result = Period("2011-01", freq="M") - idx
1475
+ exp = pd.Index([0 * off, -1 * off, -2 * off, -3 * off], name="idx")
1476
+ tm.assert_index_equal(result, exp)
1477
+
1478
+ @pytest.mark.parametrize("ng", ["str", 1.5])
1479
+ @pytest.mark.parametrize(
1480
+ "func",
1481
+ [
1482
+ lambda obj, ng: obj + ng,
1483
+ lambda obj, ng: ng + obj,
1484
+ lambda obj, ng: obj - ng,
1485
+ lambda obj, ng: ng - obj,
1486
+ lambda obj, ng: np.add(obj, ng),
1487
+ lambda obj, ng: np.add(ng, obj),
1488
+ lambda obj, ng: np.subtract(obj, ng),
1489
+ lambda obj, ng: np.subtract(ng, obj),
1490
+ ],
1491
+ )
1492
+ def test_parr_ops_errors(self, ng, func, box_with_array):
1493
+ idx = PeriodIndex(
1494
+ ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
1495
+ )
1496
+ obj = tm.box_expected(idx, box_with_array)
1497
+ msg = "|".join(
1498
+ [
1499
+ r"unsupported operand type\(s\)",
1500
+ "can only concatenate",
1501
+ r"must be str",
1502
+ "object to str implicitly",
1503
+ ]
1504
+ )
1505
+
1506
+ with pytest.raises(TypeError, match=msg):
1507
+ func(obj, ng)
1508
+
1509
+ def test_pi_ops_nat(self):
1510
+ idx = PeriodIndex(
1511
+ ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx"
1512
+ )
1513
+ expected = PeriodIndex(
1514
+ ["2011-03", "2011-04", "NaT", "2011-06"], freq="M", name="idx"
1515
+ )
1516
+
1517
+ self._check(idx, lambda x: x + 2, expected)
1518
+ self._check(idx, lambda x: 2 + x, expected)
1519
+ self._check(idx, lambda x: np.add(x, 2), expected)
1520
+
1521
+ self._check(idx + 2, lambda x: x - 2, idx)
1522
+ self._check(idx + 2, lambda x: np.subtract(x, 2), idx)
1523
+
1524
+ # freq with mult
1525
+ idx = PeriodIndex(
1526
+ ["2011-01", "2011-02", "NaT", "2011-04"], freq="2M", name="idx"
1527
+ )
1528
+ expected = PeriodIndex(
1529
+ ["2011-07", "2011-08", "NaT", "2011-10"], freq="2M", name="idx"
1530
+ )
1531
+
1532
+ self._check(idx, lambda x: x + 3, expected)
1533
+ self._check(idx, lambda x: 3 + x, expected)
1534
+ self._check(idx, lambda x: np.add(x, 3), expected)
1535
+
1536
+ self._check(idx + 3, lambda x: x - 3, idx)
1537
+ self._check(idx + 3, lambda x: np.subtract(x, 3), idx)
1538
+
1539
+ def test_pi_ops_array_int(self):
1540
+ idx = PeriodIndex(
1541
+ ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx"
1542
+ )
1543
+ f = lambda x: x + np.array([1, 2, 3, 4])
1544
+ exp = PeriodIndex(
1545
+ ["2011-02", "2011-04", "NaT", "2011-08"], freq="M", name="idx"
1546
+ )
1547
+ self._check(idx, f, exp)
1548
+
1549
+ f = lambda x: np.add(x, np.array([4, -1, 1, 2]))
1550
+ exp = PeriodIndex(
1551
+ ["2011-05", "2011-01", "NaT", "2011-06"], freq="M", name="idx"
1552
+ )
1553
+ self._check(idx, f, exp)
1554
+
1555
+ f = lambda x: x - np.array([1, 2, 3, 4])
1556
+ exp = PeriodIndex(
1557
+ ["2010-12", "2010-12", "NaT", "2010-12"], freq="M", name="idx"
1558
+ )
1559
+ self._check(idx, f, exp)
1560
+
1561
+ f = lambda x: np.subtract(x, np.array([3, 2, 3, -2]))
1562
+ exp = PeriodIndex(
1563
+ ["2010-10", "2010-12", "NaT", "2011-06"], freq="M", name="idx"
1564
+ )
1565
+ self._check(idx, f, exp)
1566
+
1567
+ def test_pi_ops_offset(self):
1568
+ idx = PeriodIndex(
1569
+ ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01"],
1570
+ freq="D",
1571
+ name="idx",
1572
+ )
1573
+ f = lambda x: x + pd.offsets.Day()
1574
+ exp = PeriodIndex(
1575
+ ["2011-01-02", "2011-02-02", "2011-03-02", "2011-04-02"],
1576
+ freq="D",
1577
+ name="idx",
1578
+ )
1579
+ self._check(idx, f, exp)
1580
+
1581
+ f = lambda x: x + pd.offsets.Day(2)
1582
+ exp = PeriodIndex(
1583
+ ["2011-01-03", "2011-02-03", "2011-03-03", "2011-04-03"],
1584
+ freq="D",
1585
+ name="idx",
1586
+ )
1587
+ self._check(idx, f, exp)
1588
+
1589
+ f = lambda x: x - pd.offsets.Day(2)
1590
+ exp = PeriodIndex(
1591
+ ["2010-12-30", "2011-01-30", "2011-02-27", "2011-03-30"],
1592
+ freq="D",
1593
+ name="idx",
1594
+ )
1595
+ self._check(idx, f, exp)
1596
+
1597
+ def test_pi_offset_errors(self):
1598
+ idx = PeriodIndex(
1599
+ ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01"],
1600
+ freq="D",
1601
+ name="idx",
1602
+ )
1603
+ ser = Series(idx)
1604
+
1605
+ msg = (
1606
+ "Cannot add/subtract timedelta-like from PeriodArray that is not "
1607
+ "an integer multiple of the PeriodArray's freq"
1608
+ )
1609
+ for obj in [idx, ser]:
1610
+ with pytest.raises(IncompatibleFrequency, match=msg):
1611
+ obj + pd.offsets.Hour(2)
1612
+
1613
+ with pytest.raises(IncompatibleFrequency, match=msg):
1614
+ pd.offsets.Hour(2) + obj
1615
+
1616
+ with pytest.raises(IncompatibleFrequency, match=msg):
1617
+ obj - pd.offsets.Hour(2)
1618
+
1619
+ def test_pi_sub_period(self):
1620
+ # GH#13071
1621
+ idx = PeriodIndex(
1622
+ ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
1623
+ )
1624
+
1625
+ result = idx - Period("2012-01", freq="M")
1626
+ off = idx.freq
1627
+ exp = pd.Index([-12 * off, -11 * off, -10 * off, -9 * off], name="idx")
1628
+ tm.assert_index_equal(result, exp)
1629
+
1630
+ result = np.subtract(idx, Period("2012-01", freq="M"))
1631
+ tm.assert_index_equal(result, exp)
1632
+
1633
+ result = Period("2012-01", freq="M") - idx
1634
+ exp = pd.Index([12 * off, 11 * off, 10 * off, 9 * off], name="idx")
1635
+ tm.assert_index_equal(result, exp)
1636
+
1637
+ result = np.subtract(Period("2012-01", freq="M"), idx)
1638
+ tm.assert_index_equal(result, exp)
1639
+
1640
+ exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
1641
+ result = idx - Period("NaT", freq="M")
1642
+ tm.assert_index_equal(result, exp)
1643
+ assert result.freq == exp.freq
1644
+
1645
+ result = Period("NaT", freq="M") - idx
1646
+ tm.assert_index_equal(result, exp)
1647
+ assert result.freq == exp.freq
1648
+
1649
+ def test_pi_sub_pdnat(self):
1650
+ # GH#13071, GH#19389
1651
+ idx = PeriodIndex(
1652
+ ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx"
1653
+ )
1654
+ exp = TimedeltaIndex([pd.NaT] * 4, name="idx")
1655
+ tm.assert_index_equal(pd.NaT - idx, exp)
1656
+ tm.assert_index_equal(idx - pd.NaT, exp)
1657
+
1658
+ def test_pi_sub_period_nat(self):
1659
+ # GH#13071
1660
+ idx = PeriodIndex(
1661
+ ["2011-01", "NaT", "2011-03", "2011-04"], freq="M", name="idx"
1662
+ )
1663
+
1664
+ result = idx - Period("2012-01", freq="M")
1665
+ off = idx.freq
1666
+ exp = pd.Index([-12 * off, pd.NaT, -10 * off, -9 * off], name="idx")
1667
+ tm.assert_index_equal(result, exp)
1668
+
1669
+ result = Period("2012-01", freq="M") - idx
1670
+ exp = pd.Index([12 * off, pd.NaT, 10 * off, 9 * off], name="idx")
1671
+ tm.assert_index_equal(result, exp)
1672
+
1673
+ exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
1674
+ tm.assert_index_equal(idx - Period("NaT", freq="M"), exp)
1675
+ tm.assert_index_equal(Period("NaT", freq="M") - idx, exp)
venv/lib/python3.10/site-packages/pandas/tests/arithmetic/test_timedelta64.py ADDED
@@ -0,0 +1,2173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Arithmetic tests for DataFrame/Series/Index/Array classes that should
2
+ # behave identically.
3
+ from datetime import (
4
+ datetime,
5
+ timedelta,
6
+ )
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from pandas.errors import (
12
+ OutOfBoundsDatetime,
13
+ PerformanceWarning,
14
+ )
15
+
16
+ import pandas as pd
17
+ from pandas import (
18
+ DataFrame,
19
+ DatetimeIndex,
20
+ Index,
21
+ NaT,
22
+ Series,
23
+ Timedelta,
24
+ TimedeltaIndex,
25
+ Timestamp,
26
+ offsets,
27
+ timedelta_range,
28
+ )
29
+ import pandas._testing as tm
30
+ from pandas.core.arrays import NumpyExtensionArray
31
+ from pandas.tests.arithmetic.common import (
32
+ assert_invalid_addsub_type,
33
+ assert_invalid_comparison,
34
+ get_upcast_box,
35
+ )
36
+
37
+
38
+ def assert_dtype(obj, expected_dtype):
39
+ """
40
+ Helper to check the dtype for a Series, Index, or single-column DataFrame.
41
+ """
42
+ dtype = tm.get_dtype(obj)
43
+
44
+ assert dtype == expected_dtype
45
+
46
+
47
+ def get_expected_name(box, names):
48
+ if box is DataFrame:
49
+ # Since we are operating with a DataFrame and a non-DataFrame,
50
+ # the non-DataFrame is cast to Series and its name ignored.
51
+ exname = names[0]
52
+ elif box in [tm.to_array, pd.array]:
53
+ exname = names[1]
54
+ else:
55
+ exname = names[2]
56
+ return exname
57
+
58
+
59
+ # ------------------------------------------------------------------
60
+ # Timedelta64[ns] dtype Comparisons
61
+
62
+
63
+ class TestTimedelta64ArrayLikeComparisons:
64
+ # Comparison tests for timedelta64[ns] vectors fully parametrized over
65
+ # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all comparison
66
+ # tests will eventually end up here.
67
+
68
+ def test_compare_timedelta64_zerodim(self, box_with_array):
69
+ # GH#26689 should unbox when comparing with zerodim array
70
+ box = box_with_array
71
+ xbox = box_with_array if box_with_array not in [Index, pd.array] else np.ndarray
72
+
73
+ tdi = timedelta_range("2h", periods=4)
74
+ other = np.array(tdi.to_numpy()[0])
75
+
76
+ tdi = tm.box_expected(tdi, box)
77
+ res = tdi <= other
78
+ expected = np.array([True, False, False, False])
79
+ expected = tm.box_expected(expected, xbox)
80
+ tm.assert_equal(res, expected)
81
+
82
+ @pytest.mark.parametrize(
83
+ "td_scalar",
84
+ [
85
+ timedelta(days=1),
86
+ Timedelta(days=1),
87
+ Timedelta(days=1).to_timedelta64(),
88
+ offsets.Hour(24),
89
+ ],
90
+ )
91
+ def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar):
92
+ # regression test for GH#5963
93
+ box = box_with_array
94
+ xbox = box if box not in [Index, pd.array] else np.ndarray
95
+
96
+ ser = Series([timedelta(days=1), timedelta(days=2)])
97
+ ser = tm.box_expected(ser, box)
98
+ actual = ser > td_scalar
99
+ expected = Series([False, True])
100
+ expected = tm.box_expected(expected, xbox)
101
+ tm.assert_equal(actual, expected)
102
+
103
+ @pytest.mark.parametrize(
104
+ "invalid",
105
+ [
106
+ 345600000000000,
107
+ "a",
108
+ Timestamp("2021-01-01"),
109
+ Timestamp("2021-01-01").now("UTC"),
110
+ Timestamp("2021-01-01").now().to_datetime64(),
111
+ Timestamp("2021-01-01").now().to_pydatetime(),
112
+ Timestamp("2021-01-01").date(),
113
+ np.array(4), # zero-dim mismatched dtype
114
+ ],
115
+ )
116
+ def test_td64_comparisons_invalid(self, box_with_array, invalid):
117
+ # GH#13624 for str
118
+ box = box_with_array
119
+
120
+ rng = timedelta_range("1 days", periods=10)
121
+ obj = tm.box_expected(rng, box)
122
+
123
+ assert_invalid_comparison(obj, invalid, box)
124
+
125
+ @pytest.mark.parametrize(
126
+ "other",
127
+ [
128
+ list(range(10)),
129
+ np.arange(10),
130
+ np.arange(10).astype(np.float32),
131
+ np.arange(10).astype(object),
132
+ pd.date_range("1970-01-01", periods=10, tz="UTC").array,
133
+ np.array(pd.date_range("1970-01-01", periods=10)),
134
+ list(pd.date_range("1970-01-01", periods=10)),
135
+ pd.date_range("1970-01-01", periods=10).astype(object),
136
+ pd.period_range("1971-01-01", freq="D", periods=10).array,
137
+ pd.period_range("1971-01-01", freq="D", periods=10).astype(object),
138
+ ],
139
+ )
140
+ def test_td64arr_cmp_arraylike_invalid(self, other, box_with_array):
141
+ # We don't parametrize this over box_with_array because listlike
142
+ # other plays poorly with assert_invalid_comparison reversed checks
143
+
144
+ rng = timedelta_range("1 days", periods=10)._data
145
+ rng = tm.box_expected(rng, box_with_array)
146
+ assert_invalid_comparison(rng, other, box_with_array)
147
+
148
+ def test_td64arr_cmp_mixed_invalid(self):
149
+ rng = timedelta_range("1 days", periods=5)._data
150
+ other = np.array([0, 1, 2, rng[3], Timestamp("2021-01-01")])
151
+
152
+ result = rng == other
153
+ expected = np.array([False, False, False, True, False])
154
+ tm.assert_numpy_array_equal(result, expected)
155
+
156
+ result = rng != other
157
+ tm.assert_numpy_array_equal(result, ~expected)
158
+
159
+ msg = "Invalid comparison between|Cannot compare type|not supported between"
160
+ with pytest.raises(TypeError, match=msg):
161
+ rng < other
162
+ with pytest.raises(TypeError, match=msg):
163
+ rng > other
164
+ with pytest.raises(TypeError, match=msg):
165
+ rng <= other
166
+ with pytest.raises(TypeError, match=msg):
167
+ rng >= other
168
+
169
+
170
+ class TestTimedelta64ArrayComparisons:
171
+ # TODO: All of these need to be parametrized over box
172
+
173
+ @pytest.mark.parametrize("dtype", [None, object])
174
+ def test_comp_nat(self, dtype):
175
+ left = TimedeltaIndex([Timedelta("1 days"), NaT, Timedelta("3 days")])
176
+ right = TimedeltaIndex([NaT, NaT, Timedelta("3 days")])
177
+
178
+ lhs, rhs = left, right
179
+ if dtype is object:
180
+ lhs, rhs = left.astype(object), right.astype(object)
181
+
182
+ result = rhs == lhs
183
+ expected = np.array([False, False, True])
184
+ tm.assert_numpy_array_equal(result, expected)
185
+
186
+ result = rhs != lhs
187
+ expected = np.array([True, True, False])
188
+ tm.assert_numpy_array_equal(result, expected)
189
+
190
+ expected = np.array([False, False, False])
191
+ tm.assert_numpy_array_equal(lhs == NaT, expected)
192
+ tm.assert_numpy_array_equal(NaT == rhs, expected)
193
+
194
+ expected = np.array([True, True, True])
195
+ tm.assert_numpy_array_equal(lhs != NaT, expected)
196
+ tm.assert_numpy_array_equal(NaT != lhs, expected)
197
+
198
+ expected = np.array([False, False, False])
199
+ tm.assert_numpy_array_equal(lhs < NaT, expected)
200
+ tm.assert_numpy_array_equal(NaT > lhs, expected)
201
+
202
+ @pytest.mark.parametrize(
203
+ "idx2",
204
+ [
205
+ TimedeltaIndex(
206
+ ["2 day", "2 day", NaT, NaT, "1 day 00:00:02", "5 days 00:00:03"]
207
+ ),
208
+ np.array(
209
+ [
210
+ np.timedelta64(2, "D"),
211
+ np.timedelta64(2, "D"),
212
+ np.timedelta64("nat"),
213
+ np.timedelta64("nat"),
214
+ np.timedelta64(1, "D") + np.timedelta64(2, "s"),
215
+ np.timedelta64(5, "D") + np.timedelta64(3, "s"),
216
+ ]
217
+ ),
218
+ ],
219
+ )
220
+ def test_comparisons_nat(self, idx2):
221
+ idx1 = TimedeltaIndex(
222
+ [
223
+ "1 day",
224
+ NaT,
225
+ "1 day 00:00:01",
226
+ NaT,
227
+ "1 day 00:00:01",
228
+ "5 day 00:00:03",
229
+ ]
230
+ )
231
+ # Check pd.NaT is handles as the same as np.nan
232
+ result = idx1 < idx2
233
+ expected = np.array([True, False, False, False, True, False])
234
+ tm.assert_numpy_array_equal(result, expected)
235
+
236
+ result = idx2 > idx1
237
+ expected = np.array([True, False, False, False, True, False])
238
+ tm.assert_numpy_array_equal(result, expected)
239
+
240
+ result = idx1 <= idx2
241
+ expected = np.array([True, False, False, False, True, True])
242
+ tm.assert_numpy_array_equal(result, expected)
243
+
244
+ result = idx2 >= idx1
245
+ expected = np.array([True, False, False, False, True, True])
246
+ tm.assert_numpy_array_equal(result, expected)
247
+
248
+ result = idx1 == idx2
249
+ expected = np.array([False, False, False, False, False, True])
250
+ tm.assert_numpy_array_equal(result, expected)
251
+
252
+ result = idx1 != idx2
253
+ expected = np.array([True, True, True, True, True, False])
254
+ tm.assert_numpy_array_equal(result, expected)
255
+
256
+ # TODO: better name
257
+ def test_comparisons_coverage(self):
258
+ rng = timedelta_range("1 days", periods=10)
259
+
260
+ result = rng < rng[3]
261
+ expected = np.array([True, True, True] + [False] * 7)
262
+ tm.assert_numpy_array_equal(result, expected)
263
+
264
+ result = rng == list(rng)
265
+ exp = rng == rng
266
+ tm.assert_numpy_array_equal(result, exp)
267
+
268
+
269
+ # ------------------------------------------------------------------
270
+ # Timedelta64[ns] dtype Arithmetic Operations
271
+
272
+
273
+ class TestTimedelta64ArithmeticUnsorted:
274
+ # Tests moved from type-specific test files but not
275
+ # yet sorted/parametrized/de-duplicated
276
+
277
+ def test_ufunc_coercions(self):
278
+ # normal ops are also tested in tseries/test_timedeltas.py
279
+ idx = TimedeltaIndex(["2h", "4h", "6h", "8h", "10h"], freq="2h", name="x")
280
+
281
+ for result in [idx * 2, np.multiply(idx, 2)]:
282
+ assert isinstance(result, TimedeltaIndex)
283
+ exp = TimedeltaIndex(["4h", "8h", "12h", "16h", "20h"], freq="4h", name="x")
284
+ tm.assert_index_equal(result, exp)
285
+ assert result.freq == "4h"
286
+
287
+ for result in [idx / 2, np.divide(idx, 2)]:
288
+ assert isinstance(result, TimedeltaIndex)
289
+ exp = TimedeltaIndex(["1h", "2h", "3h", "4h", "5h"], freq="h", name="x")
290
+ tm.assert_index_equal(result, exp)
291
+ assert result.freq == "h"
292
+
293
+ for result in [-idx, np.negative(idx)]:
294
+ assert isinstance(result, TimedeltaIndex)
295
+ exp = TimedeltaIndex(
296
+ ["-2h", "-4h", "-6h", "-8h", "-10h"], freq="-2h", name="x"
297
+ )
298
+ tm.assert_index_equal(result, exp)
299
+ assert result.freq == "-2h"
300
+
301
+ idx = TimedeltaIndex(["-2h", "-1h", "0h", "1h", "2h"], freq="h", name="x")
302
+ for result in [abs(idx), np.absolute(idx)]:
303
+ assert isinstance(result, TimedeltaIndex)
304
+ exp = TimedeltaIndex(["2h", "1h", "0h", "1h", "2h"], freq=None, name="x")
305
+ tm.assert_index_equal(result, exp)
306
+ assert result.freq is None
307
+
308
+ def test_subtraction_ops(self):
309
+ # with datetimes/timedelta and tdi/dti
310
+ tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
311
+ dti = pd.date_range("20130101", periods=3, name="bar")
312
+ td = Timedelta("1 days")
313
+ dt = Timestamp("20130101")
314
+
315
+ msg = "cannot subtract a datelike from a TimedeltaArray"
316
+ with pytest.raises(TypeError, match=msg):
317
+ tdi - dt
318
+ with pytest.raises(TypeError, match=msg):
319
+ tdi - dti
320
+
321
+ msg = r"unsupported operand type\(s\) for -"
322
+ with pytest.raises(TypeError, match=msg):
323
+ td - dt
324
+
325
+ msg = "(bad|unsupported) operand type for unary"
326
+ with pytest.raises(TypeError, match=msg):
327
+ td - dti
328
+
329
+ result = dt - dti
330
+ expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"], name="bar")
331
+ tm.assert_index_equal(result, expected)
332
+
333
+ result = dti - dt
334
+ expected = TimedeltaIndex(["0 days", "1 days", "2 days"], name="bar")
335
+ tm.assert_index_equal(result, expected)
336
+
337
+ result = tdi - td
338
+ expected = TimedeltaIndex(["0 days", NaT, "1 days"], name="foo")
339
+ tm.assert_index_equal(result, expected)
340
+
341
+ result = td - tdi
342
+ expected = TimedeltaIndex(["0 days", NaT, "-1 days"], name="foo")
343
+ tm.assert_index_equal(result, expected)
344
+
345
+ result = dti - td
346
+ expected = DatetimeIndex(
347
+ ["20121231", "20130101", "20130102"], dtype="M8[ns]", freq="D", name="bar"
348
+ )
349
+ tm.assert_index_equal(result, expected)
350
+
351
+ result = dt - tdi
352
+ expected = DatetimeIndex(
353
+ ["20121231", NaT, "20121230"], dtype="M8[ns]", name="foo"
354
+ )
355
+ tm.assert_index_equal(result, expected)
356
+
357
+ def test_subtraction_ops_with_tz(self, box_with_array):
358
+ # check that dt/dti subtraction ops with tz are validated
359
+ dti = pd.date_range("20130101", periods=3)
360
+ dti = tm.box_expected(dti, box_with_array)
361
+ ts = Timestamp("20130101")
362
+ dt = ts.to_pydatetime()
363
+ dti_tz = pd.date_range("20130101", periods=3).tz_localize("US/Eastern")
364
+ dti_tz = tm.box_expected(dti_tz, box_with_array)
365
+ ts_tz = Timestamp("20130101").tz_localize("US/Eastern")
366
+ ts_tz2 = Timestamp("20130101").tz_localize("CET")
367
+ dt_tz = ts_tz.to_pydatetime()
368
+ td = Timedelta("1 days")
369
+
370
+ def _check(result, expected):
371
+ assert result == expected
372
+ assert isinstance(result, Timedelta)
373
+
374
+ # scalars
375
+ result = ts - ts
376
+ expected = Timedelta("0 days")
377
+ _check(result, expected)
378
+
379
+ result = dt_tz - ts_tz
380
+ expected = Timedelta("0 days")
381
+ _check(result, expected)
382
+
383
+ result = ts_tz - dt_tz
384
+ expected = Timedelta("0 days")
385
+ _check(result, expected)
386
+
387
+ # tz mismatches
388
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects."
389
+ with pytest.raises(TypeError, match=msg):
390
+ dt_tz - ts
391
+ msg = "can't subtract offset-naive and offset-aware datetimes"
392
+ with pytest.raises(TypeError, match=msg):
393
+ dt_tz - dt
394
+ msg = "can't subtract offset-naive and offset-aware datetimes"
395
+ with pytest.raises(TypeError, match=msg):
396
+ dt - dt_tz
397
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects."
398
+ with pytest.raises(TypeError, match=msg):
399
+ ts - dt_tz
400
+ with pytest.raises(TypeError, match=msg):
401
+ ts_tz2 - ts
402
+ with pytest.raises(TypeError, match=msg):
403
+ ts_tz2 - dt
404
+
405
+ msg = "Cannot subtract tz-naive and tz-aware"
406
+ # with dti
407
+ with pytest.raises(TypeError, match=msg):
408
+ dti - ts_tz
409
+ with pytest.raises(TypeError, match=msg):
410
+ dti_tz - ts
411
+
412
+ result = dti_tz - dt_tz
413
+ expected = TimedeltaIndex(["0 days", "1 days", "2 days"])
414
+ expected = tm.box_expected(expected, box_with_array)
415
+ tm.assert_equal(result, expected)
416
+
417
+ result = dt_tz - dti_tz
418
+ expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"])
419
+ expected = tm.box_expected(expected, box_with_array)
420
+ tm.assert_equal(result, expected)
421
+
422
+ result = dti_tz - ts_tz
423
+ expected = TimedeltaIndex(["0 days", "1 days", "2 days"])
424
+ expected = tm.box_expected(expected, box_with_array)
425
+ tm.assert_equal(result, expected)
426
+
427
+ result = ts_tz - dti_tz
428
+ expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"])
429
+ expected = tm.box_expected(expected, box_with_array)
430
+ tm.assert_equal(result, expected)
431
+
432
+ result = td - td
433
+ expected = Timedelta("0 days")
434
+ _check(result, expected)
435
+
436
+ result = dti_tz - td
437
+ expected = DatetimeIndex(
438
+ ["20121231", "20130101", "20130102"], tz="US/Eastern"
439
+ ).as_unit("ns")
440
+ expected = tm.box_expected(expected, box_with_array)
441
+ tm.assert_equal(result, expected)
442
+
443
+ def test_dti_tdi_numeric_ops(self):
444
+ # These are normally union/diff set-like ops
445
+ tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
446
+ dti = pd.date_range("20130101", periods=3, name="bar")
447
+
448
+ result = tdi - tdi
449
+ expected = TimedeltaIndex(["0 days", NaT, "0 days"], name="foo")
450
+ tm.assert_index_equal(result, expected)
451
+
452
+ result = tdi + tdi
453
+ expected = TimedeltaIndex(["2 days", NaT, "4 days"], name="foo")
454
+ tm.assert_index_equal(result, expected)
455
+
456
+ result = dti - tdi # name will be reset
457
+ expected = DatetimeIndex(["20121231", NaT, "20130101"], dtype="M8[ns]")
458
+ tm.assert_index_equal(result, expected)
459
+
460
+ def test_addition_ops(self):
461
+ # with datetimes/timedelta and tdi/dti
462
+ tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
463
+ dti = pd.date_range("20130101", periods=3, name="bar")
464
+ td = Timedelta("1 days")
465
+ dt = Timestamp("20130101")
466
+
467
+ result = tdi + dt
468
+ expected = DatetimeIndex(
469
+ ["20130102", NaT, "20130103"], dtype="M8[ns]", name="foo"
470
+ )
471
+ tm.assert_index_equal(result, expected)
472
+
473
+ result = dt + tdi
474
+ expected = DatetimeIndex(
475
+ ["20130102", NaT, "20130103"], dtype="M8[ns]", name="foo"
476
+ )
477
+ tm.assert_index_equal(result, expected)
478
+
479
+ result = td + tdi
480
+ expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo")
481
+ tm.assert_index_equal(result, expected)
482
+
483
+ result = tdi + td
484
+ expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo")
485
+ tm.assert_index_equal(result, expected)
486
+
487
+ # unequal length
488
+ msg = "cannot add indices of unequal length"
489
+ with pytest.raises(ValueError, match=msg):
490
+ tdi + dti[0:1]
491
+ with pytest.raises(ValueError, match=msg):
492
+ tdi[0:1] + dti
493
+
494
+ # random indexes
495
+ msg = "Addition/subtraction of integers and integer-arrays"
496
+ with pytest.raises(TypeError, match=msg):
497
+ tdi + Index([1, 2, 3], dtype=np.int64)
498
+
499
+ # this is a union!
500
+ # FIXME: don't leave commented-out
501
+ # pytest.raises(TypeError, lambda : Index([1,2,3]) + tdi)
502
+
503
+ result = tdi + dti # name will be reset
504
+ expected = DatetimeIndex(["20130102", NaT, "20130105"], dtype="M8[ns]")
505
+ tm.assert_index_equal(result, expected)
506
+
507
+ result = dti + tdi # name will be reset
508
+ expected = DatetimeIndex(["20130102", NaT, "20130105"], dtype="M8[ns]")
509
+ tm.assert_index_equal(result, expected)
510
+
511
+ result = dt + td
512
+ expected = Timestamp("20130102")
513
+ assert result == expected
514
+
515
+ result = td + dt
516
+ expected = Timestamp("20130102")
517
+ assert result == expected
518
+
519
+ # TODO: Needs more informative name, probably split up into
520
+ # more targeted tests
521
+ @pytest.mark.parametrize("freq", ["D", "B"])
522
+ def test_timedelta(self, freq):
523
+ index = pd.date_range("1/1/2000", periods=50, freq=freq)
524
+
525
+ shifted = index + timedelta(1)
526
+ back = shifted + timedelta(-1)
527
+ back = back._with_freq("infer")
528
+ tm.assert_index_equal(index, back)
529
+
530
+ if freq == "D":
531
+ expected = pd.tseries.offsets.Day(1)
532
+ assert index.freq == expected
533
+ assert shifted.freq == expected
534
+ assert back.freq == expected
535
+ else: # freq == 'B'
536
+ assert index.freq == pd.tseries.offsets.BusinessDay(1)
537
+ assert shifted.freq is None
538
+ assert back.freq == pd.tseries.offsets.BusinessDay(1)
539
+
540
+ result = index - timedelta(1)
541
+ expected = index + timedelta(-1)
542
+ tm.assert_index_equal(result, expected)
543
+
544
+ def test_timedelta_tick_arithmetic(self):
545
+ # GH#4134, buggy with timedeltas
546
+ rng = pd.date_range("2013", "2014")
547
+ s = Series(rng)
548
+ result1 = rng - offsets.Hour(1)
549
+ result2 = DatetimeIndex(s - np.timedelta64(100000000))
550
+ result3 = rng - np.timedelta64(100000000)
551
+ result4 = DatetimeIndex(s - offsets.Hour(1))
552
+
553
+ assert result1.freq == rng.freq
554
+ result1 = result1._with_freq(None)
555
+ tm.assert_index_equal(result1, result4)
556
+
557
+ assert result3.freq == rng.freq
558
+ result3 = result3._with_freq(None)
559
+ tm.assert_index_equal(result2, result3)
560
+
561
+ def test_tda_add_sub_index(self):
562
+ # Check that TimedeltaArray defers to Index on arithmetic ops
563
+ tdi = TimedeltaIndex(["1 days", NaT, "2 days"])
564
+ tda = tdi.array
565
+
566
+ dti = pd.date_range("1999-12-31", periods=3, freq="D")
567
+
568
+ result = tda + dti
569
+ expected = tdi + dti
570
+ tm.assert_index_equal(result, expected)
571
+
572
+ result = tda + tdi
573
+ expected = tdi + tdi
574
+ tm.assert_index_equal(result, expected)
575
+
576
+ result = tda - tdi
577
+ expected = tdi - tdi
578
+ tm.assert_index_equal(result, expected)
579
+
580
+ def test_tda_add_dt64_object_array(self, box_with_array, tz_naive_fixture):
581
+ # Result should be cast back to DatetimeArray
582
+ box = box_with_array
583
+
584
+ dti = pd.date_range("2016-01-01", periods=3, tz=tz_naive_fixture)
585
+ dti = dti._with_freq(None)
586
+ tdi = dti - dti
587
+
588
+ obj = tm.box_expected(tdi, box)
589
+ other = tm.box_expected(dti, box)
590
+
591
+ with tm.assert_produces_warning(PerformanceWarning):
592
+ result = obj + other.astype(object)
593
+ tm.assert_equal(result, other.astype(object))
594
+
595
+ # -------------------------------------------------------------
596
+ # Binary operations TimedeltaIndex and timedelta-like
597
+
598
+ def test_tdi_iadd_timedeltalike(self, two_hours, box_with_array):
599
+ # only test adding/sub offsets as + is now numeric
600
+ rng = timedelta_range("1 days", "10 days")
601
+ expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D")
602
+
603
+ rng = tm.box_expected(rng, box_with_array)
604
+ expected = tm.box_expected(expected, box_with_array)
605
+
606
+ orig_rng = rng
607
+ rng += two_hours
608
+ tm.assert_equal(rng, expected)
609
+ if box_with_array is not Index:
610
+ # Check that operation is actually inplace
611
+ tm.assert_equal(orig_rng, expected)
612
+
613
+ def test_tdi_isub_timedeltalike(self, two_hours, box_with_array):
614
+ # only test adding/sub offsets as - is now numeric
615
+ rng = timedelta_range("1 days", "10 days")
616
+ expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00")
617
+
618
+ rng = tm.box_expected(rng, box_with_array)
619
+ expected = tm.box_expected(expected, box_with_array)
620
+
621
+ orig_rng = rng
622
+ rng -= two_hours
623
+ tm.assert_equal(rng, expected)
624
+ if box_with_array is not Index:
625
+ # Check that operation is actually inplace
626
+ tm.assert_equal(orig_rng, expected)
627
+
628
+ # -------------------------------------------------------------
629
+
630
+ def test_tdi_ops_attributes(self):
631
+ rng = timedelta_range("2 days", periods=5, freq="2D", name="x")
632
+
633
+ result = rng + 1 * rng.freq
634
+ exp = timedelta_range("4 days", periods=5, freq="2D", name="x")
635
+ tm.assert_index_equal(result, exp)
636
+ assert result.freq == "2D"
637
+
638
+ result = rng - 2 * rng.freq
639
+ exp = timedelta_range("-2 days", periods=5, freq="2D", name="x")
640
+ tm.assert_index_equal(result, exp)
641
+ assert result.freq == "2D"
642
+
643
+ result = rng * 2
644
+ exp = timedelta_range("4 days", periods=5, freq="4D", name="x")
645
+ tm.assert_index_equal(result, exp)
646
+ assert result.freq == "4D"
647
+
648
+ result = rng / 2
649
+ exp = timedelta_range("1 days", periods=5, freq="D", name="x")
650
+ tm.assert_index_equal(result, exp)
651
+ assert result.freq == "D"
652
+
653
+ result = -rng
654
+ exp = timedelta_range("-2 days", periods=5, freq="-2D", name="x")
655
+ tm.assert_index_equal(result, exp)
656
+ assert result.freq == "-2D"
657
+
658
+ rng = timedelta_range("-2 days", periods=5, freq="D", name="x")
659
+
660
+ result = abs(rng)
661
+ exp = TimedeltaIndex(
662
+ ["2 days", "1 days", "0 days", "1 days", "2 days"], name="x"
663
+ )
664
+ tm.assert_index_equal(result, exp)
665
+ assert result.freq is None
666
+
667
+
668
+ class TestAddSubNaTMasking:
669
+ # TODO: parametrize over boxes
670
+
671
+ @pytest.mark.parametrize("str_ts", ["1950-01-01", "1980-01-01"])
672
+ def test_tdarr_add_timestamp_nat_masking(self, box_with_array, str_ts):
673
+ # GH#17991 checking for overflow-masking with NaT
674
+ tdinat = pd.to_timedelta(["24658 days 11:15:00", "NaT"])
675
+ tdobj = tm.box_expected(tdinat, box_with_array)
676
+
677
+ ts = Timestamp(str_ts)
678
+ ts_variants = [
679
+ ts,
680
+ ts.to_pydatetime(),
681
+ ts.to_datetime64().astype("datetime64[ns]"),
682
+ ts.to_datetime64().astype("datetime64[D]"),
683
+ ]
684
+
685
+ for variant in ts_variants:
686
+ res = tdobj + variant
687
+ if box_with_array is DataFrame:
688
+ assert res.iloc[1, 1] is NaT
689
+ else:
690
+ assert res[1] is NaT
691
+
692
+ def test_tdi_add_overflow(self):
693
+ # See GH#14068
694
+ # preliminary test scalar analogue of vectorized tests below
695
+ # TODO: Make raised error message more informative and test
696
+ with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"):
697
+ pd.to_timedelta(106580, "D") + Timestamp("2000")
698
+ with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"):
699
+ Timestamp("2000") + pd.to_timedelta(106580, "D")
700
+
701
+ _NaT = NaT._value + 1
702
+ msg = "Overflow in int64 addition"
703
+ with pytest.raises(OverflowError, match=msg):
704
+ pd.to_timedelta([106580], "D") + Timestamp("2000")
705
+ with pytest.raises(OverflowError, match=msg):
706
+ Timestamp("2000") + pd.to_timedelta([106580], "D")
707
+ with pytest.raises(OverflowError, match=msg):
708
+ pd.to_timedelta([_NaT]) - Timedelta("1 days")
709
+ with pytest.raises(OverflowError, match=msg):
710
+ pd.to_timedelta(["5 days", _NaT]) - Timedelta("1 days")
711
+ with pytest.raises(OverflowError, match=msg):
712
+ (
713
+ pd.to_timedelta([_NaT, "5 days", "1 hours"])
714
+ - pd.to_timedelta(["7 seconds", _NaT, "4 hours"])
715
+ )
716
+
717
+ # These should not overflow!
718
+ exp = TimedeltaIndex([NaT])
719
+ result = pd.to_timedelta([NaT]) - Timedelta("1 days")
720
+ tm.assert_index_equal(result, exp)
721
+
722
+ exp = TimedeltaIndex(["4 days", NaT])
723
+ result = pd.to_timedelta(["5 days", NaT]) - Timedelta("1 days")
724
+ tm.assert_index_equal(result, exp)
725
+
726
+ exp = TimedeltaIndex([NaT, NaT, "5 hours"])
727
+ result = pd.to_timedelta([NaT, "5 days", "1 hours"]) + pd.to_timedelta(
728
+ ["7 seconds", NaT, "4 hours"]
729
+ )
730
+ tm.assert_index_equal(result, exp)
731
+
732
+
733
+ class TestTimedeltaArraylikeAddSubOps:
734
+ # Tests for timedelta64[ns] __add__, __sub__, __radd__, __rsub__
735
+
736
+ def test_sub_nat_retain_unit(self):
737
+ ser = pd.to_timedelta(Series(["00:00:01"])).astype("m8[s]")
738
+
739
+ result = ser - NaT
740
+ expected = Series([NaT], dtype="m8[s]")
741
+ tm.assert_series_equal(result, expected)
742
+
743
+ # TODO: moved from tests.indexes.timedeltas.test_arithmetic; needs
744
+ # parametrization+de-duplication
745
+ def test_timedelta_ops_with_missing_values(self):
746
+ # setup
747
+ s1 = pd.to_timedelta(Series(["00:00:01"]))
748
+ s2 = pd.to_timedelta(Series(["00:00:02"]))
749
+
750
+ sn = pd.to_timedelta(Series([NaT], dtype="m8[ns]"))
751
+
752
+ df1 = DataFrame(["00:00:01"]).apply(pd.to_timedelta)
753
+ df2 = DataFrame(["00:00:02"]).apply(pd.to_timedelta)
754
+
755
+ dfn = DataFrame([NaT._value]).apply(pd.to_timedelta)
756
+
757
+ scalar1 = pd.to_timedelta("00:00:01")
758
+ scalar2 = pd.to_timedelta("00:00:02")
759
+ timedelta_NaT = pd.to_timedelta("NaT")
760
+
761
+ actual = scalar1 + scalar1
762
+ assert actual == scalar2
763
+ actual = scalar2 - scalar1
764
+ assert actual == scalar1
765
+
766
+ actual = s1 + s1
767
+ tm.assert_series_equal(actual, s2)
768
+ actual = s2 - s1
769
+ tm.assert_series_equal(actual, s1)
770
+
771
+ actual = s1 + scalar1
772
+ tm.assert_series_equal(actual, s2)
773
+ actual = scalar1 + s1
774
+ tm.assert_series_equal(actual, s2)
775
+ actual = s2 - scalar1
776
+ tm.assert_series_equal(actual, s1)
777
+ actual = -scalar1 + s2
778
+ tm.assert_series_equal(actual, s1)
779
+
780
+ actual = s1 + timedelta_NaT
781
+ tm.assert_series_equal(actual, sn)
782
+ actual = timedelta_NaT + s1
783
+ tm.assert_series_equal(actual, sn)
784
+ actual = s1 - timedelta_NaT
785
+ tm.assert_series_equal(actual, sn)
786
+ actual = -timedelta_NaT + s1
787
+ tm.assert_series_equal(actual, sn)
788
+
789
+ msg = "unsupported operand type"
790
+ with pytest.raises(TypeError, match=msg):
791
+ s1 + np.nan
792
+ with pytest.raises(TypeError, match=msg):
793
+ np.nan + s1
794
+ with pytest.raises(TypeError, match=msg):
795
+ s1 - np.nan
796
+ with pytest.raises(TypeError, match=msg):
797
+ -np.nan + s1
798
+
799
+ actual = s1 + NaT
800
+ tm.assert_series_equal(actual, sn)
801
+ actual = s2 - NaT
802
+ tm.assert_series_equal(actual, sn)
803
+
804
+ actual = s1 + df1
805
+ tm.assert_frame_equal(actual, df2)
806
+ actual = s2 - df1
807
+ tm.assert_frame_equal(actual, df1)
808
+ actual = df1 + s1
809
+ tm.assert_frame_equal(actual, df2)
810
+ actual = df2 - s1
811
+ tm.assert_frame_equal(actual, df1)
812
+
813
+ actual = df1 + df1
814
+ tm.assert_frame_equal(actual, df2)
815
+ actual = df2 - df1
816
+ tm.assert_frame_equal(actual, df1)
817
+
818
+ actual = df1 + scalar1
819
+ tm.assert_frame_equal(actual, df2)
820
+ actual = df2 - scalar1
821
+ tm.assert_frame_equal(actual, df1)
822
+
823
+ actual = df1 + timedelta_NaT
824
+ tm.assert_frame_equal(actual, dfn)
825
+ actual = df1 - timedelta_NaT
826
+ tm.assert_frame_equal(actual, dfn)
827
+
828
+ msg = "cannot subtract a datelike from|unsupported operand type"
829
+ with pytest.raises(TypeError, match=msg):
830
+ df1 + np.nan
831
+ with pytest.raises(TypeError, match=msg):
832
+ df1 - np.nan
833
+
834
+ actual = df1 + NaT # NaT is datetime, not timedelta
835
+ tm.assert_frame_equal(actual, dfn)
836
+ actual = df1 - NaT
837
+ tm.assert_frame_equal(actual, dfn)
838
+
839
+ # TODO: moved from tests.series.test_operators, needs splitting, cleanup,
840
+ # de-duplication, box-parametrization...
841
+ def test_operators_timedelta64(self):
842
+ # series ops
843
+ v1 = pd.date_range("2012-1-1", periods=3, freq="D")
844
+ v2 = pd.date_range("2012-1-2", periods=3, freq="D")
845
+ rs = Series(v2) - Series(v1)
846
+ xp = Series(1e9 * 3600 * 24, rs.index).astype("int64").astype("timedelta64[ns]")
847
+ tm.assert_series_equal(rs, xp)
848
+ assert rs.dtype == "timedelta64[ns]"
849
+
850
+ df = DataFrame({"A": v1})
851
+ td = Series([timedelta(days=i) for i in range(3)])
852
+ assert td.dtype == "timedelta64[ns]"
853
+
854
+ # series on the rhs
855
+ result = df["A"] - df["A"].shift()
856
+ assert result.dtype == "timedelta64[ns]"
857
+
858
+ result = df["A"] + td
859
+ assert result.dtype == "M8[ns]"
860
+
861
+ # scalar Timestamp on rhs
862
+ maxa = df["A"].max()
863
+ assert isinstance(maxa, Timestamp)
864
+
865
+ resultb = df["A"] - df["A"].max()
866
+ assert resultb.dtype == "timedelta64[ns]"
867
+
868
+ # timestamp on lhs
869
+ result = resultb + df["A"]
870
+ values = [Timestamp("20111230"), Timestamp("20120101"), Timestamp("20120103")]
871
+ expected = Series(values, dtype="M8[ns]", name="A")
872
+ tm.assert_series_equal(result, expected)
873
+
874
+ # datetimes on rhs
875
+ result = df["A"] - datetime(2001, 1, 1)
876
+ expected = Series([timedelta(days=4017 + i) for i in range(3)], name="A")
877
+ tm.assert_series_equal(result, expected)
878
+ assert result.dtype == "m8[ns]"
879
+
880
+ d = datetime(2001, 1, 1, 3, 4)
881
+ resulta = df["A"] - d
882
+ assert resulta.dtype == "m8[ns]"
883
+
884
+ # roundtrip
885
+ resultb = resulta + d
886
+ tm.assert_series_equal(df["A"], resultb)
887
+
888
+ # timedeltas on rhs
889
+ td = timedelta(days=1)
890
+ resulta = df["A"] + td
891
+ resultb = resulta - td
892
+ tm.assert_series_equal(resultb, df["A"])
893
+ assert resultb.dtype == "M8[ns]"
894
+
895
+ # roundtrip
896
+ td = timedelta(minutes=5, seconds=3)
897
+ resulta = df["A"] + td
898
+ resultb = resulta - td
899
+ tm.assert_series_equal(df["A"], resultb)
900
+ assert resultb.dtype == "M8[ns]"
901
+
902
+ # inplace
903
+ value = rs[2] + np.timedelta64(timedelta(minutes=5, seconds=1))
904
+ rs[2] += np.timedelta64(timedelta(minutes=5, seconds=1))
905
+ assert rs[2] == value
906
+
907
+ def test_timedelta64_ops_nat(self):
908
+ # GH 11349
909
+ timedelta_series = Series([NaT, Timedelta("1s")])
910
+ nat_series_dtype_timedelta = Series([NaT, NaT], dtype="timedelta64[ns]")
911
+ single_nat_dtype_timedelta = Series([NaT], dtype="timedelta64[ns]")
912
+
913
+ # subtraction
914
+ tm.assert_series_equal(timedelta_series - NaT, nat_series_dtype_timedelta)
915
+ tm.assert_series_equal(-NaT + timedelta_series, nat_series_dtype_timedelta)
916
+
917
+ tm.assert_series_equal(
918
+ timedelta_series - single_nat_dtype_timedelta, nat_series_dtype_timedelta
919
+ )
920
+ tm.assert_series_equal(
921
+ -single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta
922
+ )
923
+
924
+ # addition
925
+ tm.assert_series_equal(
926
+ nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta
927
+ )
928
+ tm.assert_series_equal(
929
+ NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta
930
+ )
931
+
932
+ tm.assert_series_equal(
933
+ nat_series_dtype_timedelta + single_nat_dtype_timedelta,
934
+ nat_series_dtype_timedelta,
935
+ )
936
+ tm.assert_series_equal(
937
+ single_nat_dtype_timedelta + nat_series_dtype_timedelta,
938
+ nat_series_dtype_timedelta,
939
+ )
940
+
941
+ tm.assert_series_equal(timedelta_series + NaT, nat_series_dtype_timedelta)
942
+ tm.assert_series_equal(NaT + timedelta_series, nat_series_dtype_timedelta)
943
+
944
+ tm.assert_series_equal(
945
+ timedelta_series + single_nat_dtype_timedelta, nat_series_dtype_timedelta
946
+ )
947
+ tm.assert_series_equal(
948
+ single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta
949
+ )
950
+
951
+ tm.assert_series_equal(
952
+ nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta
953
+ )
954
+ tm.assert_series_equal(
955
+ NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta
956
+ )
957
+
958
+ tm.assert_series_equal(
959
+ nat_series_dtype_timedelta + single_nat_dtype_timedelta,
960
+ nat_series_dtype_timedelta,
961
+ )
962
+ tm.assert_series_equal(
963
+ single_nat_dtype_timedelta + nat_series_dtype_timedelta,
964
+ nat_series_dtype_timedelta,
965
+ )
966
+
967
+ # multiplication
968
+ tm.assert_series_equal(
969
+ nat_series_dtype_timedelta * 1.0, nat_series_dtype_timedelta
970
+ )
971
+ tm.assert_series_equal(
972
+ 1.0 * nat_series_dtype_timedelta, nat_series_dtype_timedelta
973
+ )
974
+
975
+ tm.assert_series_equal(timedelta_series * 1, timedelta_series)
976
+ tm.assert_series_equal(1 * timedelta_series, timedelta_series)
977
+
978
+ tm.assert_series_equal(timedelta_series * 1.5, Series([NaT, Timedelta("1.5s")]))
979
+ tm.assert_series_equal(1.5 * timedelta_series, Series([NaT, Timedelta("1.5s")]))
980
+
981
+ tm.assert_series_equal(timedelta_series * np.nan, nat_series_dtype_timedelta)
982
+ tm.assert_series_equal(np.nan * timedelta_series, nat_series_dtype_timedelta)
983
+
984
+ # division
985
+ tm.assert_series_equal(timedelta_series / 2, Series([NaT, Timedelta("0.5s")]))
986
+ tm.assert_series_equal(timedelta_series / 2.0, Series([NaT, Timedelta("0.5s")]))
987
+ tm.assert_series_equal(timedelta_series / np.nan, nat_series_dtype_timedelta)
988
+
989
+ # -------------------------------------------------------------
990
+ # Binary operations td64 arraylike and datetime-like
991
+
992
+ @pytest.mark.parametrize("cls", [Timestamp, datetime, np.datetime64])
993
+ def test_td64arr_add_sub_datetimelike_scalar(
994
+ self, cls, box_with_array, tz_naive_fixture
995
+ ):
996
+ # GH#11925, GH#29558, GH#23215
997
+ tz = tz_naive_fixture
998
+
999
+ dt_scalar = Timestamp("2012-01-01", tz=tz)
1000
+ if cls is datetime:
1001
+ ts = dt_scalar.to_pydatetime()
1002
+ elif cls is np.datetime64:
1003
+ if tz_naive_fixture is not None:
1004
+ pytest.skip(f"{cls} doesn support {tz_naive_fixture}")
1005
+ ts = dt_scalar.to_datetime64()
1006
+ else:
1007
+ ts = dt_scalar
1008
+
1009
+ tdi = timedelta_range("1 day", periods=3)
1010
+ expected = pd.date_range("2012-01-02", periods=3, tz=tz)
1011
+
1012
+ tdarr = tm.box_expected(tdi, box_with_array)
1013
+ expected = tm.box_expected(expected, box_with_array)
1014
+
1015
+ tm.assert_equal(ts + tdarr, expected)
1016
+ tm.assert_equal(tdarr + ts, expected)
1017
+
1018
+ expected2 = pd.date_range("2011-12-31", periods=3, freq="-1D", tz=tz)
1019
+ expected2 = tm.box_expected(expected2, box_with_array)
1020
+
1021
+ tm.assert_equal(ts - tdarr, expected2)
1022
+ tm.assert_equal(ts + (-tdarr), expected2)
1023
+
1024
+ msg = "cannot subtract a datelike"
1025
+ with pytest.raises(TypeError, match=msg):
1026
+ tdarr - ts
1027
+
1028
+ def test_td64arr_add_datetime64_nat(self, box_with_array):
1029
+ # GH#23215
1030
+ other = np.datetime64("NaT")
1031
+
1032
+ tdi = timedelta_range("1 day", periods=3)
1033
+ expected = DatetimeIndex(["NaT", "NaT", "NaT"], dtype="M8[ns]")
1034
+
1035
+ tdser = tm.box_expected(tdi, box_with_array)
1036
+ expected = tm.box_expected(expected, box_with_array)
1037
+
1038
+ tm.assert_equal(tdser + other, expected)
1039
+ tm.assert_equal(other + tdser, expected)
1040
+
1041
+ def test_td64arr_sub_dt64_array(self, box_with_array):
1042
+ dti = pd.date_range("2016-01-01", periods=3)
1043
+ tdi = TimedeltaIndex(["-1 Day"] * 3)
1044
+ dtarr = dti.values
1045
+ expected = DatetimeIndex(dtarr) - tdi
1046
+
1047
+ tdi = tm.box_expected(tdi, box_with_array)
1048
+ expected = tm.box_expected(expected, box_with_array)
1049
+
1050
+ msg = "cannot subtract a datelike from"
1051
+ with pytest.raises(TypeError, match=msg):
1052
+ tdi - dtarr
1053
+
1054
+ # TimedeltaIndex.__rsub__
1055
+ result = dtarr - tdi
1056
+ tm.assert_equal(result, expected)
1057
+
1058
+ def test_td64arr_add_dt64_array(self, box_with_array):
1059
+ dti = pd.date_range("2016-01-01", periods=3)
1060
+ tdi = TimedeltaIndex(["-1 Day"] * 3)
1061
+ dtarr = dti.values
1062
+ expected = DatetimeIndex(dtarr) + tdi
1063
+
1064
+ tdi = tm.box_expected(tdi, box_with_array)
1065
+ expected = tm.box_expected(expected, box_with_array)
1066
+
1067
+ result = tdi + dtarr
1068
+ tm.assert_equal(result, expected)
1069
+ result = dtarr + tdi
1070
+ tm.assert_equal(result, expected)
1071
+
1072
+ # ------------------------------------------------------------------
1073
+ # Invalid __add__/__sub__ operations
1074
+
1075
+ @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "h"])
1076
+ @pytest.mark.parametrize("tdi_freq", [None, "h"])
1077
+ def test_td64arr_sub_periodlike(
1078
+ self, box_with_array, box_with_array2, tdi_freq, pi_freq
1079
+ ):
1080
+ # GH#20049 subtracting PeriodIndex should raise TypeError
1081
+ tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq)
1082
+ dti = Timestamp("2018-03-07 17:16:40") + tdi
1083
+ pi = dti.to_period(pi_freq)
1084
+ per = pi[0]
1085
+
1086
+ tdi = tm.box_expected(tdi, box_with_array)
1087
+ pi = tm.box_expected(pi, box_with_array2)
1088
+ msg = "cannot subtract|unsupported operand type"
1089
+ with pytest.raises(TypeError, match=msg):
1090
+ tdi - pi
1091
+
1092
+ # GH#13078 subtraction of Period scalar not supported
1093
+ with pytest.raises(TypeError, match=msg):
1094
+ tdi - per
1095
+
1096
+ @pytest.mark.parametrize(
1097
+ "other",
1098
+ [
1099
+ # GH#12624 for str case
1100
+ "a",
1101
+ # GH#19123
1102
+ 1,
1103
+ 1.5,
1104
+ np.array(2),
1105
+ ],
1106
+ )
1107
+ def test_td64arr_addsub_numeric_scalar_invalid(self, box_with_array, other):
1108
+ # vector-like others are tested in test_td64arr_add_sub_numeric_arr_invalid
1109
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
1110
+ tdarr = tm.box_expected(tdser, box_with_array)
1111
+
1112
+ assert_invalid_addsub_type(tdarr, other)
1113
+
1114
+ @pytest.mark.parametrize(
1115
+ "vec",
1116
+ [
1117
+ np.array([1, 2, 3]),
1118
+ Index([1, 2, 3]),
1119
+ Series([1, 2, 3]),
1120
+ DataFrame([[1, 2, 3]]),
1121
+ ],
1122
+ ids=lambda x: type(x).__name__,
1123
+ )
1124
+ def test_td64arr_addsub_numeric_arr_invalid(
1125
+ self, box_with_array, vec, any_real_numpy_dtype
1126
+ ):
1127
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
1128
+ tdarr = tm.box_expected(tdser, box_with_array)
1129
+
1130
+ vector = vec.astype(any_real_numpy_dtype)
1131
+ assert_invalid_addsub_type(tdarr, vector)
1132
+
1133
+ def test_td64arr_add_sub_int(self, box_with_array, one):
1134
+ # Variants of `one` for #19012, deprecated GH#22535
1135
+ rng = timedelta_range("1 days 09:00:00", freq="h", periods=10)
1136
+ tdarr = tm.box_expected(rng, box_with_array)
1137
+
1138
+ msg = "Addition/subtraction of integers"
1139
+ assert_invalid_addsub_type(tdarr, one, msg)
1140
+
1141
+ # TODO: get inplace ops into assert_invalid_addsub_type
1142
+ with pytest.raises(TypeError, match=msg):
1143
+ tdarr += one
1144
+ with pytest.raises(TypeError, match=msg):
1145
+ tdarr -= one
1146
+
1147
+ def test_td64arr_add_sub_integer_array(self, box_with_array):
1148
+ # GH#19959, deprecated GH#22535
1149
+ # GH#22696 for DataFrame case, check that we don't dispatch to numpy
1150
+ # implementation, which treats int64 as m8[ns]
1151
+ box = box_with_array
1152
+ xbox = np.ndarray if box is pd.array else box
1153
+
1154
+ rng = timedelta_range("1 days 09:00:00", freq="h", periods=3)
1155
+ tdarr = tm.box_expected(rng, box)
1156
+ other = tm.box_expected([4, 3, 2], xbox)
1157
+
1158
+ msg = "Addition/subtraction of integers and integer-arrays"
1159
+ assert_invalid_addsub_type(tdarr, other, msg)
1160
+
1161
+ def test_td64arr_addsub_integer_array_no_freq(self, box_with_array):
1162
+ # GH#19959
1163
+ box = box_with_array
1164
+ xbox = np.ndarray if box is pd.array else box
1165
+
1166
+ tdi = TimedeltaIndex(["1 Day", "NaT", "3 Hours"])
1167
+ tdarr = tm.box_expected(tdi, box)
1168
+ other = tm.box_expected([14, -1, 16], xbox)
1169
+
1170
+ msg = "Addition/subtraction of integers"
1171
+ assert_invalid_addsub_type(tdarr, other, msg)
1172
+
1173
+ # ------------------------------------------------------------------
1174
+ # Operations with timedelta-like others
1175
+
1176
+ def test_td64arr_add_sub_td64_array(self, box_with_array):
1177
+ box = box_with_array
1178
+ dti = pd.date_range("2016-01-01", periods=3)
1179
+ tdi = dti - dti.shift(1)
1180
+ tdarr = tdi.values
1181
+
1182
+ expected = 2 * tdi
1183
+ tdi = tm.box_expected(tdi, box)
1184
+ expected = tm.box_expected(expected, box)
1185
+
1186
+ result = tdi + tdarr
1187
+ tm.assert_equal(result, expected)
1188
+ result = tdarr + tdi
1189
+ tm.assert_equal(result, expected)
1190
+
1191
+ expected_sub = 0 * tdi
1192
+ result = tdi - tdarr
1193
+ tm.assert_equal(result, expected_sub)
1194
+ result = tdarr - tdi
1195
+ tm.assert_equal(result, expected_sub)
1196
+
1197
+ def test_td64arr_add_sub_tdi(self, box_with_array, names):
1198
+ # GH#17250 make sure result dtype is correct
1199
+ # GH#19043 make sure names are propagated correctly
1200
+ box = box_with_array
1201
+ exname = get_expected_name(box, names)
1202
+
1203
+ tdi = TimedeltaIndex(["0 days", "1 day"], name=names[1])
1204
+ tdi = np.array(tdi) if box in [tm.to_array, pd.array] else tdi
1205
+ ser = Series([Timedelta(hours=3), Timedelta(hours=4)], name=names[0])
1206
+ expected = Series([Timedelta(hours=3), Timedelta(days=1, hours=4)], name=exname)
1207
+
1208
+ ser = tm.box_expected(ser, box)
1209
+ expected = tm.box_expected(expected, box)
1210
+
1211
+ result = tdi + ser
1212
+ tm.assert_equal(result, expected)
1213
+ assert_dtype(result, "timedelta64[ns]")
1214
+
1215
+ result = ser + tdi
1216
+ tm.assert_equal(result, expected)
1217
+ assert_dtype(result, "timedelta64[ns]")
1218
+
1219
+ expected = Series(
1220
+ [Timedelta(hours=-3), Timedelta(days=1, hours=-4)], name=exname
1221
+ )
1222
+ expected = tm.box_expected(expected, box)
1223
+
1224
+ result = tdi - ser
1225
+ tm.assert_equal(result, expected)
1226
+ assert_dtype(result, "timedelta64[ns]")
1227
+
1228
+ result = ser - tdi
1229
+ tm.assert_equal(result, -expected)
1230
+ assert_dtype(result, "timedelta64[ns]")
1231
+
1232
+ @pytest.mark.parametrize("tdnat", [np.timedelta64("NaT"), NaT])
1233
+ def test_td64arr_add_sub_td64_nat(self, box_with_array, tdnat):
1234
+ # GH#18808, GH#23320 special handling for timedelta64("NaT")
1235
+ box = box_with_array
1236
+ tdi = TimedeltaIndex([NaT, Timedelta("1s")])
1237
+ expected = TimedeltaIndex(["NaT"] * 2)
1238
+
1239
+ obj = tm.box_expected(tdi, box)
1240
+ expected = tm.box_expected(expected, box)
1241
+
1242
+ result = obj + tdnat
1243
+ tm.assert_equal(result, expected)
1244
+ result = tdnat + obj
1245
+ tm.assert_equal(result, expected)
1246
+ result = obj - tdnat
1247
+ tm.assert_equal(result, expected)
1248
+ result = tdnat - obj
1249
+ tm.assert_equal(result, expected)
1250
+
1251
+ def test_td64arr_add_timedeltalike(self, two_hours, box_with_array):
1252
+ # only test adding/sub offsets as + is now numeric
1253
+ # GH#10699 for Tick cases
1254
+ box = box_with_array
1255
+ rng = timedelta_range("1 days", "10 days")
1256
+ expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D")
1257
+ rng = tm.box_expected(rng, box)
1258
+ expected = tm.box_expected(expected, box)
1259
+
1260
+ result = rng + two_hours
1261
+ tm.assert_equal(result, expected)
1262
+
1263
+ result = two_hours + rng
1264
+ tm.assert_equal(result, expected)
1265
+
1266
+ def test_td64arr_sub_timedeltalike(self, two_hours, box_with_array):
1267
+ # only test adding/sub offsets as - is now numeric
1268
+ # GH#10699 for Tick cases
1269
+ box = box_with_array
1270
+ rng = timedelta_range("1 days", "10 days")
1271
+ expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00")
1272
+
1273
+ rng = tm.box_expected(rng, box)
1274
+ expected = tm.box_expected(expected, box)
1275
+
1276
+ result = rng - two_hours
1277
+ tm.assert_equal(result, expected)
1278
+
1279
+ result = two_hours - rng
1280
+ tm.assert_equal(result, -expected)
1281
+
1282
+ # ------------------------------------------------------------------
1283
+ # __add__/__sub__ with DateOffsets and arrays of DateOffsets
1284
+
1285
+ def test_td64arr_add_sub_offset_index(self, names, box_with_array):
1286
+ # GH#18849, GH#19744
1287
+ box = box_with_array
1288
+ exname = get_expected_name(box, names)
1289
+
1290
+ tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0])
1291
+ other = Index([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1])
1292
+ other = np.array(other) if box in [tm.to_array, pd.array] else other
1293
+
1294
+ expected = TimedeltaIndex(
1295
+ [tdi[n] + other[n] for n in range(len(tdi))], freq="infer", name=exname
1296
+ )
1297
+ expected_sub = TimedeltaIndex(
1298
+ [tdi[n] - other[n] for n in range(len(tdi))], freq="infer", name=exname
1299
+ )
1300
+
1301
+ tdi = tm.box_expected(tdi, box)
1302
+ expected = tm.box_expected(expected, box).astype(object, copy=False)
1303
+ expected_sub = tm.box_expected(expected_sub, box).astype(object, copy=False)
1304
+
1305
+ with tm.assert_produces_warning(PerformanceWarning):
1306
+ res = tdi + other
1307
+ tm.assert_equal(res, expected)
1308
+
1309
+ with tm.assert_produces_warning(PerformanceWarning):
1310
+ res2 = other + tdi
1311
+ tm.assert_equal(res2, expected)
1312
+
1313
+ with tm.assert_produces_warning(PerformanceWarning):
1314
+ res_sub = tdi - other
1315
+ tm.assert_equal(res_sub, expected_sub)
1316
+
1317
+ def test_td64arr_add_sub_offset_array(self, box_with_array):
1318
+ # GH#18849, GH#18824
1319
+ box = box_with_array
1320
+ tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"])
1321
+ other = np.array([offsets.Hour(n=1), offsets.Minute(n=-2)])
1322
+
1323
+ expected = TimedeltaIndex(
1324
+ [tdi[n] + other[n] for n in range(len(tdi))], freq="infer"
1325
+ )
1326
+ expected_sub = TimedeltaIndex(
1327
+ [tdi[n] - other[n] for n in range(len(tdi))], freq="infer"
1328
+ )
1329
+
1330
+ tdi = tm.box_expected(tdi, box)
1331
+ expected = tm.box_expected(expected, box).astype(object)
1332
+
1333
+ with tm.assert_produces_warning(PerformanceWarning):
1334
+ res = tdi + other
1335
+ tm.assert_equal(res, expected)
1336
+
1337
+ with tm.assert_produces_warning(PerformanceWarning):
1338
+ res2 = other + tdi
1339
+ tm.assert_equal(res2, expected)
1340
+
1341
+ expected_sub = tm.box_expected(expected_sub, box_with_array).astype(object)
1342
+ with tm.assert_produces_warning(PerformanceWarning):
1343
+ res_sub = tdi - other
1344
+ tm.assert_equal(res_sub, expected_sub)
1345
+
1346
+ def test_td64arr_with_offset_series(self, names, box_with_array):
1347
+ # GH#18849
1348
+ box = box_with_array
1349
+ box2 = Series if box in [Index, tm.to_array, pd.array] else box
1350
+ exname = get_expected_name(box, names)
1351
+
1352
+ tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0])
1353
+ other = Series([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1])
1354
+
1355
+ expected_add = Series(
1356
+ [tdi[n] + other[n] for n in range(len(tdi))], name=exname, dtype=object
1357
+ )
1358
+ obj = tm.box_expected(tdi, box)
1359
+ expected_add = tm.box_expected(expected_add, box2).astype(object)
1360
+
1361
+ with tm.assert_produces_warning(PerformanceWarning):
1362
+ res = obj + other
1363
+ tm.assert_equal(res, expected_add)
1364
+
1365
+ with tm.assert_produces_warning(PerformanceWarning):
1366
+ res2 = other + obj
1367
+ tm.assert_equal(res2, expected_add)
1368
+
1369
+ expected_sub = Series(
1370
+ [tdi[n] - other[n] for n in range(len(tdi))], name=exname, dtype=object
1371
+ )
1372
+ expected_sub = tm.box_expected(expected_sub, box2).astype(object)
1373
+
1374
+ with tm.assert_produces_warning(PerformanceWarning):
1375
+ res3 = obj - other
1376
+ tm.assert_equal(res3, expected_sub)
1377
+
1378
+ @pytest.mark.parametrize("obox", [np.array, Index, Series])
1379
+ def test_td64arr_addsub_anchored_offset_arraylike(self, obox, box_with_array):
1380
+ # GH#18824
1381
+ tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"])
1382
+ tdi = tm.box_expected(tdi, box_with_array)
1383
+
1384
+ anchored = obox([offsets.MonthEnd(), offsets.Day(n=2)])
1385
+
1386
+ # addition/subtraction ops with anchored offsets should issue
1387
+ # a PerformanceWarning and _then_ raise a TypeError.
1388
+ msg = "has incorrect type|cannot add the type MonthEnd"
1389
+ with pytest.raises(TypeError, match=msg):
1390
+ with tm.assert_produces_warning(PerformanceWarning):
1391
+ tdi + anchored
1392
+ with pytest.raises(TypeError, match=msg):
1393
+ with tm.assert_produces_warning(PerformanceWarning):
1394
+ anchored + tdi
1395
+ with pytest.raises(TypeError, match=msg):
1396
+ with tm.assert_produces_warning(PerformanceWarning):
1397
+ tdi - anchored
1398
+ with pytest.raises(TypeError, match=msg):
1399
+ with tm.assert_produces_warning(PerformanceWarning):
1400
+ anchored - tdi
1401
+
1402
+ # ------------------------------------------------------------------
1403
+ # Unsorted
1404
+
1405
+ def test_td64arr_add_sub_object_array(self, box_with_array):
1406
+ box = box_with_array
1407
+ xbox = np.ndarray if box is pd.array else box
1408
+
1409
+ tdi = timedelta_range("1 day", periods=3, freq="D")
1410
+ tdarr = tm.box_expected(tdi, box)
1411
+
1412
+ other = np.array([Timedelta(days=1), offsets.Day(2), Timestamp("2000-01-04")])
1413
+
1414
+ with tm.assert_produces_warning(PerformanceWarning):
1415
+ result = tdarr + other
1416
+
1417
+ expected = Index(
1418
+ [Timedelta(days=2), Timedelta(days=4), Timestamp("2000-01-07")]
1419
+ )
1420
+ expected = tm.box_expected(expected, xbox).astype(object)
1421
+ tm.assert_equal(result, expected)
1422
+
1423
+ msg = "unsupported operand type|cannot subtract a datelike"
1424
+ with pytest.raises(TypeError, match=msg):
1425
+ with tm.assert_produces_warning(PerformanceWarning):
1426
+ tdarr - other
1427
+
1428
+ with tm.assert_produces_warning(PerformanceWarning):
1429
+ result = other - tdarr
1430
+
1431
+ expected = Index([Timedelta(0), Timedelta(0), Timestamp("2000-01-01")])
1432
+ expected = tm.box_expected(expected, xbox).astype(object)
1433
+ tm.assert_equal(result, expected)
1434
+
1435
+
1436
+ class TestTimedeltaArraylikeMulDivOps:
1437
+ # Tests for timedelta64[ns]
1438
+ # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__
1439
+
1440
+ # ------------------------------------------------------------------
1441
+ # Multiplication
1442
+ # organized with scalar others first, then array-like
1443
+
1444
+ def test_td64arr_mul_int(self, box_with_array):
1445
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
1446
+ idx = tm.box_expected(idx, box_with_array)
1447
+
1448
+ result = idx * 1
1449
+ tm.assert_equal(result, idx)
1450
+
1451
+ result = 1 * idx
1452
+ tm.assert_equal(result, idx)
1453
+
1454
+ def test_td64arr_mul_tdlike_scalar_raises(self, two_hours, box_with_array):
1455
+ rng = timedelta_range("1 days", "10 days", name="foo")
1456
+ rng = tm.box_expected(rng, box_with_array)
1457
+ msg = "argument must be an integer|cannot use operands with types dtype"
1458
+ with pytest.raises(TypeError, match=msg):
1459
+ rng * two_hours
1460
+
1461
+ def test_tdi_mul_int_array_zerodim(self, box_with_array):
1462
+ rng5 = np.arange(5, dtype="int64")
1463
+ idx = TimedeltaIndex(rng5)
1464
+ expected = TimedeltaIndex(rng5 * 5)
1465
+
1466
+ idx = tm.box_expected(idx, box_with_array)
1467
+ expected = tm.box_expected(expected, box_with_array)
1468
+
1469
+ result = idx * np.array(5, dtype="int64")
1470
+ tm.assert_equal(result, expected)
1471
+
1472
+ def test_tdi_mul_int_array(self, box_with_array):
1473
+ rng5 = np.arange(5, dtype="int64")
1474
+ idx = TimedeltaIndex(rng5)
1475
+ expected = TimedeltaIndex(rng5**2)
1476
+
1477
+ idx = tm.box_expected(idx, box_with_array)
1478
+ expected = tm.box_expected(expected, box_with_array)
1479
+
1480
+ result = idx * rng5
1481
+ tm.assert_equal(result, expected)
1482
+
1483
+ def test_tdi_mul_int_series(self, box_with_array):
1484
+ box = box_with_array
1485
+ xbox = Series if box in [Index, tm.to_array, pd.array] else box
1486
+
1487
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
1488
+ expected = TimedeltaIndex(np.arange(5, dtype="int64") ** 2)
1489
+
1490
+ idx = tm.box_expected(idx, box)
1491
+ expected = tm.box_expected(expected, xbox)
1492
+
1493
+ result = idx * Series(np.arange(5, dtype="int64"))
1494
+ tm.assert_equal(result, expected)
1495
+
1496
+ def test_tdi_mul_float_series(self, box_with_array):
1497
+ box = box_with_array
1498
+ xbox = Series if box in [Index, tm.to_array, pd.array] else box
1499
+
1500
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
1501
+ idx = tm.box_expected(idx, box)
1502
+
1503
+ rng5f = np.arange(5, dtype="float64")
1504
+ expected = TimedeltaIndex(rng5f * (rng5f + 1.0))
1505
+ expected = tm.box_expected(expected, xbox)
1506
+
1507
+ result = idx * Series(rng5f + 1.0)
1508
+ tm.assert_equal(result, expected)
1509
+
1510
+ # TODO: Put Series/DataFrame in others?
1511
+ @pytest.mark.parametrize(
1512
+ "other",
1513
+ [
1514
+ np.arange(1, 11),
1515
+ Index(np.arange(1, 11), np.int64),
1516
+ Index(range(1, 11), np.uint64),
1517
+ Index(range(1, 11), np.float64),
1518
+ pd.RangeIndex(1, 11),
1519
+ ],
1520
+ ids=lambda x: type(x).__name__,
1521
+ )
1522
+ def test_tdi_rmul_arraylike(self, other, box_with_array):
1523
+ box = box_with_array
1524
+
1525
+ tdi = TimedeltaIndex(["1 Day"] * 10)
1526
+ expected = timedelta_range("1 days", "10 days")._with_freq(None)
1527
+
1528
+ tdi = tm.box_expected(tdi, box)
1529
+ xbox = get_upcast_box(tdi, other)
1530
+
1531
+ expected = tm.box_expected(expected, xbox)
1532
+
1533
+ result = other * tdi
1534
+ tm.assert_equal(result, expected)
1535
+ commute = tdi * other
1536
+ tm.assert_equal(commute, expected)
1537
+
1538
+ # ------------------------------------------------------------------
1539
+ # __div__, __rdiv__
1540
+
1541
+ def test_td64arr_div_nat_invalid(self, box_with_array):
1542
+ # don't allow division by NaT (maybe could in the future)
1543
+ rng = timedelta_range("1 days", "10 days", name="foo")
1544
+ rng = tm.box_expected(rng, box_with_array)
1545
+
1546
+ with pytest.raises(TypeError, match="unsupported operand type"):
1547
+ rng / NaT
1548
+ with pytest.raises(TypeError, match="Cannot divide NaTType by"):
1549
+ NaT / rng
1550
+
1551
+ dt64nat = np.datetime64("NaT", "ns")
1552
+ msg = "|".join(
1553
+ [
1554
+ # 'divide' on npdev as of 2021-12-18
1555
+ "ufunc '(true_divide|divide)' cannot use operands",
1556
+ "cannot perform __r?truediv__",
1557
+ "Cannot divide datetime64 by TimedeltaArray",
1558
+ ]
1559
+ )
1560
+ with pytest.raises(TypeError, match=msg):
1561
+ rng / dt64nat
1562
+ with pytest.raises(TypeError, match=msg):
1563
+ dt64nat / rng
1564
+
1565
+ def test_td64arr_div_td64nat(self, box_with_array):
1566
+ # GH#23829
1567
+ box = box_with_array
1568
+ xbox = np.ndarray if box is pd.array else box
1569
+
1570
+ rng = timedelta_range("1 days", "10 days")
1571
+ rng = tm.box_expected(rng, box)
1572
+
1573
+ other = np.timedelta64("NaT")
1574
+
1575
+ expected = np.array([np.nan] * 10)
1576
+ expected = tm.box_expected(expected, xbox)
1577
+
1578
+ result = rng / other
1579
+ tm.assert_equal(result, expected)
1580
+
1581
+ result = other / rng
1582
+ tm.assert_equal(result, expected)
1583
+
1584
+ def test_td64arr_div_int(self, box_with_array):
1585
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
1586
+ idx = tm.box_expected(idx, box_with_array)
1587
+
1588
+ result = idx / 1
1589
+ tm.assert_equal(result, idx)
1590
+
1591
+ with pytest.raises(TypeError, match="Cannot divide"):
1592
+ # GH#23829
1593
+ 1 / idx
1594
+
1595
+ def test_td64arr_div_tdlike_scalar(self, two_hours, box_with_array):
1596
+ # GH#20088, GH#22163 ensure DataFrame returns correct dtype
1597
+ box = box_with_array
1598
+ xbox = np.ndarray if box is pd.array else box
1599
+
1600
+ rng = timedelta_range("1 days", "10 days", name="foo")
1601
+ expected = Index((np.arange(10) + 1) * 12, dtype=np.float64, name="foo")
1602
+
1603
+ rng = tm.box_expected(rng, box)
1604
+ expected = tm.box_expected(expected, xbox)
1605
+
1606
+ result = rng / two_hours
1607
+ tm.assert_equal(result, expected)
1608
+
1609
+ result = two_hours / rng
1610
+ expected = 1 / expected
1611
+ tm.assert_equal(result, expected)
1612
+
1613
+ @pytest.mark.parametrize("m", [1, 3, 10])
1614
+ @pytest.mark.parametrize("unit", ["D", "h", "m", "s", "ms", "us", "ns"])
1615
+ def test_td64arr_div_td64_scalar(self, m, unit, box_with_array):
1616
+ box = box_with_array
1617
+ xbox = np.ndarray if box is pd.array else box
1618
+
1619
+ ser = Series([Timedelta(days=59)] * 3)
1620
+ ser[2] = np.nan
1621
+ flat = ser
1622
+ ser = tm.box_expected(ser, box)
1623
+
1624
+ # op
1625
+ expected = Series([x / np.timedelta64(m, unit) for x in flat])
1626
+ expected = tm.box_expected(expected, xbox)
1627
+ result = ser / np.timedelta64(m, unit)
1628
+ tm.assert_equal(result, expected)
1629
+
1630
+ # reverse op
1631
+ expected = Series([Timedelta(np.timedelta64(m, unit)) / x for x in flat])
1632
+ expected = tm.box_expected(expected, xbox)
1633
+ result = np.timedelta64(m, unit) / ser
1634
+ tm.assert_equal(result, expected)
1635
+
1636
+ def test_td64arr_div_tdlike_scalar_with_nat(self, two_hours, box_with_array):
1637
+ box = box_with_array
1638
+ xbox = np.ndarray if box is pd.array else box
1639
+
1640
+ rng = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
1641
+ expected = Index([12, np.nan, 24], dtype=np.float64, name="foo")
1642
+
1643
+ rng = tm.box_expected(rng, box)
1644
+ expected = tm.box_expected(expected, xbox)
1645
+
1646
+ result = rng / two_hours
1647
+ tm.assert_equal(result, expected)
1648
+
1649
+ result = two_hours / rng
1650
+ expected = 1 / expected
1651
+ tm.assert_equal(result, expected)
1652
+
1653
+ def test_td64arr_div_td64_ndarray(self, box_with_array):
1654
+ # GH#22631
1655
+ box = box_with_array
1656
+ xbox = np.ndarray if box is pd.array else box
1657
+
1658
+ rng = TimedeltaIndex(["1 days", NaT, "2 days"])
1659
+ expected = Index([12, np.nan, 24], dtype=np.float64)
1660
+
1661
+ rng = tm.box_expected(rng, box)
1662
+ expected = tm.box_expected(expected, xbox)
1663
+
1664
+ other = np.array([2, 4, 2], dtype="m8[h]")
1665
+ result = rng / other
1666
+ tm.assert_equal(result, expected)
1667
+
1668
+ result = rng / tm.box_expected(other, box)
1669
+ tm.assert_equal(result, expected)
1670
+
1671
+ result = rng / other.astype(object)
1672
+ tm.assert_equal(result, expected.astype(object))
1673
+
1674
+ result = rng / list(other)
1675
+ tm.assert_equal(result, expected)
1676
+
1677
+ # reversed op
1678
+ expected = 1 / expected
1679
+ result = other / rng
1680
+ tm.assert_equal(result, expected)
1681
+
1682
+ result = tm.box_expected(other, box) / rng
1683
+ tm.assert_equal(result, expected)
1684
+
1685
+ result = other.astype(object) / rng
1686
+ tm.assert_equal(result, expected)
1687
+
1688
+ result = list(other) / rng
1689
+ tm.assert_equal(result, expected)
1690
+
1691
+ def test_tdarr_div_length_mismatch(self, box_with_array):
1692
+ rng = TimedeltaIndex(["1 days", NaT, "2 days"])
1693
+ mismatched = [1, 2, 3, 4]
1694
+
1695
+ rng = tm.box_expected(rng, box_with_array)
1696
+ msg = "Cannot divide vectors|Unable to coerce to Series"
1697
+ for obj in [mismatched, mismatched[:2]]:
1698
+ # one shorter, one longer
1699
+ for other in [obj, np.array(obj), Index(obj)]:
1700
+ with pytest.raises(ValueError, match=msg):
1701
+ rng / other
1702
+ with pytest.raises(ValueError, match=msg):
1703
+ other / rng
1704
+
1705
+ def test_td64_div_object_mixed_result(self, box_with_array):
1706
+ # Case where we having a NaT in the result inseat of timedelta64("NaT")
1707
+ # is misleading
1708
+ orig = timedelta_range("1 Day", periods=3).insert(1, NaT)
1709
+ tdi = tm.box_expected(orig, box_with_array, transpose=False)
1710
+
1711
+ other = np.array([orig[0], 1.5, 2.0, orig[2]], dtype=object)
1712
+ other = tm.box_expected(other, box_with_array, transpose=False)
1713
+
1714
+ res = tdi / other
1715
+
1716
+ expected = Index([1.0, np.timedelta64("NaT", "ns"), orig[0], 1.5], dtype=object)
1717
+ expected = tm.box_expected(expected, box_with_array, transpose=False)
1718
+ if isinstance(expected, NumpyExtensionArray):
1719
+ expected = expected.to_numpy()
1720
+ tm.assert_equal(res, expected)
1721
+ if box_with_array is DataFrame:
1722
+ # We have a np.timedelta64(NaT), not pd.NaT
1723
+ assert isinstance(res.iloc[1, 0], np.timedelta64)
1724
+
1725
+ res = tdi // other
1726
+
1727
+ expected = Index([1, np.timedelta64("NaT", "ns"), orig[0], 1], dtype=object)
1728
+ expected = tm.box_expected(expected, box_with_array, transpose=False)
1729
+ if isinstance(expected, NumpyExtensionArray):
1730
+ expected = expected.to_numpy()
1731
+ tm.assert_equal(res, expected)
1732
+ if box_with_array is DataFrame:
1733
+ # We have a np.timedelta64(NaT), not pd.NaT
1734
+ assert isinstance(res.iloc[1, 0], np.timedelta64)
1735
+
1736
+ # ------------------------------------------------------------------
1737
+ # __floordiv__, __rfloordiv__
1738
+
1739
+ def test_td64arr_floordiv_td64arr_with_nat(
1740
+ self, box_with_array, using_array_manager
1741
+ ):
1742
+ # GH#35529
1743
+ box = box_with_array
1744
+ xbox = np.ndarray if box is pd.array else box
1745
+
1746
+ left = Series([1000, 222330, 30], dtype="timedelta64[ns]")
1747
+ right = Series([1000, 222330, None], dtype="timedelta64[ns]")
1748
+
1749
+ left = tm.box_expected(left, box)
1750
+ right = tm.box_expected(right, box)
1751
+
1752
+ expected = np.array([1.0, 1.0, np.nan], dtype=np.float64)
1753
+ expected = tm.box_expected(expected, xbox)
1754
+ if box is DataFrame and using_array_manager:
1755
+ # INFO(ArrayManager) floordiv returns integer, and ArrayManager
1756
+ # performs ops column-wise and thus preserves int64 dtype for
1757
+ # columns without missing values
1758
+ expected[[0, 1]] = expected[[0, 1]].astype("int64")
1759
+
1760
+ with tm.maybe_produces_warning(
1761
+ RuntimeWarning, box is pd.array, check_stacklevel=False
1762
+ ):
1763
+ result = left // right
1764
+
1765
+ tm.assert_equal(result, expected)
1766
+
1767
+ # case that goes through __rfloordiv__ with arraylike
1768
+ with tm.maybe_produces_warning(
1769
+ RuntimeWarning, box is pd.array, check_stacklevel=False
1770
+ ):
1771
+ result = np.asarray(left) // right
1772
+ tm.assert_equal(result, expected)
1773
+
1774
+ @pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning")
1775
+ def test_td64arr_floordiv_tdscalar(self, box_with_array, scalar_td):
1776
+ # GH#18831, GH#19125
1777
+ box = box_with_array
1778
+ xbox = np.ndarray if box is pd.array else box
1779
+ td = Timedelta("5m3s") # i.e. (scalar_td - 1sec) / 2
1780
+
1781
+ td1 = Series([td, td, NaT], dtype="m8[ns]")
1782
+ td1 = tm.box_expected(td1, box, transpose=False)
1783
+
1784
+ expected = Series([0, 0, np.nan])
1785
+ expected = tm.box_expected(expected, xbox, transpose=False)
1786
+
1787
+ result = td1 // scalar_td
1788
+ tm.assert_equal(result, expected)
1789
+
1790
+ # Reversed op
1791
+ expected = Series([2, 2, np.nan])
1792
+ expected = tm.box_expected(expected, xbox, transpose=False)
1793
+
1794
+ result = scalar_td // td1
1795
+ tm.assert_equal(result, expected)
1796
+
1797
+ # same thing buts let's be explicit about calling __rfloordiv__
1798
+ result = td1.__rfloordiv__(scalar_td)
1799
+ tm.assert_equal(result, expected)
1800
+
1801
+ def test_td64arr_floordiv_int(self, box_with_array):
1802
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
1803
+ idx = tm.box_expected(idx, box_with_array)
1804
+ result = idx // 1
1805
+ tm.assert_equal(result, idx)
1806
+
1807
+ pattern = "floor_divide cannot use operands|Cannot divide int by Timedelta*"
1808
+ with pytest.raises(TypeError, match=pattern):
1809
+ 1 // idx
1810
+
1811
+ # ------------------------------------------------------------------
1812
+ # mod, divmod
1813
+ # TODO: operations with timedelta-like arrays, numeric arrays,
1814
+ # reversed ops
1815
+
1816
+ def test_td64arr_mod_tdscalar(self, box_with_array, three_days):
1817
+ tdi = timedelta_range("1 Day", "9 days")
1818
+ tdarr = tm.box_expected(tdi, box_with_array)
1819
+
1820
+ expected = TimedeltaIndex(["1 Day", "2 Days", "0 Days"] * 3)
1821
+ expected = tm.box_expected(expected, box_with_array)
1822
+
1823
+ result = tdarr % three_days
1824
+ tm.assert_equal(result, expected)
1825
+
1826
+ warn = None
1827
+ if box_with_array is DataFrame and isinstance(three_days, pd.DateOffset):
1828
+ warn = PerformanceWarning
1829
+ # TODO: making expected be object here a result of DataFrame.__divmod__
1830
+ # being defined in a naive way that does not dispatch to the underlying
1831
+ # array's __divmod__
1832
+ expected = expected.astype(object)
1833
+
1834
+ with tm.assert_produces_warning(warn):
1835
+ result = divmod(tdarr, three_days)
1836
+
1837
+ tm.assert_equal(result[1], expected)
1838
+ tm.assert_equal(result[0], tdarr // three_days)
1839
+
1840
+ def test_td64arr_mod_int(self, box_with_array):
1841
+ tdi = timedelta_range("1 ns", "10 ns", periods=10)
1842
+ tdarr = tm.box_expected(tdi, box_with_array)
1843
+
1844
+ expected = TimedeltaIndex(["1 ns", "0 ns"] * 5)
1845
+ expected = tm.box_expected(expected, box_with_array)
1846
+
1847
+ result = tdarr % 2
1848
+ tm.assert_equal(result, expected)
1849
+
1850
+ msg = "Cannot divide int by"
1851
+ with pytest.raises(TypeError, match=msg):
1852
+ 2 % tdarr
1853
+
1854
+ result = divmod(tdarr, 2)
1855
+ tm.assert_equal(result[1], expected)
1856
+ tm.assert_equal(result[0], tdarr // 2)
1857
+
1858
+ def test_td64arr_rmod_tdscalar(self, box_with_array, three_days):
1859
+ tdi = timedelta_range("1 Day", "9 days")
1860
+ tdarr = tm.box_expected(tdi, box_with_array)
1861
+
1862
+ expected = ["0 Days", "1 Day", "0 Days"] + ["3 Days"] * 6
1863
+ expected = TimedeltaIndex(expected)
1864
+ expected = tm.box_expected(expected, box_with_array)
1865
+
1866
+ result = three_days % tdarr
1867
+ tm.assert_equal(result, expected)
1868
+
1869
+ result = divmod(three_days, tdarr)
1870
+ tm.assert_equal(result[1], expected)
1871
+ tm.assert_equal(result[0], three_days // tdarr)
1872
+
1873
+ # ------------------------------------------------------------------
1874
+ # Operations with invalid others
1875
+
1876
+ def test_td64arr_mul_tdscalar_invalid(self, box_with_array, scalar_td):
1877
+ td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
1878
+ td1.iloc[2] = np.nan
1879
+
1880
+ td1 = tm.box_expected(td1, box_with_array)
1881
+
1882
+ # check that we are getting a TypeError
1883
+ # with 'operate' (from core/ops.py) for the ops that are not
1884
+ # defined
1885
+ pattern = "operate|unsupported|cannot|not supported"
1886
+ with pytest.raises(TypeError, match=pattern):
1887
+ td1 * scalar_td
1888
+ with pytest.raises(TypeError, match=pattern):
1889
+ scalar_td * td1
1890
+
1891
+ def test_td64arr_mul_too_short_raises(self, box_with_array):
1892
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
1893
+ idx = tm.box_expected(idx, box_with_array)
1894
+ msg = "|".join(
1895
+ [
1896
+ "cannot use operands with types dtype",
1897
+ "Cannot multiply with unequal lengths",
1898
+ "Unable to coerce to Series",
1899
+ ]
1900
+ )
1901
+ with pytest.raises(TypeError, match=msg):
1902
+ # length check before dtype check
1903
+ idx * idx[:3]
1904
+ with pytest.raises(ValueError, match=msg):
1905
+ idx * np.array([1, 2])
1906
+
1907
+ def test_td64arr_mul_td64arr_raises(self, box_with_array):
1908
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
1909
+ idx = tm.box_expected(idx, box_with_array)
1910
+ msg = "cannot use operands with types dtype"
1911
+ with pytest.raises(TypeError, match=msg):
1912
+ idx * idx
1913
+
1914
+ # ------------------------------------------------------------------
1915
+ # Operations with numeric others
1916
+
1917
+ def test_td64arr_mul_numeric_scalar(self, box_with_array, one):
1918
+ # GH#4521
1919
+ # divide/multiply by integers
1920
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
1921
+ expected = Series(["-59 Days", "-59 Days", "NaT"], dtype="timedelta64[ns]")
1922
+
1923
+ tdser = tm.box_expected(tdser, box_with_array)
1924
+ expected = tm.box_expected(expected, box_with_array)
1925
+
1926
+ result = tdser * (-one)
1927
+ tm.assert_equal(result, expected)
1928
+ result = (-one) * tdser
1929
+ tm.assert_equal(result, expected)
1930
+
1931
+ expected = Series(["118 Days", "118 Days", "NaT"], dtype="timedelta64[ns]")
1932
+ expected = tm.box_expected(expected, box_with_array)
1933
+
1934
+ result = tdser * (2 * one)
1935
+ tm.assert_equal(result, expected)
1936
+ result = (2 * one) * tdser
1937
+ tm.assert_equal(result, expected)
1938
+
1939
+ @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)])
1940
+ def test_td64arr_div_numeric_scalar(self, box_with_array, two):
1941
+ # GH#4521
1942
+ # divide/multiply by integers
1943
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
1944
+ expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]")
1945
+
1946
+ tdser = tm.box_expected(tdser, box_with_array)
1947
+ expected = tm.box_expected(expected, box_with_array)
1948
+
1949
+ result = tdser / two
1950
+ tm.assert_equal(result, expected)
1951
+
1952
+ with pytest.raises(TypeError, match="Cannot divide"):
1953
+ two / tdser
1954
+
1955
+ @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)])
1956
+ def test_td64arr_floordiv_numeric_scalar(self, box_with_array, two):
1957
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
1958
+ expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]")
1959
+
1960
+ tdser = tm.box_expected(tdser, box_with_array)
1961
+ expected = tm.box_expected(expected, box_with_array)
1962
+
1963
+ result = tdser // two
1964
+ tm.assert_equal(result, expected)
1965
+
1966
+ with pytest.raises(TypeError, match="Cannot divide"):
1967
+ two // tdser
1968
+
1969
+ @pytest.mark.parametrize(
1970
+ "vector",
1971
+ [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
1972
+ ids=lambda x: type(x).__name__,
1973
+ )
1974
+ def test_td64arr_rmul_numeric_array(
1975
+ self,
1976
+ box_with_array,
1977
+ vector,
1978
+ any_real_numpy_dtype,
1979
+ ):
1980
+ # GH#4521
1981
+ # divide/multiply by integers
1982
+
1983
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
1984
+ vector = vector.astype(any_real_numpy_dtype)
1985
+
1986
+ expected = Series(["1180 Days", "1770 Days", "NaT"], dtype="timedelta64[ns]")
1987
+
1988
+ tdser = tm.box_expected(tdser, box_with_array)
1989
+ xbox = get_upcast_box(tdser, vector)
1990
+
1991
+ expected = tm.box_expected(expected, xbox)
1992
+
1993
+ result = tdser * vector
1994
+ tm.assert_equal(result, expected)
1995
+
1996
+ result = vector * tdser
1997
+ tm.assert_equal(result, expected)
1998
+
1999
+ @pytest.mark.parametrize(
2000
+ "vector",
2001
+ [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
2002
+ ids=lambda x: type(x).__name__,
2003
+ )
2004
+ def test_td64arr_div_numeric_array(
2005
+ self, box_with_array, vector, any_real_numpy_dtype
2006
+ ):
2007
+ # GH#4521
2008
+ # divide/multiply by integers
2009
+
2010
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
2011
+ vector = vector.astype(any_real_numpy_dtype)
2012
+
2013
+ expected = Series(["2.95D", "1D 23h 12m", "NaT"], dtype="timedelta64[ns]")
2014
+
2015
+ tdser = tm.box_expected(tdser, box_with_array)
2016
+ xbox = get_upcast_box(tdser, vector)
2017
+ expected = tm.box_expected(expected, xbox)
2018
+
2019
+ result = tdser / vector
2020
+ tm.assert_equal(result, expected)
2021
+
2022
+ pattern = "|".join(
2023
+ [
2024
+ "true_divide'? cannot use operands",
2025
+ "cannot perform __div__",
2026
+ "cannot perform __truediv__",
2027
+ "unsupported operand",
2028
+ "Cannot divide",
2029
+ "ufunc 'divide' cannot use operands with types",
2030
+ ]
2031
+ )
2032
+ with pytest.raises(TypeError, match=pattern):
2033
+ vector / tdser
2034
+
2035
+ result = tdser / vector.astype(object)
2036
+ if box_with_array is DataFrame:
2037
+ expected = [tdser.iloc[0, n] / vector[n] for n in range(len(vector))]
2038
+ expected = tm.box_expected(expected, xbox).astype(object)
2039
+ # We specifically expect timedelta64("NaT") here, not pd.NA
2040
+ msg = "The 'downcast' keyword in fillna"
2041
+ with tm.assert_produces_warning(FutureWarning, match=msg):
2042
+ expected[2] = expected[2].fillna(
2043
+ np.timedelta64("NaT", "ns"), downcast=False
2044
+ )
2045
+ else:
2046
+ expected = [tdser[n] / vector[n] for n in range(len(tdser))]
2047
+ expected = [
2048
+ x if x is not NaT else np.timedelta64("NaT", "ns") for x in expected
2049
+ ]
2050
+ if xbox is tm.to_array:
2051
+ expected = tm.to_array(expected).astype(object)
2052
+ else:
2053
+ expected = xbox(expected, dtype=object)
2054
+
2055
+ tm.assert_equal(result, expected)
2056
+
2057
+ with pytest.raises(TypeError, match=pattern):
2058
+ vector.astype(object) / tdser
2059
+
2060
+ def test_td64arr_mul_int_series(self, box_with_array, names):
2061
+ # GH#19042 test for correct name attachment
2062
+ box = box_with_array
2063
+ exname = get_expected_name(box, names)
2064
+
2065
+ tdi = TimedeltaIndex(
2066
+ ["0days", "1day", "2days", "3days", "4days"], name=names[0]
2067
+ )
2068
+ # TODO: Should we be parametrizing over types for `ser` too?
2069
+ ser = Series([0, 1, 2, 3, 4], dtype=np.int64, name=names[1])
2070
+
2071
+ expected = Series(
2072
+ ["0days", "1day", "4days", "9days", "16days"],
2073
+ dtype="timedelta64[ns]",
2074
+ name=exname,
2075
+ )
2076
+
2077
+ tdi = tm.box_expected(tdi, box)
2078
+ xbox = get_upcast_box(tdi, ser)
2079
+
2080
+ expected = tm.box_expected(expected, xbox)
2081
+
2082
+ result = ser * tdi
2083
+ tm.assert_equal(result, expected)
2084
+
2085
+ result = tdi * ser
2086
+ tm.assert_equal(result, expected)
2087
+
2088
+ # TODO: Should we be parametrizing over types for `ser` too?
2089
+ def test_float_series_rdiv_td64arr(self, box_with_array, names):
2090
+ # GH#19042 test for correct name attachment
2091
+ box = box_with_array
2092
+ tdi = TimedeltaIndex(
2093
+ ["0days", "1day", "2days", "3days", "4days"], name=names[0]
2094
+ )
2095
+ ser = Series([1.5, 3, 4.5, 6, 7.5], dtype=np.float64, name=names[1])
2096
+
2097
+ xname = names[2] if box not in [tm.to_array, pd.array] else names[1]
2098
+ expected = Series(
2099
+ [tdi[n] / ser[n] for n in range(len(ser))],
2100
+ dtype="timedelta64[ns]",
2101
+ name=xname,
2102
+ )
2103
+
2104
+ tdi = tm.box_expected(tdi, box)
2105
+ xbox = get_upcast_box(tdi, ser)
2106
+ expected = tm.box_expected(expected, xbox)
2107
+
2108
+ result = ser.__rtruediv__(tdi)
2109
+ if box is DataFrame:
2110
+ assert result is NotImplemented
2111
+ else:
2112
+ tm.assert_equal(result, expected)
2113
+
2114
+ def test_td64arr_all_nat_div_object_dtype_numeric(self, box_with_array):
2115
+ # GH#39750 make sure we infer the result as td64
2116
+ tdi = TimedeltaIndex([NaT, NaT])
2117
+
2118
+ left = tm.box_expected(tdi, box_with_array)
2119
+ right = np.array([2, 2.0], dtype=object)
2120
+
2121
+ tdnat = np.timedelta64("NaT", "ns")
2122
+ expected = Index([tdnat] * 2, dtype=object)
2123
+ if box_with_array is not Index:
2124
+ expected = tm.box_expected(expected, box_with_array).astype(object)
2125
+ if box_with_array in [Series, DataFrame]:
2126
+ msg = "The 'downcast' keyword in fillna is deprecated"
2127
+ with tm.assert_produces_warning(FutureWarning, match=msg):
2128
+ expected = expected.fillna(tdnat, downcast=False) # GH#18463
2129
+
2130
+ result = left / right
2131
+ tm.assert_equal(result, expected)
2132
+
2133
+ result = left // right
2134
+ tm.assert_equal(result, expected)
2135
+
2136
+
2137
+ class TestTimedelta64ArrayLikeArithmetic:
2138
+ # Arithmetic tests for timedelta64[ns] vectors fully parametrized over
2139
+ # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all arithmetic
2140
+ # tests will eventually end up here.
2141
+
2142
+ def test_td64arr_pow_invalid(self, scalar_td, box_with_array):
2143
+ td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
2144
+ td1.iloc[2] = np.nan
2145
+
2146
+ td1 = tm.box_expected(td1, box_with_array)
2147
+
2148
+ # check that we are getting a TypeError
2149
+ # with 'operate' (from core/ops.py) for the ops that are not
2150
+ # defined
2151
+ pattern = "operate|unsupported|cannot|not supported"
2152
+ with pytest.raises(TypeError, match=pattern):
2153
+ scalar_td**td1
2154
+
2155
+ with pytest.raises(TypeError, match=pattern):
2156
+ td1**scalar_td
2157
+
2158
+
2159
+ def test_add_timestamp_to_timedelta():
2160
+ # GH: 35897
2161
+ timestamp = Timestamp("2021-01-01")
2162
+ result = timestamp + timedelta_range("0s", "1s", periods=31)
2163
+ expected = DatetimeIndex(
2164
+ [
2165
+ timestamp
2166
+ + (
2167
+ pd.to_timedelta("0.033333333s") * i
2168
+ + pd.to_timedelta("0.000000001s") * divmod(i, 3)[0]
2169
+ )
2170
+ for i in range(31)
2171
+ ]
2172
+ )
2173
+ tm.assert_index_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/computation/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/test_compat.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/computation/__pycache__/test_eval.cpython-310.pyc ADDED
Binary file (58.5 kB). View file
 
venv/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
venv/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)
venv/lib/python3.10/site-packages/pandas/tests/config/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/config/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/config/__pycache__/test_config.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/config/__pycache__/test_localization.cpython-310.pyc ADDED
Binary file (3.7 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/config/test_config.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas._config import config as cf
4
+ from pandas._config.config import OptionError
5
+
6
+ import pandas as pd
7
+ import pandas._testing as tm
8
+
9
+
10
+ class TestConfig:
11
+ @pytest.fixture(autouse=True)
12
+ def clean_config(self, monkeypatch):
13
+ with monkeypatch.context() as m:
14
+ m.setattr(cf, "_global_config", {})
15
+ m.setattr(cf, "options", cf.DictWrapper(cf._global_config))
16
+ m.setattr(cf, "_deprecated_options", {})
17
+ m.setattr(cf, "_registered_options", {})
18
+
19
+ # Our test fixture in conftest.py sets "chained_assignment"
20
+ # to "raise" only after all test methods have been setup.
21
+ # However, after this setup, there is no longer any
22
+ # "chained_assignment" option, so re-register it.
23
+ cf.register_option("chained_assignment", "raise")
24
+ yield
25
+
26
+ def test_api(self):
27
+ # the pandas object exposes the user API
28
+ assert hasattr(pd, "get_option")
29
+ assert hasattr(pd, "set_option")
30
+ assert hasattr(pd, "reset_option")
31
+ assert hasattr(pd, "describe_option")
32
+
33
+ def test_is_one_of_factory(self):
34
+ v = cf.is_one_of_factory([None, 12])
35
+
36
+ v(12)
37
+ v(None)
38
+ msg = r"Value must be one of None\|12"
39
+ with pytest.raises(ValueError, match=msg):
40
+ v(1.1)
41
+
42
+ def test_register_option(self):
43
+ cf.register_option("a", 1, "doc")
44
+
45
+ # can't register an already registered option
46
+ msg = "Option 'a' has already been registered"
47
+ with pytest.raises(OptionError, match=msg):
48
+ cf.register_option("a", 1, "doc")
49
+
50
+ # can't register an already registered option
51
+ msg = "Path prefix to option 'a' is already an option"
52
+ with pytest.raises(OptionError, match=msg):
53
+ cf.register_option("a.b.c.d1", 1, "doc")
54
+ with pytest.raises(OptionError, match=msg):
55
+ cf.register_option("a.b.c.d2", 1, "doc")
56
+
57
+ # no python keywords
58
+ msg = "for is a python keyword"
59
+ with pytest.raises(ValueError, match=msg):
60
+ cf.register_option("for", 0)
61
+ with pytest.raises(ValueError, match=msg):
62
+ cf.register_option("a.for.b", 0)
63
+ # must be valid identifier (ensure attribute access works)
64
+ msg = "oh my goddess! is not a valid identifier"
65
+ with pytest.raises(ValueError, match=msg):
66
+ cf.register_option("Oh my Goddess!", 0)
67
+
68
+ # we can register options several levels deep
69
+ # without predefining the intermediate steps
70
+ # and we can define differently named options
71
+ # in the same namespace
72
+ cf.register_option("k.b.c.d1", 1, "doc")
73
+ cf.register_option("k.b.c.d2", 1, "doc")
74
+
75
+ def test_describe_option(self):
76
+ cf.register_option("a", 1, "doc")
77
+ cf.register_option("b", 1, "doc2")
78
+ cf.deprecate_option("b")
79
+
80
+ cf.register_option("c.d.e1", 1, "doc3")
81
+ cf.register_option("c.d.e2", 1, "doc4")
82
+ cf.register_option("f", 1)
83
+ cf.register_option("g.h", 1)
84
+ cf.register_option("k", 2)
85
+ cf.deprecate_option("g.h", rkey="k")
86
+ cf.register_option("l", "foo")
87
+
88
+ # non-existent keys raise KeyError
89
+ msg = r"No such keys\(s\)"
90
+ with pytest.raises(OptionError, match=msg):
91
+ cf.describe_option("no.such.key")
92
+
93
+ # we can get the description for any key we registered
94
+ assert "doc" in cf.describe_option("a", _print_desc=False)
95
+ assert "doc2" in cf.describe_option("b", _print_desc=False)
96
+ assert "precated" in cf.describe_option("b", _print_desc=False)
97
+ assert "doc3" in cf.describe_option("c.d.e1", _print_desc=False)
98
+ assert "doc4" in cf.describe_option("c.d.e2", _print_desc=False)
99
+
100
+ # if no doc is specified we get a default message
101
+ # saying "description not available"
102
+ assert "available" in cf.describe_option("f", _print_desc=False)
103
+ assert "available" in cf.describe_option("g.h", _print_desc=False)
104
+ assert "precated" in cf.describe_option("g.h", _print_desc=False)
105
+ assert "k" in cf.describe_option("g.h", _print_desc=False)
106
+
107
+ # default is reported
108
+ assert "foo" in cf.describe_option("l", _print_desc=False)
109
+ # current value is reported
110
+ assert "bar" not in cf.describe_option("l", _print_desc=False)
111
+ cf.set_option("l", "bar")
112
+ assert "bar" in cf.describe_option("l", _print_desc=False)
113
+
114
+ def test_case_insensitive(self):
115
+ cf.register_option("KanBAN", 1, "doc")
116
+
117
+ assert "doc" in cf.describe_option("kanbaN", _print_desc=False)
118
+ assert cf.get_option("kanBaN") == 1
119
+ cf.set_option("KanBan", 2)
120
+ assert cf.get_option("kAnBaN") == 2
121
+
122
+ # gets of non-existent keys fail
123
+ msg = r"No such keys\(s\): 'no_such_option'"
124
+ with pytest.raises(OptionError, match=msg):
125
+ cf.get_option("no_such_option")
126
+ cf.deprecate_option("KanBan")
127
+
128
+ assert cf._is_deprecated("kAnBaN")
129
+
130
+ def test_get_option(self):
131
+ cf.register_option("a", 1, "doc")
132
+ cf.register_option("b.c", "hullo", "doc2")
133
+ cf.register_option("b.b", None, "doc2")
134
+
135
+ # gets of existing keys succeed
136
+ assert cf.get_option("a") == 1
137
+ assert cf.get_option("b.c") == "hullo"
138
+ assert cf.get_option("b.b") is None
139
+
140
+ # gets of non-existent keys fail
141
+ msg = r"No such keys\(s\): 'no_such_option'"
142
+ with pytest.raises(OptionError, match=msg):
143
+ cf.get_option("no_such_option")
144
+
145
+ def test_set_option(self):
146
+ cf.register_option("a", 1, "doc")
147
+ cf.register_option("b.c", "hullo", "doc2")
148
+ cf.register_option("b.b", None, "doc2")
149
+
150
+ assert cf.get_option("a") == 1
151
+ assert cf.get_option("b.c") == "hullo"
152
+ assert cf.get_option("b.b") is None
153
+
154
+ cf.set_option("a", 2)
155
+ cf.set_option("b.c", "wurld")
156
+ cf.set_option("b.b", 1.1)
157
+
158
+ assert cf.get_option("a") == 2
159
+ assert cf.get_option("b.c") == "wurld"
160
+ assert cf.get_option("b.b") == 1.1
161
+
162
+ msg = r"No such keys\(s\): 'no.such.key'"
163
+ with pytest.raises(OptionError, match=msg):
164
+ cf.set_option("no.such.key", None)
165
+
166
+ def test_set_option_empty_args(self):
167
+ msg = "Must provide an even number of non-keyword arguments"
168
+ with pytest.raises(ValueError, match=msg):
169
+ cf.set_option()
170
+
171
+ def test_set_option_uneven_args(self):
172
+ msg = "Must provide an even number of non-keyword arguments"
173
+ with pytest.raises(ValueError, match=msg):
174
+ cf.set_option("a.b", 2, "b.c")
175
+
176
+ def test_set_option_invalid_single_argument_type(self):
177
+ msg = "Must provide an even number of non-keyword arguments"
178
+ with pytest.raises(ValueError, match=msg):
179
+ cf.set_option(2)
180
+
181
+ def test_set_option_multiple(self):
182
+ cf.register_option("a", 1, "doc")
183
+ cf.register_option("b.c", "hullo", "doc2")
184
+ cf.register_option("b.b", None, "doc2")
185
+
186
+ assert cf.get_option("a") == 1
187
+ assert cf.get_option("b.c") == "hullo"
188
+ assert cf.get_option("b.b") is None
189
+
190
+ cf.set_option("a", "2", "b.c", None, "b.b", 10.0)
191
+
192
+ assert cf.get_option("a") == "2"
193
+ assert cf.get_option("b.c") is None
194
+ assert cf.get_option("b.b") == 10.0
195
+
196
+ def test_validation(self):
197
+ cf.register_option("a", 1, "doc", validator=cf.is_int)
198
+ cf.register_option("d", 1, "doc", validator=cf.is_nonnegative_int)
199
+ cf.register_option("b.c", "hullo", "doc2", validator=cf.is_text)
200
+
201
+ msg = "Value must have type '<class 'int'>'"
202
+ with pytest.raises(ValueError, match=msg):
203
+ cf.register_option("a.b.c.d2", "NO", "doc", validator=cf.is_int)
204
+
205
+ cf.set_option("a", 2) # int is_int
206
+ cf.set_option("b.c", "wurld") # str is_str
207
+ cf.set_option("d", 2)
208
+ cf.set_option("d", None) # non-negative int can be None
209
+
210
+ # None not is_int
211
+ with pytest.raises(ValueError, match=msg):
212
+ cf.set_option("a", None)
213
+ with pytest.raises(ValueError, match=msg):
214
+ cf.set_option("a", "ab")
215
+
216
+ msg = "Value must be a nonnegative integer or None"
217
+ with pytest.raises(ValueError, match=msg):
218
+ cf.register_option("a.b.c.d3", "NO", "doc", validator=cf.is_nonnegative_int)
219
+ with pytest.raises(ValueError, match=msg):
220
+ cf.register_option("a.b.c.d3", -2, "doc", validator=cf.is_nonnegative_int)
221
+
222
+ msg = r"Value must be an instance of <class 'str'>\|<class 'bytes'>"
223
+ with pytest.raises(ValueError, match=msg):
224
+ cf.set_option("b.c", 1)
225
+
226
+ validator = cf.is_one_of_factory([None, cf.is_callable])
227
+ cf.register_option("b", lambda: None, "doc", validator=validator)
228
+ # pylint: disable-next=consider-using-f-string
229
+ cf.set_option("b", "%.1f".format) # Formatter is callable
230
+ cf.set_option("b", None) # Formatter is none (default)
231
+ with pytest.raises(ValueError, match="Value must be a callable"):
232
+ cf.set_option("b", "%.1f")
233
+
234
+ def test_reset_option(self):
235
+ cf.register_option("a", 1, "doc", validator=cf.is_int)
236
+ cf.register_option("b.c", "hullo", "doc2", validator=cf.is_str)
237
+ assert cf.get_option("a") == 1
238
+ assert cf.get_option("b.c") == "hullo"
239
+
240
+ cf.set_option("a", 2)
241
+ cf.set_option("b.c", "wurld")
242
+ assert cf.get_option("a") == 2
243
+ assert cf.get_option("b.c") == "wurld"
244
+
245
+ cf.reset_option("a")
246
+ assert cf.get_option("a") == 1
247
+ assert cf.get_option("b.c") == "wurld"
248
+ cf.reset_option("b.c")
249
+ assert cf.get_option("a") == 1
250
+ assert cf.get_option("b.c") == "hullo"
251
+
252
+ def test_reset_option_all(self):
253
+ cf.register_option("a", 1, "doc", validator=cf.is_int)
254
+ cf.register_option("b.c", "hullo", "doc2", validator=cf.is_str)
255
+ assert cf.get_option("a") == 1
256
+ assert cf.get_option("b.c") == "hullo"
257
+
258
+ cf.set_option("a", 2)
259
+ cf.set_option("b.c", "wurld")
260
+ assert cf.get_option("a") == 2
261
+ assert cf.get_option("b.c") == "wurld"
262
+
263
+ cf.reset_option("all")
264
+ assert cf.get_option("a") == 1
265
+ assert cf.get_option("b.c") == "hullo"
266
+
267
+ def test_deprecate_option(self):
268
+ # we can deprecate non-existent options
269
+ cf.deprecate_option("foo")
270
+
271
+ assert cf._is_deprecated("foo")
272
+ with tm.assert_produces_warning(FutureWarning, match="deprecated"):
273
+ with pytest.raises(KeyError, match="No such keys.s.: 'foo'"):
274
+ cf.get_option("foo")
275
+
276
+ cf.register_option("a", 1, "doc", validator=cf.is_int)
277
+ cf.register_option("b.c", "hullo", "doc2")
278
+ cf.register_option("foo", "hullo", "doc2")
279
+
280
+ cf.deprecate_option("a", removal_ver="nifty_ver")
281
+ with tm.assert_produces_warning(FutureWarning, match="eprecated.*nifty_ver"):
282
+ cf.get_option("a")
283
+
284
+ msg = "Option 'a' has already been defined as deprecated"
285
+ with pytest.raises(OptionError, match=msg):
286
+ cf.deprecate_option("a")
287
+
288
+ cf.deprecate_option("b.c", "zounds!")
289
+ with tm.assert_produces_warning(FutureWarning, match="zounds!"):
290
+ cf.get_option("b.c")
291
+
292
+ # test rerouting keys
293
+ cf.register_option("d.a", "foo", "doc2")
294
+ cf.register_option("d.dep", "bar", "doc2")
295
+ assert cf.get_option("d.a") == "foo"
296
+ assert cf.get_option("d.dep") == "bar"
297
+
298
+ cf.deprecate_option("d.dep", rkey="d.a") # reroute d.dep to d.a
299
+ with tm.assert_produces_warning(FutureWarning, match="eprecated"):
300
+ assert cf.get_option("d.dep") == "foo"
301
+
302
+ with tm.assert_produces_warning(FutureWarning, match="eprecated"):
303
+ cf.set_option("d.dep", "baz") # should overwrite "d.a"
304
+
305
+ with tm.assert_produces_warning(FutureWarning, match="eprecated"):
306
+ assert cf.get_option("d.dep") == "baz"
307
+
308
+ def test_config_prefix(self):
309
+ with cf.config_prefix("base"):
310
+ cf.register_option("a", 1, "doc1")
311
+ cf.register_option("b", 2, "doc2")
312
+ assert cf.get_option("a") == 1
313
+ assert cf.get_option("b") == 2
314
+
315
+ cf.set_option("a", 3)
316
+ cf.set_option("b", 4)
317
+ assert cf.get_option("a") == 3
318
+ assert cf.get_option("b") == 4
319
+
320
+ assert cf.get_option("base.a") == 3
321
+ assert cf.get_option("base.b") == 4
322
+ assert "doc1" in cf.describe_option("base.a", _print_desc=False)
323
+ assert "doc2" in cf.describe_option("base.b", _print_desc=False)
324
+
325
+ cf.reset_option("base.a")
326
+ cf.reset_option("base.b")
327
+
328
+ with cf.config_prefix("base"):
329
+ assert cf.get_option("a") == 1
330
+ assert cf.get_option("b") == 2
331
+
332
+ def test_callback(self):
333
+ k = [None]
334
+ v = [None]
335
+
336
+ def callback(key):
337
+ k.append(key)
338
+ v.append(cf.get_option(key))
339
+
340
+ cf.register_option("d.a", "foo", cb=callback)
341
+ cf.register_option("d.b", "foo", cb=callback)
342
+
343
+ del k[-1], v[-1]
344
+ cf.set_option("d.a", "fooz")
345
+ assert k[-1] == "d.a"
346
+ assert v[-1] == "fooz"
347
+
348
+ del k[-1], v[-1]
349
+ cf.set_option("d.b", "boo")
350
+ assert k[-1] == "d.b"
351
+ assert v[-1] == "boo"
352
+
353
+ del k[-1], v[-1]
354
+ cf.reset_option("d.b")
355
+ assert k[-1] == "d.b"
356
+
357
+ def test_set_ContextManager(self):
358
+ def eq(val):
359
+ assert cf.get_option("a") == val
360
+
361
+ cf.register_option("a", 0)
362
+ eq(0)
363
+ with cf.option_context("a", 15):
364
+ eq(15)
365
+ with cf.option_context("a", 25):
366
+ eq(25)
367
+ eq(15)
368
+ eq(0)
369
+
370
+ cf.set_option("a", 17)
371
+ eq(17)
372
+
373
+ # Test that option_context can be used as a decorator too (#34253).
374
+ @cf.option_context("a", 123)
375
+ def f():
376
+ eq(123)
377
+
378
+ f()
379
+
380
+ def test_attribute_access(self):
381
+ holder = []
382
+
383
+ def f3(key):
384
+ holder.append(True)
385
+
386
+ cf.register_option("a", 0)
387
+ cf.register_option("c", 0, cb=f3)
388
+ options = cf.options
389
+
390
+ assert options.a == 0
391
+ with cf.option_context("a", 15):
392
+ assert options.a == 15
393
+
394
+ options.a = 500
395
+ assert cf.get_option("a") == 500
396
+
397
+ cf.reset_option("a")
398
+ assert options.a == cf.get_option("a", 0)
399
+
400
+ msg = "You can only set the value of existing options"
401
+ with pytest.raises(OptionError, match=msg):
402
+ options.b = 1
403
+ with pytest.raises(OptionError, match=msg):
404
+ options.display = 1
405
+
406
+ # make sure callback kicks when using this form of setting
407
+ options.c = 1
408
+ assert len(holder) == 1
409
+
410
+ def test_option_context_scope(self):
411
+ # Ensure that creating a context does not affect the existing
412
+ # environment as it is supposed to be used with the `with` statement.
413
+ # See https://github.com/pandas-dev/pandas/issues/8514
414
+
415
+ original_value = 60
416
+ context_value = 10
417
+ option_name = "a"
418
+
419
+ cf.register_option(option_name, original_value)
420
+
421
+ # Ensure creating contexts didn't affect the current context.
422
+ ctx = cf.option_context(option_name, context_value)
423
+ assert cf.get_option(option_name) == original_value
424
+
425
+ # Ensure the correct value is available inside the context.
426
+ with ctx:
427
+ assert cf.get_option(option_name) == context_value
428
+
429
+ # Ensure the current context is reset
430
+ assert cf.get_option(option_name) == original_value
431
+
432
+ def test_dictwrapper_getattr(self):
433
+ options = cf.options
434
+ # GH 19789
435
+ with pytest.raises(OptionError, match="No such option"):
436
+ options.bananas
437
+ assert not hasattr(options, "bananas")
venv/lib/python3.10/site-packages/pandas/tests/config/test_localization.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import codecs
2
+ import locale
3
+ import os
4
+
5
+ import pytest
6
+
7
+ from pandas._config.localization import (
8
+ can_set_locale,
9
+ get_locales,
10
+ set_locale,
11
+ )
12
+
13
+ from pandas.compat import ISMUSL
14
+
15
+ import pandas as pd
16
+
17
+ _all_locales = get_locales()
18
+ _current_locale = locale.setlocale(locale.LC_ALL) # getlocale() is wrong, see GH#46595
19
+
20
+ # Don't run any of these tests if we have no locales.
21
+ pytestmark = pytest.mark.skipif(not _all_locales, reason="Need locales")
22
+
23
+ _skip_if_only_one_locale = pytest.mark.skipif(
24
+ len(_all_locales) <= 1, reason="Need multiple locales for meaningful test"
25
+ )
26
+
27
+
28
+ def _get_current_locale(lc_var: int = locale.LC_ALL) -> str:
29
+ # getlocale is not always compliant with setlocale, use setlocale. GH#46595
30
+ return locale.setlocale(lc_var)
31
+
32
+
33
+ @pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))
34
+ def test_can_set_current_locale(lc_var):
35
+ # Can set the current locale
36
+ before_locale = _get_current_locale(lc_var)
37
+ assert can_set_locale(before_locale, lc_var=lc_var)
38
+ after_locale = _get_current_locale(lc_var)
39
+ assert before_locale == after_locale
40
+
41
+
42
+ @pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))
43
+ def test_can_set_locale_valid_set(lc_var):
44
+ # Can set the default locale.
45
+ before_locale = _get_current_locale(lc_var)
46
+ assert can_set_locale("", lc_var=lc_var)
47
+ after_locale = _get_current_locale(lc_var)
48
+ assert before_locale == after_locale
49
+
50
+
51
+ @pytest.mark.parametrize(
52
+ "lc_var",
53
+ (
54
+ locale.LC_ALL,
55
+ locale.LC_CTYPE,
56
+ pytest.param(
57
+ locale.LC_TIME,
58
+ marks=pytest.mark.skipif(
59
+ ISMUSL, reason="MUSL allows setting invalid LC_TIME."
60
+ ),
61
+ ),
62
+ ),
63
+ )
64
+ def test_can_set_locale_invalid_set(lc_var):
65
+ # Cannot set an invalid locale.
66
+ before_locale = _get_current_locale(lc_var)
67
+ assert not can_set_locale("non-existent_locale", lc_var=lc_var)
68
+ after_locale = _get_current_locale(lc_var)
69
+ assert before_locale == after_locale
70
+
71
+
72
+ @pytest.mark.parametrize(
73
+ "lang,enc",
74
+ [
75
+ ("it_CH", "UTF-8"),
76
+ ("en_US", "ascii"),
77
+ ("zh_CN", "GB2312"),
78
+ ("it_IT", "ISO-8859-1"),
79
+ ],
80
+ )
81
+ @pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))
82
+ def test_can_set_locale_no_leak(lang, enc, lc_var):
83
+ # Test that can_set_locale does not leak even when returning False. See GH#46595
84
+ before_locale = _get_current_locale(lc_var)
85
+ can_set_locale((lang, enc), locale.LC_ALL)
86
+ after_locale = _get_current_locale(lc_var)
87
+ assert before_locale == after_locale
88
+
89
+
90
+ def test_can_set_locale_invalid_get(monkeypatch):
91
+ # see GH#22129
92
+ # In some cases, an invalid locale can be set,
93
+ # but a subsequent getlocale() raises a ValueError.
94
+
95
+ def mock_get_locale():
96
+ raise ValueError()
97
+
98
+ with monkeypatch.context() as m:
99
+ m.setattr(locale, "getlocale", mock_get_locale)
100
+ assert not can_set_locale("")
101
+
102
+
103
+ def test_get_locales_at_least_one():
104
+ # see GH#9744
105
+ assert len(_all_locales) > 0
106
+
107
+
108
+ @_skip_if_only_one_locale
109
+ def test_get_locales_prefix():
110
+ first_locale = _all_locales[0]
111
+ assert len(get_locales(prefix=first_locale[:2])) > 0
112
+
113
+
114
+ @_skip_if_only_one_locale
115
+ @pytest.mark.parametrize(
116
+ "lang,enc",
117
+ [
118
+ ("it_CH", "UTF-8"),
119
+ ("en_US", "ascii"),
120
+ ("zh_CN", "GB2312"),
121
+ ("it_IT", "ISO-8859-1"),
122
+ ],
123
+ )
124
+ def test_set_locale(lang, enc):
125
+ before_locale = _get_current_locale()
126
+
127
+ enc = codecs.lookup(enc).name
128
+ new_locale = lang, enc
129
+
130
+ if not can_set_locale(new_locale):
131
+ msg = "unsupported locale setting"
132
+
133
+ with pytest.raises(locale.Error, match=msg):
134
+ with set_locale(new_locale):
135
+ pass
136
+ else:
137
+ with set_locale(new_locale) as normalized_locale:
138
+ new_lang, new_enc = normalized_locale.split(".")
139
+ new_enc = codecs.lookup(enc).name
140
+
141
+ normalized_locale = new_lang, new_enc
142
+ assert normalized_locale == new_locale
143
+
144
+ # Once we exit the "with" statement, locale should be back to what it was.
145
+ after_locale = _get_current_locale()
146
+ assert before_locale == after_locale
147
+
148
+
149
+ def test_encoding_detected():
150
+ system_locale = os.environ.get("LC_ALL")
151
+ system_encoding = system_locale.split(".")[-1] if system_locale else "utf-8"
152
+
153
+ assert (
154
+ codecs.lookup(pd.options.display.encoding).name
155
+ == codecs.lookup(system_encoding).name
156
+ )
venv/lib/python3.10/site-packages/pandas/tests/interchange/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/interchange/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/interchange/__pycache__/test_impl.cpython-310.pyc ADDED
Binary file (17.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/interchange/__pycache__/test_spec_conformance.cpython-310.pyc ADDED
Binary file (5.26 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/interchange/__pycache__/test_utils.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/interchange/test_impl.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ datetime,
3
+ timezone,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas._libs.tslibs import iNaT
10
+ from pandas.compat import (
11
+ is_ci_environment,
12
+ is_platform_windows,
13
+ )
14
+ from pandas.compat.numpy import np_version_lt1p23
15
+
16
+ import pandas as pd
17
+ import pandas._testing as tm
18
+ from pandas.core.interchange.column import PandasColumn
19
+ from pandas.core.interchange.dataframe_protocol import (
20
+ ColumnNullType,
21
+ DtypeKind,
22
+ )
23
+ from pandas.core.interchange.from_dataframe import from_dataframe
24
+ from pandas.core.interchange.utils import ArrowCTypes
25
+
26
+
27
+ @pytest.fixture
28
+ def data_categorical():
29
+ return {
30
+ "ordered": pd.Categorical(list("testdata") * 30, ordered=True),
31
+ "unordered": pd.Categorical(list("testdata") * 30, ordered=False),
32
+ }
33
+
34
+
35
+ @pytest.fixture
36
+ def string_data():
37
+ return {
38
+ "separator data": [
39
+ "abC|DeF,Hik",
40
+ "234,3245.67",
41
+ "gSaf,qWer|Gre",
42
+ "asd3,4sad|",
43
+ np.nan,
44
+ ]
45
+ }
46
+
47
+
48
+ @pytest.mark.parametrize("data", [("ordered", True), ("unordered", False)])
49
+ def test_categorical_dtype(data, data_categorical):
50
+ df = pd.DataFrame({"A": (data_categorical[data[0]])})
51
+
52
+ col = df.__dataframe__().get_column_by_name("A")
53
+ assert col.dtype[0] == DtypeKind.CATEGORICAL
54
+ assert col.null_count == 0
55
+ assert col.describe_null == (ColumnNullType.USE_SENTINEL, -1)
56
+ assert col.num_chunks() == 1
57
+ desc_cat = col.describe_categorical
58
+ assert desc_cat["is_ordered"] == data[1]
59
+ assert desc_cat["is_dictionary"] is True
60
+ assert isinstance(desc_cat["categories"], PandasColumn)
61
+ tm.assert_series_equal(
62
+ desc_cat["categories"]._col, pd.Series(["a", "d", "e", "s", "t"])
63
+ )
64
+
65
+ tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))
66
+
67
+
68
+ def test_categorical_pyarrow():
69
+ # GH 49889
70
+ pa = pytest.importorskip("pyarrow", "11.0.0")
71
+
72
+ arr = ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"]
73
+ table = pa.table({"weekday": pa.array(arr).dictionary_encode()})
74
+ exchange_df = table.__dataframe__()
75
+ result = from_dataframe(exchange_df)
76
+ weekday = pd.Categorical(
77
+ arr, categories=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
78
+ )
79
+ expected = pd.DataFrame({"weekday": weekday})
80
+ tm.assert_frame_equal(result, expected)
81
+
82
+
83
+ def test_empty_categorical_pyarrow():
84
+ # https://github.com/pandas-dev/pandas/issues/53077
85
+ pa = pytest.importorskip("pyarrow", "11.0.0")
86
+
87
+ arr = [None]
88
+ table = pa.table({"arr": pa.array(arr, "float64").dictionary_encode()})
89
+ exchange_df = table.__dataframe__()
90
+ result = pd.api.interchange.from_dataframe(exchange_df)
91
+ expected = pd.DataFrame({"arr": pd.Categorical([np.nan])})
92
+ tm.assert_frame_equal(result, expected)
93
+
94
+
95
+ def test_large_string_pyarrow():
96
+ # GH 52795
97
+ pa = pytest.importorskip("pyarrow", "11.0.0")
98
+
99
+ arr = ["Mon", "Tue"]
100
+ table = pa.table({"weekday": pa.array(arr, "large_string")})
101
+ exchange_df = table.__dataframe__()
102
+ result = from_dataframe(exchange_df)
103
+ expected = pd.DataFrame({"weekday": ["Mon", "Tue"]})
104
+ tm.assert_frame_equal(result, expected)
105
+
106
+ # check round-trip
107
+ assert pa.Table.equals(pa.interchange.from_dataframe(result), table)
108
+
109
+
110
+ @pytest.mark.parametrize(
111
+ ("offset", "length", "expected_values"),
112
+ [
113
+ (0, None, [3.3, float("nan"), 2.1]),
114
+ (1, None, [float("nan"), 2.1]),
115
+ (2, None, [2.1]),
116
+ (0, 2, [3.3, float("nan")]),
117
+ (0, 1, [3.3]),
118
+ (1, 1, [float("nan")]),
119
+ ],
120
+ )
121
+ def test_bitmasks_pyarrow(offset, length, expected_values):
122
+ # GH 52795
123
+ pa = pytest.importorskip("pyarrow", "11.0.0")
124
+
125
+ arr = [3.3, None, 2.1]
126
+ table = pa.table({"arr": arr}).slice(offset, length)
127
+ exchange_df = table.__dataframe__()
128
+ result = from_dataframe(exchange_df)
129
+ expected = pd.DataFrame({"arr": expected_values})
130
+ tm.assert_frame_equal(result, expected)
131
+
132
+ # check round-trip
133
+ assert pa.Table.equals(pa.interchange.from_dataframe(result), table)
134
+
135
+
136
+ @pytest.mark.parametrize(
137
+ "data",
138
+ [
139
+ lambda: np.random.default_rng(2).integers(-100, 100),
140
+ lambda: np.random.default_rng(2).integers(1, 100),
141
+ lambda: np.random.default_rng(2).random(),
142
+ lambda: np.random.default_rng(2).choice([True, False]),
143
+ lambda: datetime(
144
+ year=np.random.default_rng(2).integers(1900, 2100),
145
+ month=np.random.default_rng(2).integers(1, 12),
146
+ day=np.random.default_rng(2).integers(1, 20),
147
+ ),
148
+ ],
149
+ )
150
+ def test_dataframe(data):
151
+ NCOLS, NROWS = 10, 20
152
+ data = {
153
+ f"col{int((i - NCOLS / 2) % NCOLS + 1)}": [data() for _ in range(NROWS)]
154
+ for i in range(NCOLS)
155
+ }
156
+ df = pd.DataFrame(data)
157
+
158
+ df2 = df.__dataframe__()
159
+
160
+ assert df2.num_columns() == NCOLS
161
+ assert df2.num_rows() == NROWS
162
+
163
+ assert list(df2.column_names()) == list(data.keys())
164
+
165
+ indices = (0, 2)
166
+ names = tuple(list(data.keys())[idx] for idx in indices)
167
+
168
+ result = from_dataframe(df2.select_columns(indices))
169
+ expected = from_dataframe(df2.select_columns_by_name(names))
170
+ tm.assert_frame_equal(result, expected)
171
+
172
+ assert isinstance(result.attrs["_INTERCHANGE_PROTOCOL_BUFFERS"], list)
173
+ assert isinstance(expected.attrs["_INTERCHANGE_PROTOCOL_BUFFERS"], list)
174
+
175
+
176
+ def test_missing_from_masked():
177
+ df = pd.DataFrame(
178
+ {
179
+ "x": np.array([1.0, 2.0, 3.0, 4.0, 0.0]),
180
+ "y": np.array([1.5, 2.5, 3.5, 4.5, 0]),
181
+ "z": np.array([1.0, 0.0, 1.0, 1.0, 1.0]),
182
+ }
183
+ )
184
+
185
+ rng = np.random.default_rng(2)
186
+ dict_null = {col: rng.integers(low=0, high=len(df)) for col in df.columns}
187
+ for col, num_nulls in dict_null.items():
188
+ null_idx = df.index[
189
+ rng.choice(np.arange(len(df)), size=num_nulls, replace=False)
190
+ ]
191
+ df.loc[null_idx, col] = None
192
+
193
+ df2 = df.__dataframe__()
194
+
195
+ assert df2.get_column_by_name("x").null_count == dict_null["x"]
196
+ assert df2.get_column_by_name("y").null_count == dict_null["y"]
197
+ assert df2.get_column_by_name("z").null_count == dict_null["z"]
198
+
199
+
200
+ @pytest.mark.parametrize(
201
+ "data",
202
+ [
203
+ {"x": [1.5, 2.5, 3.5], "y": [9.2, 10.5, 11.8]},
204
+ {"x": [1, 2, 0], "y": [9.2, 10.5, 11.8]},
205
+ {
206
+ "x": np.array([True, True, False]),
207
+ "y": np.array([1, 2, 0]),
208
+ "z": np.array([9.2, 10.5, 11.8]),
209
+ },
210
+ ],
211
+ )
212
+ def test_mixed_data(data):
213
+ df = pd.DataFrame(data)
214
+ df2 = df.__dataframe__()
215
+
216
+ for col_name in df.columns:
217
+ assert df2.get_column_by_name(col_name).null_count == 0
218
+
219
+
220
+ def test_mixed_missing():
221
+ df = pd.DataFrame(
222
+ {
223
+ "x": np.array([True, None, False, None, True]),
224
+ "y": np.array([None, 2, None, 1, 2]),
225
+ "z": np.array([9.2, 10.5, None, 11.8, None]),
226
+ }
227
+ )
228
+
229
+ df2 = df.__dataframe__()
230
+
231
+ for col_name in df.columns:
232
+ assert df2.get_column_by_name(col_name).null_count == 2
233
+
234
+
235
+ def test_string(string_data):
236
+ test_str_data = string_data["separator data"] + [""]
237
+ df = pd.DataFrame({"A": test_str_data})
238
+ col = df.__dataframe__().get_column_by_name("A")
239
+
240
+ assert col.size() == 6
241
+ assert col.null_count == 1
242
+ assert col.dtype[0] == DtypeKind.STRING
243
+ assert col.describe_null == (ColumnNullType.USE_BYTEMASK, 0)
244
+
245
+ df_sliced = df[1:]
246
+ col = df_sliced.__dataframe__().get_column_by_name("A")
247
+ assert col.size() == 5
248
+ assert col.null_count == 1
249
+ assert col.dtype[0] == DtypeKind.STRING
250
+ assert col.describe_null == (ColumnNullType.USE_BYTEMASK, 0)
251
+
252
+
253
+ def test_nonstring_object():
254
+ df = pd.DataFrame({"A": ["a", 10, 1.0, ()]})
255
+ col = df.__dataframe__().get_column_by_name("A")
256
+ with pytest.raises(NotImplementedError, match="not supported yet"):
257
+ col.dtype
258
+
259
+
260
+ def test_datetime():
261
+ df = pd.DataFrame({"A": [pd.Timestamp("2022-01-01"), pd.NaT]})
262
+ col = df.__dataframe__().get_column_by_name("A")
263
+
264
+ assert col.size() == 2
265
+ assert col.null_count == 1
266
+ assert col.dtype[0] == DtypeKind.DATETIME
267
+ assert col.describe_null == (ColumnNullType.USE_SENTINEL, iNaT)
268
+
269
+ tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))
270
+
271
+
272
+ @pytest.mark.skipif(np_version_lt1p23, reason="Numpy > 1.23 required")
273
+ def test_categorical_to_numpy_dlpack():
274
+ # https://github.com/pandas-dev/pandas/issues/48393
275
+ df = pd.DataFrame({"A": pd.Categorical(["a", "b", "a"])})
276
+ col = df.__dataframe__().get_column_by_name("A")
277
+ result = np.from_dlpack(col.get_buffers()["data"][0])
278
+ expected = np.array([0, 1, 0], dtype="int8")
279
+ tm.assert_numpy_array_equal(result, expected)
280
+
281
+
282
+ @pytest.mark.parametrize("data", [{}, {"a": []}])
283
+ def test_empty_pyarrow(data):
284
+ # GH 53155
285
+ pytest.importorskip("pyarrow", "11.0.0")
286
+ from pyarrow.interchange import from_dataframe as pa_from_dataframe
287
+
288
+ expected = pd.DataFrame(data)
289
+ arrow_df = pa_from_dataframe(expected)
290
+ result = from_dataframe(arrow_df)
291
+ tm.assert_frame_equal(result, expected)
292
+
293
+
294
+ def test_multi_chunk_pyarrow() -> None:
295
+ pa = pytest.importorskip("pyarrow", "11.0.0")
296
+ n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
297
+ names = ["n_legs"]
298
+ table = pa.table([n_legs], names=names)
299
+ with pytest.raises(
300
+ RuntimeError,
301
+ match="To join chunks a copy is required which is "
302
+ "forbidden by allow_copy=False",
303
+ ):
304
+ pd.api.interchange.from_dataframe(table, allow_copy=False)
305
+
306
+
307
+ def test_multi_chunk_column() -> None:
308
+ pytest.importorskip("pyarrow", "11.0.0")
309
+ ser = pd.Series([1, 2, None], dtype="Int64[pyarrow]")
310
+ df = pd.concat([ser, ser], ignore_index=True).to_frame("a")
311
+ df_orig = df.copy()
312
+ with pytest.raises(
313
+ RuntimeError, match="Found multi-chunk pyarrow array, but `allow_copy` is False"
314
+ ):
315
+ pd.api.interchange.from_dataframe(df.__dataframe__(allow_copy=False))
316
+ result = pd.api.interchange.from_dataframe(df.__dataframe__(allow_copy=True))
317
+ # Interchange protocol defaults to creating numpy-backed columns, so currently this
318
+ # is 'float64'.
319
+ expected = pd.DataFrame({"a": [1.0, 2.0, None, 1.0, 2.0, None]}, dtype="float64")
320
+ tm.assert_frame_equal(result, expected)
321
+
322
+ # Check that the rechunking we did didn't modify the original DataFrame.
323
+ tm.assert_frame_equal(df, df_orig)
324
+ assert len(df["a"].array._pa_array.chunks) == 2
325
+ assert len(df_orig["a"].array._pa_array.chunks) == 2
326
+
327
+
328
+ def test_timestamp_ns_pyarrow():
329
+ # GH 56712
330
+ pytest.importorskip("pyarrow", "11.0.0")
331
+ timestamp_args = {
332
+ "year": 2000,
333
+ "month": 1,
334
+ "day": 1,
335
+ "hour": 1,
336
+ "minute": 1,
337
+ "second": 1,
338
+ }
339
+ df = pd.Series(
340
+ [datetime(**timestamp_args)],
341
+ dtype="timestamp[ns][pyarrow]",
342
+ name="col0",
343
+ ).to_frame()
344
+
345
+ dfi = df.__dataframe__()
346
+ result = pd.api.interchange.from_dataframe(dfi)["col0"].item()
347
+
348
+ expected = pd.Timestamp(**timestamp_args)
349
+ assert result == expected
350
+
351
+
352
+ @pytest.mark.parametrize("tz", ["UTC", "US/Pacific"])
353
+ @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
354
+ def test_datetimetzdtype(tz, unit):
355
+ # GH 54239
356
+ tz_data = (
357
+ pd.date_range("2018-01-01", periods=5, freq="D").tz_localize(tz).as_unit(unit)
358
+ )
359
+ df = pd.DataFrame({"ts_tz": tz_data})
360
+ tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))
361
+
362
+
363
+ def test_interchange_from_non_pandas_tz_aware(request):
364
+ # GH 54239, 54287
365
+ pa = pytest.importorskip("pyarrow", "11.0.0")
366
+ import pyarrow.compute as pc
367
+
368
+ if is_platform_windows() and is_ci_environment():
369
+ mark = pytest.mark.xfail(
370
+ raises=pa.ArrowInvalid,
371
+ reason=(
372
+ "TODO: Set ARROW_TIMEZONE_DATABASE environment variable "
373
+ "on CI to path to the tzdata for pyarrow."
374
+ ),
375
+ )
376
+ request.applymarker(mark)
377
+
378
+ arr = pa.array([datetime(2020, 1, 1), None, datetime(2020, 1, 2)])
379
+ arr = pc.assume_timezone(arr, "Asia/Kathmandu")
380
+ table = pa.table({"arr": arr})
381
+ exchange_df = table.__dataframe__()
382
+ result = from_dataframe(exchange_df)
383
+
384
+ expected = pd.DataFrame(
385
+ ["2020-01-01 00:00:00+05:45", "NaT", "2020-01-02 00:00:00+05:45"],
386
+ columns=["arr"],
387
+ dtype="datetime64[us, Asia/Kathmandu]",
388
+ )
389
+ tm.assert_frame_equal(expected, result)
390
+
391
+
392
+ def test_interchange_from_corrected_buffer_dtypes(monkeypatch) -> None:
393
+ # https://github.com/pandas-dev/pandas/issues/54781
394
+ df = pd.DataFrame({"a": ["foo", "bar"]}).__dataframe__()
395
+ interchange = df.__dataframe__()
396
+ column = interchange.get_column_by_name("a")
397
+ buffers = column.get_buffers()
398
+ buffers_data = buffers["data"]
399
+ buffer_dtype = buffers_data[1]
400
+ buffer_dtype = (
401
+ DtypeKind.UINT,
402
+ 8,
403
+ ArrowCTypes.UINT8,
404
+ buffer_dtype[3],
405
+ )
406
+ buffers["data"] = (buffers_data[0], buffer_dtype)
407
+ column.get_buffers = lambda: buffers
408
+ interchange.get_column_by_name = lambda _: column
409
+ monkeypatch.setattr(df, "__dataframe__", lambda allow_copy: interchange)
410
+ pd.api.interchange.from_dataframe(df)
411
+
412
+
413
+ def test_empty_string_column():
414
+ # https://github.com/pandas-dev/pandas/issues/56703
415
+ df = pd.DataFrame({"a": []}, dtype=str)
416
+ df2 = df.__dataframe__()
417
+ result = pd.api.interchange.from_dataframe(df2)
418
+ tm.assert_frame_equal(df, result)
419
+
420
+
421
+ def test_large_string():
422
+ # GH#56702
423
+ pytest.importorskip("pyarrow")
424
+ df = pd.DataFrame({"a": ["x"]}, dtype="large_string[pyarrow]")
425
+ result = pd.api.interchange.from_dataframe(df.__dataframe__())
426
+ expected = pd.DataFrame({"a": ["x"]}, dtype="object")
427
+ tm.assert_frame_equal(result, expected)
428
+
429
+
430
+ def test_non_str_names():
431
+ # https://github.com/pandas-dev/pandas/issues/56701
432
+ df = pd.Series([1, 2, 3], name=0).to_frame()
433
+ names = df.__dataframe__().column_names()
434
+ assert names == ["0"]
435
+
436
+
437
+ def test_non_str_names_w_duplicates():
438
+ # https://github.com/pandas-dev/pandas/issues/56701
439
+ df = pd.DataFrame({"0": [1, 2, 3], 0: [4, 5, 6]})
440
+ dfi = df.__dataframe__()
441
+ with pytest.raises(
442
+ TypeError,
443
+ match=(
444
+ "Expected a Series, got a DataFrame. This likely happened because you "
445
+ "called __dataframe__ on a DataFrame which, after converting column "
446
+ r"names to string, resulted in duplicated names: Index\(\['0', '0'\], "
447
+ r"dtype='object'\). Please rename these columns before using the "
448
+ "interchange protocol."
449
+ ),
450
+ ):
451
+ pd.api.interchange.from_dataframe(dfi, allow_copy=False)
452
+
453
+
454
+ @pytest.mark.parametrize(
455
+ ("data", "dtype", "expected_dtype"),
456
+ [
457
+ ([1, 2, None], "Int64", "int64"),
458
+ ([1, 2, None], "Int64[pyarrow]", "int64"),
459
+ ([1, 2, None], "Int8", "int8"),
460
+ ([1, 2, None], "Int8[pyarrow]", "int8"),
461
+ (
462
+ [1, 2, None],
463
+ "UInt64",
464
+ "uint64",
465
+ ),
466
+ (
467
+ [1, 2, None],
468
+ "UInt64[pyarrow]",
469
+ "uint64",
470
+ ),
471
+ ([1.0, 2.25, None], "Float32", "float32"),
472
+ ([1.0, 2.25, None], "Float32[pyarrow]", "float32"),
473
+ ([True, False, None], "boolean", "bool"),
474
+ ([True, False, None], "boolean[pyarrow]", "bool"),
475
+ (["much ado", "about", None], "string[pyarrow_numpy]", "large_string"),
476
+ (["much ado", "about", None], "string[pyarrow]", "large_string"),
477
+ (
478
+ [datetime(2020, 1, 1), datetime(2020, 1, 2), None],
479
+ "timestamp[ns][pyarrow]",
480
+ "timestamp[ns]",
481
+ ),
482
+ (
483
+ [datetime(2020, 1, 1), datetime(2020, 1, 2), None],
484
+ "timestamp[us][pyarrow]",
485
+ "timestamp[us]",
486
+ ),
487
+ (
488
+ [
489
+ datetime(2020, 1, 1, tzinfo=timezone.utc),
490
+ datetime(2020, 1, 2, tzinfo=timezone.utc),
491
+ None,
492
+ ],
493
+ "timestamp[us, Asia/Kathmandu][pyarrow]",
494
+ "timestamp[us, tz=Asia/Kathmandu]",
495
+ ),
496
+ ],
497
+ )
498
+ def test_pandas_nullable_with_missing_values(
499
+ data: list, dtype: str, expected_dtype: str
500
+ ) -> None:
501
+ # https://github.com/pandas-dev/pandas/issues/57643
502
+ # https://github.com/pandas-dev/pandas/issues/57664
503
+ pa = pytest.importorskip("pyarrow", "11.0.0")
504
+ import pyarrow.interchange as pai
505
+
506
+ if expected_dtype == "timestamp[us, tz=Asia/Kathmandu]":
507
+ expected_dtype = pa.timestamp("us", "Asia/Kathmandu")
508
+
509
+ df = pd.DataFrame({"a": data}, dtype=dtype)
510
+ result = pai.from_dataframe(df.__dataframe__())["a"]
511
+ assert result.type == expected_dtype
512
+ assert result[0].as_py() == data[0]
513
+ assert result[1].as_py() == data[1]
514
+ assert result[2].as_py() is None
515
+
516
+
517
+ @pytest.mark.parametrize(
518
+ ("data", "dtype", "expected_dtype"),
519
+ [
520
+ ([1, 2, 3], "Int64", "int64"),
521
+ ([1, 2, 3], "Int64[pyarrow]", "int64"),
522
+ ([1, 2, 3], "Int8", "int8"),
523
+ ([1, 2, 3], "Int8[pyarrow]", "int8"),
524
+ (
525
+ [1, 2, 3],
526
+ "UInt64",
527
+ "uint64",
528
+ ),
529
+ (
530
+ [1, 2, 3],
531
+ "UInt64[pyarrow]",
532
+ "uint64",
533
+ ),
534
+ ([1.0, 2.25, 5.0], "Float32", "float32"),
535
+ ([1.0, 2.25, 5.0], "Float32[pyarrow]", "float32"),
536
+ ([True, False, False], "boolean", "bool"),
537
+ ([True, False, False], "boolean[pyarrow]", "bool"),
538
+ (["much ado", "about", "nothing"], "string[pyarrow_numpy]", "large_string"),
539
+ (["much ado", "about", "nothing"], "string[pyarrow]", "large_string"),
540
+ (
541
+ [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3)],
542
+ "timestamp[ns][pyarrow]",
543
+ "timestamp[ns]",
544
+ ),
545
+ (
546
+ [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3)],
547
+ "timestamp[us][pyarrow]",
548
+ "timestamp[us]",
549
+ ),
550
+ (
551
+ [
552
+ datetime(2020, 1, 1, tzinfo=timezone.utc),
553
+ datetime(2020, 1, 2, tzinfo=timezone.utc),
554
+ datetime(2020, 1, 3, tzinfo=timezone.utc),
555
+ ],
556
+ "timestamp[us, Asia/Kathmandu][pyarrow]",
557
+ "timestamp[us, tz=Asia/Kathmandu]",
558
+ ),
559
+ ],
560
+ )
561
+ def test_pandas_nullable_without_missing_values(
562
+ data: list, dtype: str, expected_dtype: str
563
+ ) -> None:
564
+ # https://github.com/pandas-dev/pandas/issues/57643
565
+ pa = pytest.importorskip("pyarrow", "11.0.0")
566
+ import pyarrow.interchange as pai
567
+
568
+ if expected_dtype == "timestamp[us, tz=Asia/Kathmandu]":
569
+ expected_dtype = pa.timestamp("us", "Asia/Kathmandu")
570
+
571
+ df = pd.DataFrame({"a": data}, dtype=dtype)
572
+ result = pai.from_dataframe(df.__dataframe__())["a"]
573
+ assert result.type == expected_dtype
574
+ assert result[0].as_py() == data[0]
575
+ assert result[1].as_py() == data[1]
576
+ assert result[2].as_py() == data[2]
577
+
578
+
579
+ def test_string_validity_buffer() -> None:
580
+ # https://github.com/pandas-dev/pandas/issues/57761
581
+ pytest.importorskip("pyarrow", "11.0.0")
582
+ df = pd.DataFrame({"a": ["x"]}, dtype="large_string[pyarrow]")
583
+ result = df.__dataframe__().get_column_by_name("a").get_buffers()["validity"]
584
+ assert result is None
585
+
586
+
587
+ def test_string_validity_buffer_no_missing() -> None:
588
+ # https://github.com/pandas-dev/pandas/issues/57762
589
+ pytest.importorskip("pyarrow", "11.0.0")
590
+ df = pd.DataFrame({"a": ["x", None]}, dtype="large_string[pyarrow]")
591
+ validity = df.__dataframe__().get_column_by_name("a").get_buffers()["validity"]
592
+ assert validity is not None
593
+ result = validity[1]
594
+ expected = (DtypeKind.BOOL, 1, ArrowCTypes.BOOL, "=")
595
+ assert result == expected
596
+
597
+
598
+ def test_empty_dataframe():
599
+ # https://github.com/pandas-dev/pandas/issues/56700
600
+ df = pd.DataFrame({"a": []}, dtype="int8")
601
+ dfi = df.__dataframe__()
602
+ result = pd.api.interchange.from_dataframe(dfi, allow_copy=False)
603
+ expected = pd.DataFrame({"a": []}, dtype="int8")
604
+ tm.assert_frame_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/interchange/test_spec_conformance.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A verbatim copy (vendored) of the spec tests.
3
+ Taken from https://github.com/data-apis/dataframe-api
4
+ """
5
+ import ctypes
6
+ import math
7
+
8
+ import pytest
9
+
10
+ import pandas as pd
11
+
12
+
13
+ @pytest.fixture
14
+ def df_from_dict():
15
+ def maker(dct, is_categorical=False):
16
+ df = pd.DataFrame(dct)
17
+ return df.astype("category") if is_categorical else df
18
+
19
+ return maker
20
+
21
+
22
+ @pytest.mark.parametrize(
23
+ "test_data",
24
+ [
25
+ {"a": ["foo", "bar"], "b": ["baz", "qux"]},
26
+ {"a": [1.5, 2.5, 3.5], "b": [9.2, 10.5, 11.8]},
27
+ {"A": [1, 2, 3, 4], "B": [1, 2, 3, 4]},
28
+ ],
29
+ ids=["str_data", "float_data", "int_data"],
30
+ )
31
+ def test_only_one_dtype(test_data, df_from_dict):
32
+ columns = list(test_data.keys())
33
+ df = df_from_dict(test_data)
34
+ dfX = df.__dataframe__()
35
+
36
+ column_size = len(test_data[columns[0]])
37
+ for column in columns:
38
+ null_count = dfX.get_column_by_name(column).null_count
39
+ assert null_count == 0
40
+ assert isinstance(null_count, int)
41
+ assert dfX.get_column_by_name(column).size() == column_size
42
+ assert dfX.get_column_by_name(column).offset == 0
43
+
44
+
45
+ def test_mixed_dtypes(df_from_dict):
46
+ df = df_from_dict(
47
+ {
48
+ "a": [1, 2, 3], # dtype kind INT = 0
49
+ "b": [3, 4, 5], # dtype kind INT = 0
50
+ "c": [1.5, 2.5, 3.5], # dtype kind FLOAT = 2
51
+ "d": [9, 10, 11], # dtype kind INT = 0
52
+ "e": [True, False, True], # dtype kind BOOLEAN = 20
53
+ "f": ["a", "", "c"], # dtype kind STRING = 21
54
+ }
55
+ )
56
+ dfX = df.__dataframe__()
57
+ # for meanings of dtype[0] see the spec; we cannot import the spec here as this
58
+ # file is expected to be vendored *anywhere*;
59
+ # values for dtype[0] are explained above
60
+ columns = {"a": 0, "b": 0, "c": 2, "d": 0, "e": 20, "f": 21}
61
+
62
+ for column, kind in columns.items():
63
+ colX = dfX.get_column_by_name(column)
64
+ assert colX.null_count == 0
65
+ assert isinstance(colX.null_count, int)
66
+ assert colX.size() == 3
67
+ assert colX.offset == 0
68
+
69
+ assert colX.dtype[0] == kind
70
+
71
+ assert dfX.get_column_by_name("c").dtype[1] == 64
72
+
73
+
74
+ def test_na_float(df_from_dict):
75
+ df = df_from_dict({"a": [1.0, math.nan, 2.0]})
76
+ dfX = df.__dataframe__()
77
+ colX = dfX.get_column_by_name("a")
78
+ assert colX.null_count == 1
79
+ assert isinstance(colX.null_count, int)
80
+
81
+
82
+ def test_noncategorical(df_from_dict):
83
+ df = df_from_dict({"a": [1, 2, 3]})
84
+ dfX = df.__dataframe__()
85
+ colX = dfX.get_column_by_name("a")
86
+ with pytest.raises(TypeError, match=".*categorical.*"):
87
+ colX.describe_categorical
88
+
89
+
90
+ def test_categorical(df_from_dict):
91
+ df = df_from_dict(
92
+ {"weekday": ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"]},
93
+ is_categorical=True,
94
+ )
95
+
96
+ colX = df.__dataframe__().get_column_by_name("weekday")
97
+ categorical = colX.describe_categorical
98
+ assert isinstance(categorical["is_ordered"], bool)
99
+ assert isinstance(categorical["is_dictionary"], bool)
100
+
101
+
102
+ def test_dataframe(df_from_dict):
103
+ df = df_from_dict(
104
+ {"x": [True, True, False], "y": [1, 2, 0], "z": [9.2, 10.5, 11.8]}
105
+ )
106
+ dfX = df.__dataframe__()
107
+
108
+ assert dfX.num_columns() == 3
109
+ assert dfX.num_rows() == 3
110
+ assert dfX.num_chunks() == 1
111
+ assert list(dfX.column_names()) == ["x", "y", "z"]
112
+ assert list(dfX.select_columns((0, 2)).column_names()) == list(
113
+ dfX.select_columns_by_name(("x", "z")).column_names()
114
+ )
115
+
116
+
117
+ @pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])
118
+ def test_df_get_chunks(size, n_chunks, df_from_dict):
119
+ df = df_from_dict({"x": list(range(size))})
120
+ dfX = df.__dataframe__()
121
+ chunks = list(dfX.get_chunks(n_chunks))
122
+ assert len(chunks) == n_chunks
123
+ assert sum(chunk.num_rows() for chunk in chunks) == size
124
+
125
+
126
+ @pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])
127
+ def test_column_get_chunks(size, n_chunks, df_from_dict):
128
+ df = df_from_dict({"x": list(range(size))})
129
+ dfX = df.__dataframe__()
130
+ chunks = list(dfX.get_column(0).get_chunks(n_chunks))
131
+ assert len(chunks) == n_chunks
132
+ assert sum(chunk.size() for chunk in chunks) == size
133
+
134
+
135
+ def test_get_columns(df_from_dict):
136
+ df = df_from_dict({"a": [0, 1], "b": [2.5, 3.5]})
137
+ dfX = df.__dataframe__()
138
+ for colX in dfX.get_columns():
139
+ assert colX.size() == 2
140
+ assert colX.num_chunks() == 1
141
+ # for meanings of dtype[0] see the spec; we cannot import the spec here as this
142
+ # file is expected to be vendored *anywhere*
143
+ assert dfX.get_column(0).dtype[0] == 0 # INT
144
+ assert dfX.get_column(1).dtype[0] == 2 # FLOAT
145
+
146
+
147
+ def test_buffer(df_from_dict):
148
+ arr = [0, 1, -1]
149
+ df = df_from_dict({"a": arr})
150
+ dfX = df.__dataframe__()
151
+ colX = dfX.get_column(0)
152
+ bufX = colX.get_buffers()
153
+
154
+ dataBuf, dataDtype = bufX["data"]
155
+
156
+ assert dataBuf.bufsize > 0
157
+ assert dataBuf.ptr != 0
158
+ device, _ = dataBuf.__dlpack_device__()
159
+
160
+ # for meanings of dtype[0] see the spec; we cannot import the spec here as this
161
+ # file is expected to be vendored *anywhere*
162
+ assert dataDtype[0] == 0 # INT
163
+
164
+ if device == 1: # CPU-only as we're going to directly read memory here
165
+ bitwidth = dataDtype[1]
166
+ ctype = {
167
+ 8: ctypes.c_int8,
168
+ 16: ctypes.c_int16,
169
+ 32: ctypes.c_int32,
170
+ 64: ctypes.c_int64,
171
+ }[bitwidth]
172
+
173
+ for idx, truth in enumerate(arr):
174
+ val = ctype.from_address(dataBuf.ptr + idx * (bitwidth // 8)).value
175
+ assert val == truth, f"Buffer at index {idx} mismatch"
venv/lib/python3.10/site-packages/pandas/tests/interchange/test_utils.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas.core.interchange.utils import dtype_to_arrow_c_fmt
6
+
7
+ # TODO: use ArrowSchema to get reference C-string.
8
+ # At the time, there is no way to access ArrowSchema holding a type format string
9
+ # from python. The only way to access it is to export the structure to a C-pointer,
10
+ # see DataType._export_to_c() method defined in
11
+ # https://github.com/apache/arrow/blob/master/python/pyarrow/types.pxi
12
+
13
+
14
+ @pytest.mark.parametrize(
15
+ "pandas_dtype, c_string",
16
+ [
17
+ (np.dtype("bool"), "b"),
18
+ (np.dtype("int8"), "c"),
19
+ (np.dtype("uint8"), "C"),
20
+ (np.dtype("int16"), "s"),
21
+ (np.dtype("uint16"), "S"),
22
+ (np.dtype("int32"), "i"),
23
+ (np.dtype("uint32"), "I"),
24
+ (np.dtype("int64"), "l"),
25
+ (np.dtype("uint64"), "L"),
26
+ (np.dtype("float16"), "e"),
27
+ (np.dtype("float32"), "f"),
28
+ (np.dtype("float64"), "g"),
29
+ (pd.Series(["a"]).dtype, "u"),
30
+ (
31
+ pd.Series([0]).astype("datetime64[ns]").dtype,
32
+ "tsn:",
33
+ ),
34
+ (pd.CategoricalDtype(["a"]), "l"),
35
+ (np.dtype("O"), "u"),
36
+ ],
37
+ )
38
+ def test_dtype_to_arrow_c_fmt(pandas_dtype, c_string): # PR01
39
+ """Test ``dtype_to_arrow_c_fmt`` utility function."""
40
+ assert dtype_to_arrow_c_fmt(pandas_dtype) == c_string
41
+
42
+
43
+ @pytest.mark.parametrize(
44
+ "pa_dtype, args_kwargs, c_string",
45
+ [
46
+ ["null", {}, "n"],
47
+ ["bool_", {}, "b"],
48
+ ["uint8", {}, "C"],
49
+ ["uint16", {}, "S"],
50
+ ["uint32", {}, "I"],
51
+ ["uint64", {}, "L"],
52
+ ["int8", {}, "c"],
53
+ ["int16", {}, "S"],
54
+ ["int32", {}, "i"],
55
+ ["int64", {}, "l"],
56
+ ["float16", {}, "e"],
57
+ ["float32", {}, "f"],
58
+ ["float64", {}, "g"],
59
+ ["string", {}, "u"],
60
+ ["binary", {}, "z"],
61
+ ["time32", ("s",), "tts"],
62
+ ["time32", ("ms",), "ttm"],
63
+ ["time64", ("us",), "ttu"],
64
+ ["time64", ("ns",), "ttn"],
65
+ ["date32", {}, "tdD"],
66
+ ["date64", {}, "tdm"],
67
+ ["timestamp", {"unit": "s"}, "tss:"],
68
+ ["timestamp", {"unit": "ms"}, "tsm:"],
69
+ ["timestamp", {"unit": "us"}, "tsu:"],
70
+ ["timestamp", {"unit": "ns"}, "tsn:"],
71
+ ["timestamp", {"unit": "ns", "tz": "UTC"}, "tsn:UTC"],
72
+ ["duration", ("s",), "tDs"],
73
+ ["duration", ("ms",), "tDm"],
74
+ ["duration", ("us",), "tDu"],
75
+ ["duration", ("ns",), "tDn"],
76
+ ["decimal128", {"precision": 4, "scale": 2}, "d:4,2"],
77
+ ],
78
+ )
79
+ def test_dtype_to_arrow_c_fmt_arrowdtype(pa_dtype, args_kwargs, c_string):
80
+ # GH 52323
81
+ pa = pytest.importorskip("pyarrow")
82
+ if not args_kwargs:
83
+ pa_type = getattr(pa, pa_dtype)()
84
+ elif isinstance(args_kwargs, tuple):
85
+ pa_type = getattr(pa, pa_dtype)(*args_kwargs)
86
+ else:
87
+ pa_type = getattr(pa, pa_dtype)(**args_kwargs)
88
+ arrow_type = pd.ArrowDtype(pa_type)
89
+ assert dtype_to_arrow_c_fmt(arrow_type) == c_string
venv/lib/python3.10/site-packages/pandas/tests/reductions/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Tests for reductions where we want to test for matching behavior across
3
+ Array, Index, Series, and DataFrame methods.
4
+ """
venv/lib/python3.10/site-packages/pandas/tests/reductions/test_stat_reductions.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for statistical reductions of 2nd moment or higher: var, skew, kurt, ...
3
+ """
4
+ import inspect
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ import pandas as pd
10
+ from pandas import (
11
+ DataFrame,
12
+ Series,
13
+ date_range,
14
+ )
15
+ import pandas._testing as tm
16
+
17
+
18
+ class TestDatetimeLikeStatReductions:
19
+ @pytest.mark.parametrize("box", [Series, pd.Index, pd.array])
20
+ def test_dt64_mean(self, tz_naive_fixture, box):
21
+ tz = tz_naive_fixture
22
+
23
+ dti = date_range("2001-01-01", periods=11, tz=tz)
24
+ # shuffle so that we are not just working with monotone-increasing
25
+ dti = dti.take([4, 1, 3, 10, 9, 7, 8, 5, 0, 2, 6])
26
+ dtarr = dti._data
27
+
28
+ obj = box(dtarr)
29
+ assert obj.mean() == pd.Timestamp("2001-01-06", tz=tz)
30
+ assert obj.mean(skipna=False) == pd.Timestamp("2001-01-06", tz=tz)
31
+
32
+ # dtarr[-2] will be the first date 2001-01-1
33
+ dtarr[-2] = pd.NaT
34
+
35
+ obj = box(dtarr)
36
+ assert obj.mean() == pd.Timestamp("2001-01-06 07:12:00", tz=tz)
37
+ assert obj.mean(skipna=False) is pd.NaT
38
+
39
+ @pytest.mark.parametrize("box", [Series, pd.Index, pd.array])
40
+ @pytest.mark.parametrize("freq", ["s", "h", "D", "W", "B"])
41
+ def test_period_mean(self, box, freq):
42
+ # GH#24757
43
+ dti = date_range("2001-01-01", periods=11)
44
+ # shuffle so that we are not just working with monotone-increasing
45
+ dti = dti.take([4, 1, 3, 10, 9, 7, 8, 5, 0, 2, 6])
46
+
47
+ warn = FutureWarning if freq == "B" else None
48
+ msg = r"PeriodDtype\[B\] is deprecated"
49
+ with tm.assert_produces_warning(warn, match=msg):
50
+ parr = dti._data.to_period(freq)
51
+ obj = box(parr)
52
+ with pytest.raises(TypeError, match="ambiguous"):
53
+ obj.mean()
54
+ with pytest.raises(TypeError, match="ambiguous"):
55
+ obj.mean(skipna=True)
56
+
57
+ # parr[-2] will be the first date 2001-01-1
58
+ parr[-2] = pd.NaT
59
+
60
+ with pytest.raises(TypeError, match="ambiguous"):
61
+ obj.mean()
62
+ with pytest.raises(TypeError, match="ambiguous"):
63
+ obj.mean(skipna=True)
64
+
65
+ @pytest.mark.parametrize("box", [Series, pd.Index, pd.array])
66
+ def test_td64_mean(self, box):
67
+ m8values = np.array([0, 3, -2, -7, 1, 2, -1, 3, 5, -2, 4], "m8[D]")
68
+ tdi = pd.TimedeltaIndex(m8values).as_unit("ns")
69
+
70
+ tdarr = tdi._data
71
+ obj = box(tdarr, copy=False)
72
+
73
+ result = obj.mean()
74
+ expected = np.array(tdarr).mean()
75
+ assert result == expected
76
+
77
+ tdarr[0] = pd.NaT
78
+ assert obj.mean(skipna=False) is pd.NaT
79
+
80
+ result2 = obj.mean(skipna=True)
81
+ assert result2 == tdi[1:].mean()
82
+
83
+ # exact equality fails by 1 nanosecond
84
+ assert result2.round("us") == (result * 11.0 / 10).round("us")
85
+
86
+
87
+ class TestSeriesStatReductions:
88
+ # Note: the name TestSeriesStatReductions indicates these tests
89
+ # were moved from a series-specific test file, _not_ that these tests are
90
+ # intended long-term to be series-specific
91
+
92
+ def _check_stat_op(
93
+ self, name, alternate, string_series_, check_objects=False, check_allna=False
94
+ ):
95
+ with pd.option_context("use_bottleneck", False):
96
+ f = getattr(Series, name)
97
+
98
+ # add some NaNs
99
+ string_series_[5:15] = np.nan
100
+
101
+ # mean, idxmax, idxmin, min, and max are valid for dates
102
+ if name not in ["max", "min", "mean", "median", "std"]:
103
+ ds = Series(date_range("1/1/2001", periods=10))
104
+ msg = f"does not support reduction '{name}'"
105
+ with pytest.raises(TypeError, match=msg):
106
+ f(ds)
107
+
108
+ # skipna or no
109
+ assert pd.notna(f(string_series_))
110
+ assert pd.isna(f(string_series_, skipna=False))
111
+
112
+ # check the result is correct
113
+ nona = string_series_.dropna()
114
+ tm.assert_almost_equal(f(nona), alternate(nona.values))
115
+ tm.assert_almost_equal(f(string_series_), alternate(nona.values))
116
+
117
+ allna = string_series_ * np.nan
118
+
119
+ if check_allna:
120
+ assert np.isnan(f(allna))
121
+
122
+ # dtype=object with None, it works!
123
+ s = Series([1, 2, 3, None, 5])
124
+ f(s)
125
+
126
+ # GH#2888
127
+ items = [0]
128
+ items.extend(range(2**40, 2**40 + 1000))
129
+ s = Series(items, dtype="int64")
130
+ tm.assert_almost_equal(float(f(s)), float(alternate(s.values)))
131
+
132
+ # check date range
133
+ if check_objects:
134
+ s = Series(pd.bdate_range("1/1/2000", periods=10))
135
+ res = f(s)
136
+ exp = alternate(s)
137
+ assert res == exp
138
+
139
+ # check on string data
140
+ if name not in ["sum", "min", "max"]:
141
+ with pytest.raises(TypeError, match=None):
142
+ f(Series(list("abc")))
143
+
144
+ # Invalid axis.
145
+ msg = "No axis named 1 for object type Series"
146
+ with pytest.raises(ValueError, match=msg):
147
+ f(string_series_, axis=1)
148
+
149
+ if "numeric_only" in inspect.getfullargspec(f).args:
150
+ # only the index is string; dtype is float
151
+ f(string_series_, numeric_only=True)
152
+
153
+ def test_sum(self):
154
+ string_series = Series(range(20), dtype=np.float64, name="series")
155
+ self._check_stat_op("sum", np.sum, string_series, check_allna=False)
156
+
157
+ def test_mean(self):
158
+ string_series = Series(range(20), dtype=np.float64, name="series")
159
+ self._check_stat_op("mean", np.mean, string_series)
160
+
161
+ def test_median(self):
162
+ string_series = Series(range(20), dtype=np.float64, name="series")
163
+ self._check_stat_op("median", np.median, string_series)
164
+
165
+ # test with integers, test failure
166
+ int_ts = Series(np.ones(10, dtype=int), index=range(10))
167
+ tm.assert_almost_equal(np.median(int_ts), int_ts.median())
168
+
169
+ def test_prod(self):
170
+ string_series = Series(range(20), dtype=np.float64, name="series")
171
+ self._check_stat_op("prod", np.prod, string_series)
172
+
173
+ def test_min(self):
174
+ string_series = Series(range(20), dtype=np.float64, name="series")
175
+ self._check_stat_op("min", np.min, string_series, check_objects=True)
176
+
177
+ def test_max(self):
178
+ string_series = Series(range(20), dtype=np.float64, name="series")
179
+ self._check_stat_op("max", np.max, string_series, check_objects=True)
180
+
181
+ def test_var_std(self):
182
+ string_series = Series(range(20), dtype=np.float64, name="series")
183
+ datetime_series = Series(
184
+ np.arange(10, dtype=np.float64),
185
+ index=date_range("2020-01-01", periods=10),
186
+ name="ts",
187
+ )
188
+
189
+ alt = lambda x: np.std(x, ddof=1)
190
+ self._check_stat_op("std", alt, string_series)
191
+
192
+ alt = lambda x: np.var(x, ddof=1)
193
+ self._check_stat_op("var", alt, string_series)
194
+
195
+ result = datetime_series.std(ddof=4)
196
+ expected = np.std(datetime_series.values, ddof=4)
197
+ tm.assert_almost_equal(result, expected)
198
+
199
+ result = datetime_series.var(ddof=4)
200
+ expected = np.var(datetime_series.values, ddof=4)
201
+ tm.assert_almost_equal(result, expected)
202
+
203
+ # 1 - element series with ddof=1
204
+ s = datetime_series.iloc[[0]]
205
+ result = s.var(ddof=1)
206
+ assert pd.isna(result)
207
+
208
+ result = s.std(ddof=1)
209
+ assert pd.isna(result)
210
+
211
+ def test_sem(self):
212
+ string_series = Series(range(20), dtype=np.float64, name="series")
213
+ datetime_series = Series(
214
+ np.arange(10, dtype=np.float64),
215
+ index=date_range("2020-01-01", periods=10),
216
+ name="ts",
217
+ )
218
+
219
+ alt = lambda x: np.std(x, ddof=1) / np.sqrt(len(x))
220
+ self._check_stat_op("sem", alt, string_series)
221
+
222
+ result = datetime_series.sem(ddof=4)
223
+ expected = np.std(datetime_series.values, ddof=4) / np.sqrt(
224
+ len(datetime_series.values)
225
+ )
226
+ tm.assert_almost_equal(result, expected)
227
+
228
+ # 1 - element series with ddof=1
229
+ s = datetime_series.iloc[[0]]
230
+ result = s.sem(ddof=1)
231
+ assert pd.isna(result)
232
+
233
+ def test_skew(self):
234
+ sp_stats = pytest.importorskip("scipy.stats")
235
+
236
+ string_series = Series(range(20), dtype=np.float64, name="series")
237
+
238
+ alt = lambda x: sp_stats.skew(x, bias=False)
239
+ self._check_stat_op("skew", alt, string_series)
240
+
241
+ # test corner cases, skew() returns NaN unless there's at least 3
242
+ # values
243
+ min_N = 3
244
+ for i in range(1, min_N + 1):
245
+ s = Series(np.ones(i))
246
+ df = DataFrame(np.ones((i, i)))
247
+ if i < min_N:
248
+ assert np.isnan(s.skew())
249
+ assert np.isnan(df.skew()).all()
250
+ else:
251
+ assert 0 == s.skew()
252
+ assert isinstance(s.skew(), np.float64) # GH53482
253
+ assert (df.skew() == 0).all()
254
+
255
+ def test_kurt(self):
256
+ sp_stats = pytest.importorskip("scipy.stats")
257
+
258
+ string_series = Series(range(20), dtype=np.float64, name="series")
259
+
260
+ alt = lambda x: sp_stats.kurtosis(x, bias=False)
261
+ self._check_stat_op("kurt", alt, string_series)
262
+
263
+ def test_kurt_corner(self):
264
+ # test corner cases, kurt() returns NaN unless there's at least 4
265
+ # values
266
+ min_N = 4
267
+ for i in range(1, min_N + 1):
268
+ s = Series(np.ones(i))
269
+ df = DataFrame(np.ones((i, i)))
270
+ if i < min_N:
271
+ assert np.isnan(s.kurt())
272
+ assert np.isnan(df.kurt()).all()
273
+ else:
274
+ assert 0 == s.kurt()
275
+ assert isinstance(s.kurt(), np.float64) # GH53482
276
+ assert (df.kurt() == 0).all()