applied-ai-018 commited on
Commit
524330e
·
verified ·
1 Parent(s): 5c0cb19

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/universal/global_step80/zero/29.vocab_parallel_projection.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step80/zero/29.vocab_parallel_projection.weight/fp32.pt +3 -0
  3. venv/lib/python3.10/site-packages/pandas/tests/arrays/__init__.py +0 -0
  4. venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/__init__.cpython-310.pyc +0 -0
  5. venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/masked_shared.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_array.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_datetimelike.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_datetimes.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_ndarray_backed.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_period.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_timedeltas.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__init__.py +0 -0
  13. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/__init__.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_astype.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_comparison.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_construction.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_function.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_indexing.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_logical.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_ops.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_reduction.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_repr.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_arithmetic.py +139 -0
  25. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_astype.py +53 -0
  26. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_comparison.py +60 -0
  27. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_construction.py +325 -0
  28. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_function.py +126 -0
  29. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_indexing.py +13 -0
  30. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_logical.py +254 -0
  31. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_ops.py +27 -0
  32. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_reduction.py +62 -0
  33. venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_repr.py +13 -0
  34. venv/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__init__.py +0 -0
  35. venv/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_constructors.py +284 -0
  36. venv/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_cumulative.py +44 -0
  37. venv/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_reductions.py +183 -0
  38. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__init__.py +0 -0
  39. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/__init__.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/test_arrow_compat.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/test_function.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/test_indexing.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_arithmetic.py +248 -0
  45. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_arrow_compat.py +209 -0
  46. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_function.py +74 -0
  47. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_indexing.py +60 -0
  48. venv/lib/python3.10/site-packages/pandas/tests/arrays/masked_shared.py +154 -0
  49. venv/lib/python3.10/site-packages/pandas/tests/arrays/test_array.py +478 -0
  50. venv/lib/python3.10/site-packages/pandas/tests/arrays/test_datetimelike.py +1340 -0
ckpts/universal/global_step80/zero/29.vocab_parallel_projection.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d3809ad4f4093105a7755bf0762809537b7f61f2f619bf7c249a15b71b97657
3
+ size 415237276
ckpts/universal/global_step80/zero/29.vocab_parallel_projection.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94d6106a37347803a51c41c9c7ddad11335ae199d032aa8c1365b03c2a38348b
3
+ size 415237197
venv/lib/python3.10/site-packages/pandas/tests/arrays/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/masked_shared.cpython-310.pyc ADDED
Binary file (4.33 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_array.cpython-310.pyc ADDED
Binary file (9.32 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_datetimelike.cpython-310.pyc ADDED
Binary file (35.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_datetimes.cpython-310.pyc ADDED
Binary file (24.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_ndarray_backed.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_period.cpython-310.pyc ADDED
Binary file (5.71 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_timedeltas.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (195 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_arithmetic.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_astype.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_comparison.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_construction.cpython-310.pyc ADDED
Binary file (8.29 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_function.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (642 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_logical.cpython-310.pyc ADDED
Binary file (6.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_ops.cpython-310.pyc ADDED
Binary file (1.18 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_reduction.cpython-310.pyc ADDED
Binary file (1.75 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__pycache__/test_repr.cpython-310.pyc ADDED
Binary file (653 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_arithmetic.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+ import pandas._testing as tm
8
+
9
+
10
+ @pytest.fixture
11
+ def data():
12
+ """Fixture returning boolean array with valid and missing values."""
13
+ return pd.array(
14
+ [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False],
15
+ dtype="boolean",
16
+ )
17
+
18
+
19
+ @pytest.fixture
20
+ def left_array():
21
+ """Fixture returning boolean array with valid and missing values."""
22
+ return pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
23
+
24
+
25
+ @pytest.fixture
26
+ def right_array():
27
+ """Fixture returning boolean array with valid and missing values."""
28
+ return pd.array([True, False, None] * 3, dtype="boolean")
29
+
30
+
31
+ # Basic test for the arithmetic array ops
32
+ # -----------------------------------------------------------------------------
33
+
34
+
35
+ @pytest.mark.parametrize(
36
+ "opname, exp",
37
+ [
38
+ ("add", [True, True, None, True, False, None, None, None, None]),
39
+ ("mul", [True, False, None, False, False, None, None, None, None]),
40
+ ],
41
+ ids=["add", "mul"],
42
+ )
43
+ def test_add_mul(left_array, right_array, opname, exp):
44
+ op = getattr(operator, opname)
45
+ result = op(left_array, right_array)
46
+ expected = pd.array(exp, dtype="boolean")
47
+ tm.assert_extension_array_equal(result, expected)
48
+
49
+
50
+ def test_sub(left_array, right_array):
51
+ msg = (
52
+ r"numpy boolean subtract, the `-` operator, is (?:deprecated|not supported), "
53
+ r"use the bitwise_xor, the `\^` operator, or the logical_xor function instead\."
54
+ )
55
+ with pytest.raises(TypeError, match=msg):
56
+ left_array - right_array
57
+
58
+
59
+ def test_div(left_array, right_array):
60
+ msg = "operator '.*' not implemented for bool dtypes"
61
+ with pytest.raises(NotImplementedError, match=msg):
62
+ # check that we are matching the non-masked Series behavior
63
+ pd.Series(left_array._data) / pd.Series(right_array._data)
64
+
65
+ with pytest.raises(NotImplementedError, match=msg):
66
+ left_array / right_array
67
+
68
+
69
+ @pytest.mark.parametrize(
70
+ "opname",
71
+ [
72
+ "floordiv",
73
+ "mod",
74
+ "pow",
75
+ ],
76
+ )
77
+ def test_op_int8(left_array, right_array, opname):
78
+ op = getattr(operator, opname)
79
+ if opname != "mod":
80
+ msg = "operator '.*' not implemented for bool dtypes"
81
+ with pytest.raises(NotImplementedError, match=msg):
82
+ result = op(left_array, right_array)
83
+ return
84
+ result = op(left_array, right_array)
85
+ expected = op(left_array.astype("Int8"), right_array.astype("Int8"))
86
+ tm.assert_extension_array_equal(result, expected)
87
+
88
+
89
+ # Test generic characteristics / errors
90
+ # -----------------------------------------------------------------------------
91
+
92
+
93
+ def test_error_invalid_values(data, all_arithmetic_operators, using_infer_string):
94
+ # invalid ops
95
+
96
+ if using_infer_string:
97
+ import pyarrow as pa
98
+
99
+ err = (TypeError, pa.lib.ArrowNotImplementedError, NotImplementedError)
100
+ else:
101
+ err = TypeError
102
+
103
+ op = all_arithmetic_operators
104
+ s = pd.Series(data)
105
+ ops = getattr(s, op)
106
+
107
+ # invalid scalars
108
+ msg = (
109
+ "did not contain a loop with signature matching types|"
110
+ "BooleanArray cannot perform the operation|"
111
+ "not supported for the input types, and the inputs could not be safely coerced "
112
+ "to any supported types according to the casting rule ''safe''"
113
+ )
114
+ with pytest.raises(TypeError, match=msg):
115
+ ops("foo")
116
+ msg = "|".join(
117
+ [
118
+ r"unsupported operand type\(s\) for",
119
+ "Concatenation operation is not implemented for NumPy arrays",
120
+ "has no kernel",
121
+ ]
122
+ )
123
+ with pytest.raises(err, match=msg):
124
+ ops(pd.Timestamp("20180101"))
125
+
126
+ # invalid array-likes
127
+ if op not in ("__mul__", "__rmul__"):
128
+ # TODO(extension) numpy's mul with object array sees booleans as numbers
129
+ msg = "|".join(
130
+ [
131
+ r"unsupported operand type\(s\) for",
132
+ "can only concatenate str",
133
+ "not all arguments converted during string formatting",
134
+ "has no kernel",
135
+ "not implemented",
136
+ ]
137
+ )
138
+ with pytest.raises(err, match=msg):
139
+ ops(pd.Series("foo", index=s.index))
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_astype.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+
7
+
8
+ def test_astype():
9
+ # with missing values
10
+ arr = pd.array([True, False, None], dtype="boolean")
11
+
12
+ with pytest.raises(ValueError, match="cannot convert NA to integer"):
13
+ arr.astype("int64")
14
+
15
+ with pytest.raises(ValueError, match="cannot convert float NaN to"):
16
+ arr.astype("bool")
17
+
18
+ result = arr.astype("float64")
19
+ expected = np.array([1, 0, np.nan], dtype="float64")
20
+ tm.assert_numpy_array_equal(result, expected)
21
+
22
+ result = arr.astype("str")
23
+ expected = np.array(["True", "False", "<NA>"], dtype=f"{tm.ENDIAN}U5")
24
+ tm.assert_numpy_array_equal(result, expected)
25
+
26
+ # no missing values
27
+ arr = pd.array([True, False, True], dtype="boolean")
28
+ result = arr.astype("int64")
29
+ expected = np.array([1, 0, 1], dtype="int64")
30
+ tm.assert_numpy_array_equal(result, expected)
31
+
32
+ result = arr.astype("bool")
33
+ expected = np.array([True, False, True], dtype="bool")
34
+ tm.assert_numpy_array_equal(result, expected)
35
+
36
+
37
+ def test_astype_to_boolean_array():
38
+ # astype to BooleanArray
39
+ arr = pd.array([True, False, None], dtype="boolean")
40
+
41
+ result = arr.astype("boolean")
42
+ tm.assert_extension_array_equal(result, arr)
43
+ result = arr.astype(pd.BooleanDtype())
44
+ tm.assert_extension_array_equal(result, arr)
45
+
46
+
47
+ def test_astype_to_integer_array():
48
+ # astype to IntegerArray
49
+ arr = pd.array([True, False, None], dtype="boolean")
50
+
51
+ result = arr.astype("Int64")
52
+ expected = pd.array([1, 0, None], dtype="Int64")
53
+ tm.assert_extension_array_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_comparison.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+ from pandas.arrays import BooleanArray
7
+ from pandas.tests.arrays.masked_shared import ComparisonOps
8
+
9
+
10
+ @pytest.fixture
11
+ def data():
12
+ """Fixture returning boolean array with valid and missing data"""
13
+ return pd.array(
14
+ [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False],
15
+ dtype="boolean",
16
+ )
17
+
18
+
19
+ @pytest.fixture
20
+ def dtype():
21
+ """Fixture returning BooleanDtype"""
22
+ return pd.BooleanDtype()
23
+
24
+
25
+ class TestComparisonOps(ComparisonOps):
26
+ def test_compare_scalar(self, data, comparison_op):
27
+ self._compare_other(data, comparison_op, True)
28
+
29
+ def test_compare_array(self, data, comparison_op):
30
+ other = pd.array([True] * len(data), dtype="boolean")
31
+ self._compare_other(data, comparison_op, other)
32
+ other = np.array([True] * len(data))
33
+ self._compare_other(data, comparison_op, other)
34
+ other = pd.Series([True] * len(data))
35
+ self._compare_other(data, comparison_op, other)
36
+
37
+ @pytest.mark.parametrize("other", [True, False, pd.NA])
38
+ def test_scalar(self, other, comparison_op, dtype):
39
+ ComparisonOps.test_scalar(self, other, comparison_op, dtype)
40
+
41
+ def test_array(self, comparison_op):
42
+ op = comparison_op
43
+ a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
44
+ b = pd.array([True, False, None] * 3, dtype="boolean")
45
+
46
+ result = op(a, b)
47
+
48
+ values = op(a._data, b._data)
49
+ mask = a._mask | b._mask
50
+ expected = BooleanArray(values, mask)
51
+ tm.assert_extension_array_equal(result, expected)
52
+
53
+ # ensure we haven't mutated anything inplace
54
+ result[0] = None
55
+ tm.assert_extension_array_equal(
56
+ a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
57
+ )
58
+ tm.assert_extension_array_equal(
59
+ b, pd.array([True, False, None] * 3, dtype="boolean")
60
+ )
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_construction.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+ from pandas.arrays import BooleanArray
7
+ from pandas.core.arrays.boolean import coerce_to_array
8
+
9
+
10
+ def test_boolean_array_constructor():
11
+ values = np.array([True, False, True, False], dtype="bool")
12
+ mask = np.array([False, False, False, True], dtype="bool")
13
+
14
+ result = BooleanArray(values, mask)
15
+ expected = pd.array([True, False, True, None], dtype="boolean")
16
+ tm.assert_extension_array_equal(result, expected)
17
+
18
+ with pytest.raises(TypeError, match="values should be boolean numpy array"):
19
+ BooleanArray(values.tolist(), mask)
20
+
21
+ with pytest.raises(TypeError, match="mask should be boolean numpy array"):
22
+ BooleanArray(values, mask.tolist())
23
+
24
+ with pytest.raises(TypeError, match="values should be boolean numpy array"):
25
+ BooleanArray(values.astype(int), mask)
26
+
27
+ with pytest.raises(TypeError, match="mask should be boolean numpy array"):
28
+ BooleanArray(values, None)
29
+
30
+ with pytest.raises(ValueError, match="values.shape must match mask.shape"):
31
+ BooleanArray(values.reshape(1, -1), mask)
32
+
33
+ with pytest.raises(ValueError, match="values.shape must match mask.shape"):
34
+ BooleanArray(values, mask.reshape(1, -1))
35
+
36
+
37
+ def test_boolean_array_constructor_copy():
38
+ values = np.array([True, False, True, False], dtype="bool")
39
+ mask = np.array([False, False, False, True], dtype="bool")
40
+
41
+ result = BooleanArray(values, mask)
42
+ assert result._data is values
43
+ assert result._mask is mask
44
+
45
+ result = BooleanArray(values, mask, copy=True)
46
+ assert result._data is not values
47
+ assert result._mask is not mask
48
+
49
+
50
+ def test_to_boolean_array():
51
+ expected = BooleanArray(
52
+ np.array([True, False, True]), np.array([False, False, False])
53
+ )
54
+
55
+ result = pd.array([True, False, True], dtype="boolean")
56
+ tm.assert_extension_array_equal(result, expected)
57
+ result = pd.array(np.array([True, False, True]), dtype="boolean")
58
+ tm.assert_extension_array_equal(result, expected)
59
+ result = pd.array(np.array([True, False, True], dtype=object), dtype="boolean")
60
+ tm.assert_extension_array_equal(result, expected)
61
+
62
+ # with missing values
63
+ expected = BooleanArray(
64
+ np.array([True, False, True]), np.array([False, False, True])
65
+ )
66
+
67
+ result = pd.array([True, False, None], dtype="boolean")
68
+ tm.assert_extension_array_equal(result, expected)
69
+ result = pd.array(np.array([True, False, None], dtype=object), dtype="boolean")
70
+ tm.assert_extension_array_equal(result, expected)
71
+
72
+
73
+ def test_to_boolean_array_all_none():
74
+ expected = BooleanArray(np.array([True, True, True]), np.array([True, True, True]))
75
+
76
+ result = pd.array([None, None, None], dtype="boolean")
77
+ tm.assert_extension_array_equal(result, expected)
78
+ result = pd.array(np.array([None, None, None], dtype=object), dtype="boolean")
79
+ tm.assert_extension_array_equal(result, expected)
80
+
81
+
82
+ @pytest.mark.parametrize(
83
+ "a, b",
84
+ [
85
+ ([True, False, None, np.nan, pd.NA], [True, False, None, None, None]),
86
+ ([True, np.nan], [True, None]),
87
+ ([True, pd.NA], [True, None]),
88
+ ([np.nan, np.nan], [None, None]),
89
+ (np.array([np.nan, np.nan], dtype=float), [None, None]),
90
+ ],
91
+ )
92
+ def test_to_boolean_array_missing_indicators(a, b):
93
+ result = pd.array(a, dtype="boolean")
94
+ expected = pd.array(b, dtype="boolean")
95
+ tm.assert_extension_array_equal(result, expected)
96
+
97
+
98
+ @pytest.mark.parametrize(
99
+ "values",
100
+ [
101
+ ["foo", "bar"],
102
+ ["1", "2"],
103
+ # "foo",
104
+ [1, 2],
105
+ [1.0, 2.0],
106
+ pd.date_range("20130101", periods=2),
107
+ np.array(["foo"]),
108
+ np.array([1, 2]),
109
+ np.array([1.0, 2.0]),
110
+ [np.nan, {"a": 1}],
111
+ ],
112
+ )
113
+ def test_to_boolean_array_error(values):
114
+ # error in converting existing arrays to BooleanArray
115
+ msg = "Need to pass bool-like value"
116
+ with pytest.raises(TypeError, match=msg):
117
+ pd.array(values, dtype="boolean")
118
+
119
+
120
+ def test_to_boolean_array_from_integer_array():
121
+ result = pd.array(np.array([1, 0, 1, 0]), dtype="boolean")
122
+ expected = pd.array([True, False, True, False], dtype="boolean")
123
+ tm.assert_extension_array_equal(result, expected)
124
+
125
+ # with missing values
126
+ result = pd.array(np.array([1, 0, 1, None]), dtype="boolean")
127
+ expected = pd.array([True, False, True, None], dtype="boolean")
128
+ tm.assert_extension_array_equal(result, expected)
129
+
130
+
131
+ def test_to_boolean_array_from_float_array():
132
+ result = pd.array(np.array([1.0, 0.0, 1.0, 0.0]), dtype="boolean")
133
+ expected = pd.array([True, False, True, False], dtype="boolean")
134
+ tm.assert_extension_array_equal(result, expected)
135
+
136
+ # with missing values
137
+ result = pd.array(np.array([1.0, 0.0, 1.0, np.nan]), dtype="boolean")
138
+ expected = pd.array([True, False, True, None], dtype="boolean")
139
+ tm.assert_extension_array_equal(result, expected)
140
+
141
+
142
+ def test_to_boolean_array_integer_like():
143
+ # integers of 0's and 1's
144
+ result = pd.array([1, 0, 1, 0], dtype="boolean")
145
+ expected = pd.array([True, False, True, False], dtype="boolean")
146
+ tm.assert_extension_array_equal(result, expected)
147
+
148
+ # with missing values
149
+ result = pd.array([1, 0, 1, None], dtype="boolean")
150
+ expected = pd.array([True, False, True, None], dtype="boolean")
151
+ tm.assert_extension_array_equal(result, expected)
152
+
153
+
154
+ def test_coerce_to_array():
155
+ # TODO this is currently not public API
156
+ values = np.array([True, False, True, False], dtype="bool")
157
+ mask = np.array([False, False, False, True], dtype="bool")
158
+ result = BooleanArray(*coerce_to_array(values, mask=mask))
159
+ expected = BooleanArray(values, mask)
160
+ tm.assert_extension_array_equal(result, expected)
161
+ assert result._data is values
162
+ assert result._mask is mask
163
+ result = BooleanArray(*coerce_to_array(values, mask=mask, copy=True))
164
+ expected = BooleanArray(values, mask)
165
+ tm.assert_extension_array_equal(result, expected)
166
+ assert result._data is not values
167
+ assert result._mask is not mask
168
+
169
+ # mixed missing from values and mask
170
+ values = [True, False, None, False]
171
+ mask = np.array([False, False, False, True], dtype="bool")
172
+ result = BooleanArray(*coerce_to_array(values, mask=mask))
173
+ expected = BooleanArray(
174
+ np.array([True, False, True, True]), np.array([False, False, True, True])
175
+ )
176
+ tm.assert_extension_array_equal(result, expected)
177
+ result = BooleanArray(*coerce_to_array(np.array(values, dtype=object), mask=mask))
178
+ tm.assert_extension_array_equal(result, expected)
179
+ result = BooleanArray(*coerce_to_array(values, mask=mask.tolist()))
180
+ tm.assert_extension_array_equal(result, expected)
181
+
182
+ # raise errors for wrong dimension
183
+ values = np.array([True, False, True, False], dtype="bool")
184
+ mask = np.array([False, False, False, True], dtype="bool")
185
+
186
+ # passing 2D values is OK as long as no mask
187
+ coerce_to_array(values.reshape(1, -1))
188
+
189
+ with pytest.raises(ValueError, match="values.shape and mask.shape must match"):
190
+ coerce_to_array(values.reshape(1, -1), mask=mask)
191
+
192
+ with pytest.raises(ValueError, match="values.shape and mask.shape must match"):
193
+ coerce_to_array(values, mask=mask.reshape(1, -1))
194
+
195
+
196
+ def test_coerce_to_array_from_boolean_array():
197
+ # passing BooleanArray to coerce_to_array
198
+ values = np.array([True, False, True, False], dtype="bool")
199
+ mask = np.array([False, False, False, True], dtype="bool")
200
+ arr = BooleanArray(values, mask)
201
+ result = BooleanArray(*coerce_to_array(arr))
202
+ tm.assert_extension_array_equal(result, arr)
203
+ # no copy
204
+ assert result._data is arr._data
205
+ assert result._mask is arr._mask
206
+
207
+ result = BooleanArray(*coerce_to_array(arr), copy=True)
208
+ tm.assert_extension_array_equal(result, arr)
209
+ assert result._data is not arr._data
210
+ assert result._mask is not arr._mask
211
+
212
+ with pytest.raises(ValueError, match="cannot pass mask for BooleanArray input"):
213
+ coerce_to_array(arr, mask=mask)
214
+
215
+
216
+ def test_coerce_to_numpy_array():
217
+ # with missing values -> object dtype
218
+ arr = pd.array([True, False, None], dtype="boolean")
219
+ result = np.array(arr)
220
+ expected = np.array([True, False, pd.NA], dtype="object")
221
+ tm.assert_numpy_array_equal(result, expected)
222
+
223
+ # also with no missing values -> object dtype
224
+ arr = pd.array([True, False, True], dtype="boolean")
225
+ result = np.array(arr)
226
+ expected = np.array([True, False, True], dtype="bool")
227
+ tm.assert_numpy_array_equal(result, expected)
228
+
229
+ # force bool dtype
230
+ result = np.array(arr, dtype="bool")
231
+ expected = np.array([True, False, True], dtype="bool")
232
+ tm.assert_numpy_array_equal(result, expected)
233
+ # with missing values will raise error
234
+ arr = pd.array([True, False, None], dtype="boolean")
235
+ msg = (
236
+ "cannot convert to 'bool'-dtype NumPy array with missing values. "
237
+ "Specify an appropriate 'na_value' for this dtype."
238
+ )
239
+ with pytest.raises(ValueError, match=msg):
240
+ np.array(arr, dtype="bool")
241
+
242
+
243
+ def test_to_boolean_array_from_strings():
244
+ result = BooleanArray._from_sequence_of_strings(
245
+ np.array(["True", "False", "1", "1.0", "0", "0.0", np.nan], dtype=object),
246
+ dtype="boolean",
247
+ )
248
+ expected = BooleanArray(
249
+ np.array([True, False, True, True, False, False, False]),
250
+ np.array([False, False, False, False, False, False, True]),
251
+ )
252
+
253
+ tm.assert_extension_array_equal(result, expected)
254
+
255
+
256
+ def test_to_boolean_array_from_strings_invalid_string():
257
+ with pytest.raises(ValueError, match="cannot be cast"):
258
+ BooleanArray._from_sequence_of_strings(["donkey"], dtype="boolean")
259
+
260
+
261
+ @pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
262
+ def test_to_numpy(box):
263
+ con = pd.Series if box else pd.array
264
+ # default (with or without missing values) -> object dtype
265
+ arr = con([True, False, True], dtype="boolean")
266
+ result = arr.to_numpy()
267
+ expected = np.array([True, False, True], dtype="bool")
268
+ tm.assert_numpy_array_equal(result, expected)
269
+
270
+ arr = con([True, False, None], dtype="boolean")
271
+ result = arr.to_numpy()
272
+ expected = np.array([True, False, pd.NA], dtype="object")
273
+ tm.assert_numpy_array_equal(result, expected)
274
+
275
+ arr = con([True, False, None], dtype="boolean")
276
+ result = arr.to_numpy(dtype="str")
277
+ expected = np.array([True, False, pd.NA], dtype=f"{tm.ENDIAN}U5")
278
+ tm.assert_numpy_array_equal(result, expected)
279
+
280
+ # no missing values -> can convert to bool, otherwise raises
281
+ arr = con([True, False, True], dtype="boolean")
282
+ result = arr.to_numpy(dtype="bool")
283
+ expected = np.array([True, False, True], dtype="bool")
284
+ tm.assert_numpy_array_equal(result, expected)
285
+
286
+ arr = con([True, False, None], dtype="boolean")
287
+ with pytest.raises(ValueError, match="cannot convert to 'bool'-dtype"):
288
+ result = arr.to_numpy(dtype="bool")
289
+
290
+ # specify dtype and na_value
291
+ arr = con([True, False, None], dtype="boolean")
292
+ result = arr.to_numpy(dtype=object, na_value=None)
293
+ expected = np.array([True, False, None], dtype="object")
294
+ tm.assert_numpy_array_equal(result, expected)
295
+
296
+ result = arr.to_numpy(dtype=bool, na_value=False)
297
+ expected = np.array([True, False, False], dtype="bool")
298
+ tm.assert_numpy_array_equal(result, expected)
299
+
300
+ result = arr.to_numpy(dtype="int64", na_value=-99)
301
+ expected = np.array([1, 0, -99], dtype="int64")
302
+ tm.assert_numpy_array_equal(result, expected)
303
+
304
+ result = arr.to_numpy(dtype="float64", na_value=np.nan)
305
+ expected = np.array([1, 0, np.nan], dtype="float64")
306
+ tm.assert_numpy_array_equal(result, expected)
307
+
308
+ # converting to int or float without specifying na_value raises
309
+ with pytest.raises(ValueError, match="cannot convert to 'int64'-dtype"):
310
+ arr.to_numpy(dtype="int64")
311
+
312
+
313
+ def test_to_numpy_copy():
314
+ # to_numpy can be zero-copy if no missing values
315
+ arr = pd.array([True, False, True], dtype="boolean")
316
+ result = arr.to_numpy(dtype=bool)
317
+ result[0] = False
318
+ tm.assert_extension_array_equal(
319
+ arr, pd.array([False, False, True], dtype="boolean")
320
+ )
321
+
322
+ arr = pd.array([True, False, True], dtype="boolean")
323
+ result = arr.to_numpy(dtype=bool, copy=True)
324
+ result[0] = False
325
+ tm.assert_extension_array_equal(arr, pd.array([True, False, True], dtype="boolean"))
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_function.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+
7
+
8
+ @pytest.mark.parametrize(
9
+ "ufunc", [np.add, np.logical_or, np.logical_and, np.logical_xor]
10
+ )
11
+ def test_ufuncs_binary(ufunc):
12
+ # two BooleanArrays
13
+ a = pd.array([True, False, None], dtype="boolean")
14
+ result = ufunc(a, a)
15
+ expected = pd.array(ufunc(a._data, a._data), dtype="boolean")
16
+ expected[a._mask] = np.nan
17
+ tm.assert_extension_array_equal(result, expected)
18
+
19
+ s = pd.Series(a)
20
+ result = ufunc(s, a)
21
+ expected = pd.Series(ufunc(a._data, a._data), dtype="boolean")
22
+ expected[a._mask] = np.nan
23
+ tm.assert_series_equal(result, expected)
24
+
25
+ # Boolean with numpy array
26
+ arr = np.array([True, True, False])
27
+ result = ufunc(a, arr)
28
+ expected = pd.array(ufunc(a._data, arr), dtype="boolean")
29
+ expected[a._mask] = np.nan
30
+ tm.assert_extension_array_equal(result, expected)
31
+
32
+ result = ufunc(arr, a)
33
+ expected = pd.array(ufunc(arr, a._data), dtype="boolean")
34
+ expected[a._mask] = np.nan
35
+ tm.assert_extension_array_equal(result, expected)
36
+
37
+ # BooleanArray with scalar
38
+ result = ufunc(a, True)
39
+ expected = pd.array(ufunc(a._data, True), dtype="boolean")
40
+ expected[a._mask] = np.nan
41
+ tm.assert_extension_array_equal(result, expected)
42
+
43
+ result = ufunc(True, a)
44
+ expected = pd.array(ufunc(True, a._data), dtype="boolean")
45
+ expected[a._mask] = np.nan
46
+ tm.assert_extension_array_equal(result, expected)
47
+
48
+ # not handled types
49
+ msg = r"operand type\(s\) all returned NotImplemented from __array_ufunc__"
50
+ with pytest.raises(TypeError, match=msg):
51
+ ufunc(a, "test")
52
+
53
+
54
+ @pytest.mark.parametrize("ufunc", [np.logical_not])
55
+ def test_ufuncs_unary(ufunc):
56
+ a = pd.array([True, False, None], dtype="boolean")
57
+ result = ufunc(a)
58
+ expected = pd.array(ufunc(a._data), dtype="boolean")
59
+ expected[a._mask] = np.nan
60
+ tm.assert_extension_array_equal(result, expected)
61
+
62
+ ser = pd.Series(a)
63
+ result = ufunc(ser)
64
+ expected = pd.Series(ufunc(a._data), dtype="boolean")
65
+ expected[a._mask] = np.nan
66
+ tm.assert_series_equal(result, expected)
67
+
68
+
69
+ def test_ufunc_numeric():
70
+ # np.sqrt on np.bool_ returns float16, which we upcast to Float32
71
+ # bc we do not have Float16
72
+ arr = pd.array([True, False, None], dtype="boolean")
73
+
74
+ res = np.sqrt(arr)
75
+
76
+ expected = pd.array([1, 0, None], dtype="Float32")
77
+ tm.assert_extension_array_equal(res, expected)
78
+
79
+
80
+ @pytest.mark.parametrize("values", [[True, False], [True, None]])
81
+ def test_ufunc_reduce_raises(values):
82
+ arr = pd.array(values, dtype="boolean")
83
+
84
+ res = np.add.reduce(arr)
85
+ if arr[-1] is pd.NA:
86
+ expected = pd.NA
87
+ else:
88
+ expected = arr._data.sum()
89
+ tm.assert_almost_equal(res, expected)
90
+
91
+
92
+ def test_value_counts_na():
93
+ arr = pd.array([True, False, pd.NA], dtype="boolean")
94
+ result = arr.value_counts(dropna=False)
95
+ expected = pd.Series([1, 1, 1], index=arr, dtype="Int64", name="count")
96
+ assert expected.index.dtype == arr.dtype
97
+ tm.assert_series_equal(result, expected)
98
+
99
+ result = arr.value_counts(dropna=True)
100
+ expected = pd.Series([1, 1], index=arr[:-1], dtype="Int64", name="count")
101
+ assert expected.index.dtype == arr.dtype
102
+ tm.assert_series_equal(result, expected)
103
+
104
+
105
+ def test_value_counts_with_normalize():
106
+ ser = pd.Series([True, False, pd.NA], dtype="boolean")
107
+ result = ser.value_counts(normalize=True)
108
+ expected = pd.Series([1, 1], index=ser[:-1], dtype="Float64", name="proportion") / 2
109
+ assert expected.index.dtype == "boolean"
110
+ tm.assert_series_equal(result, expected)
111
+
112
+
113
+ def test_diff():
114
+ a = pd.array(
115
+ [True, True, False, False, True, None, True, None, False], dtype="boolean"
116
+ )
117
+ result = pd.core.algorithms.diff(a, 1)
118
+ expected = pd.array(
119
+ [None, False, True, False, True, None, None, None, None], dtype="boolean"
120
+ )
121
+ tm.assert_extension_array_equal(result, expected)
122
+
123
+ ser = pd.Series(a)
124
+ result = ser.diff()
125
+ expected = pd.Series(expected)
126
+ tm.assert_series_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_indexing.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+
7
+
8
+ @pytest.mark.parametrize("na", [None, np.nan, pd.NA])
9
+ def test_setitem_missing_values(na):
10
+ arr = pd.array([True, False, None], dtype="boolean")
11
+ expected = pd.array([True, None, None], dtype="boolean")
12
+ arr[1] = na
13
+ tm.assert_extension_array_equal(arr, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_logical.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+ import pandas._testing as tm
8
+ from pandas.arrays import BooleanArray
9
+ from pandas.core.ops.mask_ops import (
10
+ kleene_and,
11
+ kleene_or,
12
+ kleene_xor,
13
+ )
14
+ from pandas.tests.extension.base import BaseOpsUtil
15
+
16
+
17
+ class TestLogicalOps(BaseOpsUtil):
18
+ def test_numpy_scalars_ok(self, all_logical_operators):
19
+ a = pd.array([True, False, None], dtype="boolean")
20
+ op = getattr(a, all_logical_operators)
21
+
22
+ tm.assert_extension_array_equal(op(True), op(np.bool_(True)))
23
+ tm.assert_extension_array_equal(op(False), op(np.bool_(False)))
24
+
25
+ def get_op_from_name(self, op_name):
26
+ short_opname = op_name.strip("_")
27
+ short_opname = short_opname if "xor" in short_opname else short_opname + "_"
28
+ try:
29
+ op = getattr(operator, short_opname)
30
+ except AttributeError:
31
+ # Assume it is the reverse operator
32
+ rop = getattr(operator, short_opname[1:])
33
+ op = lambda x, y: rop(y, x)
34
+
35
+ return op
36
+
37
+ def test_empty_ok(self, all_logical_operators):
38
+ a = pd.array([], dtype="boolean")
39
+ op_name = all_logical_operators
40
+ result = getattr(a, op_name)(True)
41
+ tm.assert_extension_array_equal(a, result)
42
+
43
+ result = getattr(a, op_name)(False)
44
+ tm.assert_extension_array_equal(a, result)
45
+
46
+ result = getattr(a, op_name)(pd.NA)
47
+ tm.assert_extension_array_equal(a, result)
48
+
49
+ @pytest.mark.parametrize(
50
+ "other", ["a", pd.Timestamp(2017, 1, 1, 12), np.timedelta64(4)]
51
+ )
52
+ def test_eq_mismatched_type(self, other):
53
+ # GH-44499
54
+ arr = pd.array([True, False])
55
+ result = arr == other
56
+ expected = pd.array([False, False])
57
+ tm.assert_extension_array_equal(result, expected)
58
+
59
+ result = arr != other
60
+ expected = pd.array([True, True])
61
+ tm.assert_extension_array_equal(result, expected)
62
+
63
+ def test_logical_length_mismatch_raises(self, all_logical_operators):
64
+ op_name = all_logical_operators
65
+ a = pd.array([True, False, None], dtype="boolean")
66
+ msg = "Lengths must match"
67
+
68
+ with pytest.raises(ValueError, match=msg):
69
+ getattr(a, op_name)([True, False])
70
+
71
+ with pytest.raises(ValueError, match=msg):
72
+ getattr(a, op_name)(np.array([True, False]))
73
+
74
+ with pytest.raises(ValueError, match=msg):
75
+ getattr(a, op_name)(pd.array([True, False], dtype="boolean"))
76
+
77
+ def test_logical_nan_raises(self, all_logical_operators):
78
+ op_name = all_logical_operators
79
+ a = pd.array([True, False, None], dtype="boolean")
80
+ msg = "Got float instead"
81
+
82
+ with pytest.raises(TypeError, match=msg):
83
+ getattr(a, op_name)(np.nan)
84
+
85
+ @pytest.mark.parametrize("other", ["a", 1])
86
+ def test_non_bool_or_na_other_raises(self, other, all_logical_operators):
87
+ a = pd.array([True, False], dtype="boolean")
88
+ with pytest.raises(TypeError, match=str(type(other).__name__)):
89
+ getattr(a, all_logical_operators)(other)
90
+
91
+ def test_kleene_or(self):
92
+ # A clear test of behavior.
93
+ a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
94
+ b = pd.array([True, False, None] * 3, dtype="boolean")
95
+ result = a | b
96
+ expected = pd.array(
97
+ [True, True, True, True, False, None, True, None, None], dtype="boolean"
98
+ )
99
+ tm.assert_extension_array_equal(result, expected)
100
+
101
+ result = b | a
102
+ tm.assert_extension_array_equal(result, expected)
103
+
104
+ # ensure we haven't mutated anything inplace
105
+ tm.assert_extension_array_equal(
106
+ a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
107
+ )
108
+ tm.assert_extension_array_equal(
109
+ b, pd.array([True, False, None] * 3, dtype="boolean")
110
+ )
111
+
112
+ @pytest.mark.parametrize(
113
+ "other, expected",
114
+ [
115
+ (pd.NA, [True, None, None]),
116
+ (True, [True, True, True]),
117
+ (np.bool_(True), [True, True, True]),
118
+ (False, [True, False, None]),
119
+ (np.bool_(False), [True, False, None]),
120
+ ],
121
+ )
122
+ def test_kleene_or_scalar(self, other, expected):
123
+ # TODO: test True & False
124
+ a = pd.array([True, False, None], dtype="boolean")
125
+ result = a | other
126
+ expected = pd.array(expected, dtype="boolean")
127
+ tm.assert_extension_array_equal(result, expected)
128
+
129
+ result = other | a
130
+ tm.assert_extension_array_equal(result, expected)
131
+
132
+ # ensure we haven't mutated anything inplace
133
+ tm.assert_extension_array_equal(
134
+ a, pd.array([True, False, None], dtype="boolean")
135
+ )
136
+
137
+ def test_kleene_and(self):
138
+ # A clear test of behavior.
139
+ a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
140
+ b = pd.array([True, False, None] * 3, dtype="boolean")
141
+ result = a & b
142
+ expected = pd.array(
143
+ [True, False, None, False, False, False, None, False, None], dtype="boolean"
144
+ )
145
+ tm.assert_extension_array_equal(result, expected)
146
+
147
+ result = b & a
148
+ tm.assert_extension_array_equal(result, expected)
149
+
150
+ # ensure we haven't mutated anything inplace
151
+ tm.assert_extension_array_equal(
152
+ a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
153
+ )
154
+ tm.assert_extension_array_equal(
155
+ b, pd.array([True, False, None] * 3, dtype="boolean")
156
+ )
157
+
158
+ @pytest.mark.parametrize(
159
+ "other, expected",
160
+ [
161
+ (pd.NA, [None, False, None]),
162
+ (True, [True, False, None]),
163
+ (False, [False, False, False]),
164
+ (np.bool_(True), [True, False, None]),
165
+ (np.bool_(False), [False, False, False]),
166
+ ],
167
+ )
168
+ def test_kleene_and_scalar(self, other, expected):
169
+ a = pd.array([True, False, None], dtype="boolean")
170
+ result = a & other
171
+ expected = pd.array(expected, dtype="boolean")
172
+ tm.assert_extension_array_equal(result, expected)
173
+
174
+ result = other & a
175
+ tm.assert_extension_array_equal(result, expected)
176
+
177
+ # ensure we haven't mutated anything inplace
178
+ tm.assert_extension_array_equal(
179
+ a, pd.array([True, False, None], dtype="boolean")
180
+ )
181
+
182
+ def test_kleene_xor(self):
183
+ a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
184
+ b = pd.array([True, False, None] * 3, dtype="boolean")
185
+ result = a ^ b
186
+ expected = pd.array(
187
+ [False, True, None, True, False, None, None, None, None], dtype="boolean"
188
+ )
189
+ tm.assert_extension_array_equal(result, expected)
190
+
191
+ result = b ^ a
192
+ tm.assert_extension_array_equal(result, expected)
193
+
194
+ # ensure we haven't mutated anything inplace
195
+ tm.assert_extension_array_equal(
196
+ a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
197
+ )
198
+ tm.assert_extension_array_equal(
199
+ b, pd.array([True, False, None] * 3, dtype="boolean")
200
+ )
201
+
202
+ @pytest.mark.parametrize(
203
+ "other, expected",
204
+ [
205
+ (pd.NA, [None, None, None]),
206
+ (True, [False, True, None]),
207
+ (np.bool_(True), [False, True, None]),
208
+ (np.bool_(False), [True, False, None]),
209
+ ],
210
+ )
211
+ def test_kleene_xor_scalar(self, other, expected):
212
+ a = pd.array([True, False, None], dtype="boolean")
213
+ result = a ^ other
214
+ expected = pd.array(expected, dtype="boolean")
215
+ tm.assert_extension_array_equal(result, expected)
216
+
217
+ result = other ^ a
218
+ tm.assert_extension_array_equal(result, expected)
219
+
220
+ # ensure we haven't mutated anything inplace
221
+ tm.assert_extension_array_equal(
222
+ a, pd.array([True, False, None], dtype="boolean")
223
+ )
224
+
225
+ @pytest.mark.parametrize("other", [True, False, pd.NA, [True, False, None] * 3])
226
+ def test_no_masked_assumptions(self, other, all_logical_operators):
227
+ # The logical operations should not assume that masked values are False!
228
+ a = pd.arrays.BooleanArray(
229
+ np.array([True, True, True, False, False, False, True, False, True]),
230
+ np.array([False] * 6 + [True, True, True]),
231
+ )
232
+ b = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")
233
+ if isinstance(other, list):
234
+ other = pd.array(other, dtype="boolean")
235
+
236
+ result = getattr(a, all_logical_operators)(other)
237
+ expected = getattr(b, all_logical_operators)(other)
238
+ tm.assert_extension_array_equal(result, expected)
239
+
240
+ if isinstance(other, BooleanArray):
241
+ other._data[other._mask] = True
242
+ a._data[a._mask] = False
243
+
244
+ result = getattr(a, all_logical_operators)(other)
245
+ expected = getattr(b, all_logical_operators)(other)
246
+ tm.assert_extension_array_equal(result, expected)
247
+
248
+
249
+ @pytest.mark.parametrize("operation", [kleene_or, kleene_xor, kleene_and])
250
+ def test_error_both_scalar(operation):
251
+ msg = r"Either `left` or `right` need to be a np\.ndarray."
252
+ with pytest.raises(TypeError, match=msg):
253
+ # masks need to be non-None, otherwise it ends up in an infinite recursion
254
+ operation(True, True, np.zeros(1), np.zeros(1))
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_ops.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import pandas._testing as tm
3
+
4
+
5
+ class TestUnaryOps:
6
+ def test_invert(self):
7
+ a = pd.array([True, False, None], dtype="boolean")
8
+ expected = pd.array([False, True, None], dtype="boolean")
9
+ tm.assert_extension_array_equal(~a, expected)
10
+
11
+ expected = pd.Series(expected, index=["a", "b", "c"], name="name")
12
+ result = ~pd.Series(a, index=["a", "b", "c"], name="name")
13
+ tm.assert_series_equal(result, expected)
14
+
15
+ df = pd.DataFrame({"A": a, "B": [True, False, False]}, index=["a", "b", "c"])
16
+ result = ~df
17
+ expected = pd.DataFrame(
18
+ {"A": expected, "B": [False, True, True]}, index=["a", "b", "c"]
19
+ )
20
+ tm.assert_frame_equal(result, expected)
21
+
22
+ def test_abs(self):
23
+ # matching numpy behavior, abs is the identity function
24
+ arr = pd.array([True, False, None], dtype="boolean")
25
+ result = abs(arr)
26
+
27
+ tm.assert_extension_array_equal(result, arr)
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_reduction.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+
6
+
7
+ @pytest.fixture
8
+ def data():
9
+ """Fixture returning boolean array, with valid and missing values."""
10
+ return pd.array(
11
+ [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False],
12
+ dtype="boolean",
13
+ )
14
+
15
+
16
+ @pytest.mark.parametrize(
17
+ "values, exp_any, exp_all, exp_any_noskip, exp_all_noskip",
18
+ [
19
+ ([True, pd.NA], True, True, True, pd.NA),
20
+ ([False, pd.NA], False, False, pd.NA, False),
21
+ ([pd.NA], False, True, pd.NA, pd.NA),
22
+ ([], False, True, False, True),
23
+ # GH-33253: all True / all False values buggy with skipna=False
24
+ ([True, True], True, True, True, True),
25
+ ([False, False], False, False, False, False),
26
+ ],
27
+ )
28
+ def test_any_all(values, exp_any, exp_all, exp_any_noskip, exp_all_noskip):
29
+ # the methods return numpy scalars
30
+ exp_any = pd.NA if exp_any is pd.NA else np.bool_(exp_any)
31
+ exp_all = pd.NA if exp_all is pd.NA else np.bool_(exp_all)
32
+ exp_any_noskip = pd.NA if exp_any_noskip is pd.NA else np.bool_(exp_any_noskip)
33
+ exp_all_noskip = pd.NA if exp_all_noskip is pd.NA else np.bool_(exp_all_noskip)
34
+
35
+ for con in [pd.array, pd.Series]:
36
+ a = con(values, dtype="boolean")
37
+ assert a.any() is exp_any
38
+ assert a.all() is exp_all
39
+ assert a.any(skipna=False) is exp_any_noskip
40
+ assert a.all(skipna=False) is exp_all_noskip
41
+
42
+ assert np.any(a.any()) is exp_any
43
+ assert np.all(a.all()) is exp_all
44
+
45
+
46
+ @pytest.mark.parametrize("dropna", [True, False])
47
+ def test_reductions_return_types(dropna, data, all_numeric_reductions):
48
+ op = all_numeric_reductions
49
+ s = pd.Series(data)
50
+ if dropna:
51
+ s = s.dropna()
52
+
53
+ if op in ("sum", "prod"):
54
+ assert isinstance(getattr(s, op)(), np.int_)
55
+ elif op == "count":
56
+ # Oddly on the 32 bit build (but not Windows), this is intc (!= intp)
57
+ assert isinstance(getattr(s, op)(), np.integer)
58
+ elif op in ("min", "max"):
59
+ assert isinstance(getattr(s, op)(), np.bool_)
60
+ else:
61
+ # "mean", "std", "var", "median", "kurt", "skew"
62
+ assert isinstance(getattr(s, op)(), np.float64)
venv/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_repr.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+
4
+ def test_repr():
5
+ df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")})
6
+ expected = " A\n0 True\n1 False\n2 <NA>"
7
+ assert repr(df) == expected
8
+
9
+ expected = "0 True\n1 False\n2 <NA>\nName: A, dtype: boolean"
10
+ assert repr(df.A) == expected
11
+
12
+ expected = "<BooleanArray>\n[True, False, <NA>]\nLength: 3, dtype: boolean"
13
+ assert repr(df.A.array) == expected
venv/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_constructors.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._libs import iNaT
5
+
6
+ from pandas.core.dtypes.dtypes import DatetimeTZDtype
7
+
8
+ import pandas as pd
9
+ import pandas._testing as tm
10
+ from pandas.core.arrays import DatetimeArray
11
+
12
+
13
+ class TestDatetimeArrayConstructor:
14
+ def test_from_sequence_invalid_type(self):
15
+ mi = pd.MultiIndex.from_product([np.arange(5), np.arange(5)])
16
+ with pytest.raises(TypeError, match="Cannot create a DatetimeArray"):
17
+ DatetimeArray._from_sequence(mi, dtype="M8[ns]")
18
+
19
+ def test_only_1dim_accepted(self):
20
+ arr = np.array([0, 1, 2, 3], dtype="M8[h]").astype("M8[ns]")
21
+
22
+ depr_msg = "DatetimeArray.__init__ is deprecated"
23
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
24
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
25
+ # 3-dim, we allow 2D to sneak in for ops purposes GH#29853
26
+ DatetimeArray(arr.reshape(2, 2, 1))
27
+
28
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
29
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
30
+ # 0-dim
31
+ DatetimeArray(arr[[0]].squeeze())
32
+
33
+ def test_freq_validation(self):
34
+ # GH#24623 check that invalid instances cannot be created with the
35
+ # public constructor
36
+ arr = np.arange(5, dtype=np.int64) * 3600 * 10**9
37
+
38
+ msg = (
39
+ "Inferred frequency h from passed values does not "
40
+ "conform to passed frequency W-SUN"
41
+ )
42
+ depr_msg = "DatetimeArray.__init__ is deprecated"
43
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
44
+ with pytest.raises(ValueError, match=msg):
45
+ DatetimeArray(arr, freq="W")
46
+
47
+ @pytest.mark.parametrize(
48
+ "meth",
49
+ [
50
+ DatetimeArray._from_sequence,
51
+ pd.to_datetime,
52
+ pd.DatetimeIndex,
53
+ ],
54
+ )
55
+ def test_mixing_naive_tzaware_raises(self, meth):
56
+ # GH#24569
57
+ arr = np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")])
58
+
59
+ msg = (
60
+ "Cannot mix tz-aware with tz-naive values|"
61
+ "Tz-aware datetime.datetime cannot be converted "
62
+ "to datetime64 unless utc=True"
63
+ )
64
+
65
+ for obj in [arr, arr[::-1]]:
66
+ # check that we raise regardless of whether naive is found
67
+ # before aware or vice-versa
68
+ with pytest.raises(ValueError, match=msg):
69
+ meth(obj)
70
+
71
+ def test_from_pandas_array(self):
72
+ arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10**9
73
+
74
+ result = DatetimeArray._from_sequence(arr, dtype="M8[ns]")._with_freq("infer")
75
+
76
+ expected = pd.date_range("1970-01-01", periods=5, freq="h")._data
77
+ tm.assert_datetime_array_equal(result, expected)
78
+
79
+ def test_mismatched_timezone_raises(self):
80
+ depr_msg = "DatetimeArray.__init__ is deprecated"
81
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
82
+ arr = DatetimeArray(
83
+ np.array(["2000-01-01T06:00:00"], dtype="M8[ns]"),
84
+ dtype=DatetimeTZDtype(tz="US/Central"),
85
+ )
86
+ dtype = DatetimeTZDtype(tz="US/Eastern")
87
+ msg = r"dtype=datetime64\[ns.*\] does not match data dtype datetime64\[ns.*\]"
88
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
89
+ with pytest.raises(TypeError, match=msg):
90
+ DatetimeArray(arr, dtype=dtype)
91
+
92
+ # also with mismatched tzawareness
93
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
94
+ with pytest.raises(TypeError, match=msg):
95
+ DatetimeArray(arr, dtype=np.dtype("M8[ns]"))
96
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
97
+ with pytest.raises(TypeError, match=msg):
98
+ DatetimeArray(arr.tz_localize(None), dtype=arr.dtype)
99
+
100
+ def test_non_array_raises(self):
101
+ depr_msg = "DatetimeArray.__init__ is deprecated"
102
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
103
+ with pytest.raises(ValueError, match="list"):
104
+ DatetimeArray([1, 2, 3])
105
+
106
+ def test_bool_dtype_raises(self):
107
+ arr = np.array([1, 2, 3], dtype="bool")
108
+
109
+ depr_msg = "DatetimeArray.__init__ is deprecated"
110
+ msg = "Unexpected value for 'dtype': 'bool'. Must be"
111
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
112
+ with pytest.raises(ValueError, match=msg):
113
+ DatetimeArray(arr)
114
+
115
+ msg = r"dtype bool cannot be converted to datetime64\[ns\]"
116
+ with pytest.raises(TypeError, match=msg):
117
+ DatetimeArray._from_sequence(arr, dtype="M8[ns]")
118
+
119
+ with pytest.raises(TypeError, match=msg):
120
+ pd.DatetimeIndex(arr)
121
+
122
+ with pytest.raises(TypeError, match=msg):
123
+ pd.to_datetime(arr)
124
+
125
+ def test_incorrect_dtype_raises(self):
126
+ depr_msg = "DatetimeArray.__init__ is deprecated"
127
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
128
+ with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
129
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="category")
130
+
131
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
132
+ with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
133
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="m8[s]")
134
+
135
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
136
+ with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
137
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="M8[D]")
138
+
139
+ def test_mismatched_values_dtype_units(self):
140
+ arr = np.array([1, 2, 3], dtype="M8[s]")
141
+ dtype = np.dtype("M8[ns]")
142
+ msg = "Values resolution does not match dtype."
143
+ depr_msg = "DatetimeArray.__init__ is deprecated"
144
+
145
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
146
+ with pytest.raises(ValueError, match=msg):
147
+ DatetimeArray(arr, dtype=dtype)
148
+
149
+ dtype2 = DatetimeTZDtype(tz="UTC", unit="ns")
150
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
151
+ with pytest.raises(ValueError, match=msg):
152
+ DatetimeArray(arr, dtype=dtype2)
153
+
154
+ def test_freq_infer_raises(self):
155
+ depr_msg = "DatetimeArray.__init__ is deprecated"
156
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
157
+ with pytest.raises(ValueError, match="Frequency inference"):
158
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), freq="infer")
159
+
160
+ def test_copy(self):
161
+ data = np.array([1, 2, 3], dtype="M8[ns]")
162
+ arr = DatetimeArray._from_sequence(data, copy=False)
163
+ assert arr._ndarray is data
164
+
165
+ arr = DatetimeArray._from_sequence(data, copy=True)
166
+ assert arr._ndarray is not data
167
+
168
+ @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
169
+ def test_numpy_datetime_unit(self, unit):
170
+ data = np.array([1, 2, 3], dtype=f"M8[{unit}]")
171
+ arr = DatetimeArray._from_sequence(data)
172
+ assert arr.unit == unit
173
+ assert arr[0].unit == unit
174
+
175
+
176
+ class TestSequenceToDT64NS:
177
+ def test_tz_dtype_mismatch_raises(self):
178
+ arr = DatetimeArray._from_sequence(
179
+ ["2000"], dtype=DatetimeTZDtype(tz="US/Central")
180
+ )
181
+ with pytest.raises(TypeError, match="data is already tz-aware"):
182
+ DatetimeArray._from_sequence(arr, dtype=DatetimeTZDtype(tz="UTC"))
183
+
184
+ def test_tz_dtype_matches(self):
185
+ dtype = DatetimeTZDtype(tz="US/Central")
186
+ arr = DatetimeArray._from_sequence(["2000"], dtype=dtype)
187
+ result = DatetimeArray._from_sequence(arr, dtype=dtype)
188
+ tm.assert_equal(arr, result)
189
+
190
+ @pytest.mark.parametrize("order", ["F", "C"])
191
+ def test_2d(self, order):
192
+ dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
193
+ arr = np.array(dti, dtype=object).reshape(3, 2)
194
+ if order == "F":
195
+ arr = arr.T
196
+
197
+ res = DatetimeArray._from_sequence(arr, dtype=dti.dtype)
198
+ expected = DatetimeArray._from_sequence(arr.ravel(), dtype=dti.dtype).reshape(
199
+ arr.shape
200
+ )
201
+ tm.assert_datetime_array_equal(res, expected)
202
+
203
+
204
+ # ----------------------------------------------------------------------------
205
+ # Arrow interaction
206
+
207
+
208
+ EXTREME_VALUES = [0, 123456789, None, iNaT, 2**63 - 1, -(2**63) + 1]
209
+ FINE_TO_COARSE_SAFE = [123_000_000_000, None, -123_000_000_000]
210
+ COARSE_TO_FINE_SAFE = [123, None, -123]
211
+
212
+
213
+ @pytest.mark.parametrize(
214
+ ("pa_unit", "pd_unit", "pa_tz", "pd_tz", "data"),
215
+ [
216
+ ("s", "s", "UTC", "UTC", EXTREME_VALUES),
217
+ ("ms", "ms", "UTC", "Europe/Berlin", EXTREME_VALUES),
218
+ ("us", "us", "US/Eastern", "UTC", EXTREME_VALUES),
219
+ ("ns", "ns", "US/Central", "Asia/Kolkata", EXTREME_VALUES),
220
+ ("ns", "s", "UTC", "UTC", FINE_TO_COARSE_SAFE),
221
+ ("us", "ms", "UTC", "Europe/Berlin", FINE_TO_COARSE_SAFE),
222
+ ("ms", "us", "US/Eastern", "UTC", COARSE_TO_FINE_SAFE),
223
+ ("s", "ns", "US/Central", "Asia/Kolkata", COARSE_TO_FINE_SAFE),
224
+ ],
225
+ )
226
+ def test_from_arrow_with_different_units_and_timezones_with(
227
+ pa_unit, pd_unit, pa_tz, pd_tz, data
228
+ ):
229
+ pa = pytest.importorskip("pyarrow")
230
+
231
+ pa_type = pa.timestamp(pa_unit, tz=pa_tz)
232
+ arr = pa.array(data, type=pa_type)
233
+ dtype = DatetimeTZDtype(unit=pd_unit, tz=pd_tz)
234
+
235
+ result = dtype.__from_arrow__(arr)
236
+ expected = DatetimeArray._from_sequence(data, dtype=f"M8[{pa_unit}, UTC]").astype(
237
+ dtype, copy=False
238
+ )
239
+ tm.assert_extension_array_equal(result, expected)
240
+
241
+ result = dtype.__from_arrow__(pa.chunked_array([arr]))
242
+ tm.assert_extension_array_equal(result, expected)
243
+
244
+
245
+ @pytest.mark.parametrize(
246
+ ("unit", "tz"),
247
+ [
248
+ ("s", "UTC"),
249
+ ("ms", "Europe/Berlin"),
250
+ ("us", "US/Eastern"),
251
+ ("ns", "Asia/Kolkata"),
252
+ ("ns", "UTC"),
253
+ ],
254
+ )
255
+ def test_from_arrow_from_empty(unit, tz):
256
+ pa = pytest.importorskip("pyarrow")
257
+
258
+ data = []
259
+ arr = pa.array(data)
260
+ dtype = DatetimeTZDtype(unit=unit, tz=tz)
261
+
262
+ result = dtype.__from_arrow__(arr)
263
+ expected = DatetimeArray._from_sequence(np.array(data, dtype=f"datetime64[{unit}]"))
264
+ expected = expected.tz_localize(tz=tz)
265
+ tm.assert_extension_array_equal(result, expected)
266
+
267
+ result = dtype.__from_arrow__(pa.chunked_array([arr]))
268
+ tm.assert_extension_array_equal(result, expected)
269
+
270
+
271
+ def test_from_arrow_from_integers():
272
+ pa = pytest.importorskip("pyarrow")
273
+
274
+ data = [0, 123456789, None, 2**63 - 1, iNaT, -123456789]
275
+ arr = pa.array(data)
276
+ dtype = DatetimeTZDtype(unit="ns", tz="UTC")
277
+
278
+ result = dtype.__from_arrow__(arr)
279
+ expected = DatetimeArray._from_sequence(np.array(data, dtype="datetime64[ns]"))
280
+ expected = expected.tz_localize("UTC")
281
+ tm.assert_extension_array_equal(result, expected)
282
+
283
+ result = dtype.__from_arrow__(pa.chunked_array([arr]))
284
+ tm.assert_extension_array_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_cumulative.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import pandas._testing as tm
4
+ from pandas.core.arrays import DatetimeArray
5
+
6
+
7
+ class TestAccumulator:
8
+ def test_accumulators_freq(self):
9
+ # GH#50297
10
+ arr = DatetimeArray._from_sequence(
11
+ [
12
+ "2000-01-01",
13
+ "2000-01-02",
14
+ "2000-01-03",
15
+ ],
16
+ dtype="M8[ns]",
17
+ )._with_freq("infer")
18
+ result = arr._accumulate("cummin")
19
+ expected = DatetimeArray._from_sequence(["2000-01-01"] * 3, dtype="M8[ns]")
20
+ tm.assert_datetime_array_equal(result, expected)
21
+
22
+ result = arr._accumulate("cummax")
23
+ expected = DatetimeArray._from_sequence(
24
+ [
25
+ "2000-01-01",
26
+ "2000-01-02",
27
+ "2000-01-03",
28
+ ],
29
+ dtype="M8[ns]",
30
+ )
31
+ tm.assert_datetime_array_equal(result, expected)
32
+
33
+ @pytest.mark.parametrize("func", ["cumsum", "cumprod"])
34
+ def test_accumulators_disallowed(self, func):
35
+ # GH#50297
36
+ arr = DatetimeArray._from_sequence(
37
+ [
38
+ "2000-01-01",
39
+ "2000-01-02",
40
+ ],
41
+ dtype="M8[ns]",
42
+ )._with_freq("infer")
43
+ with pytest.raises(TypeError, match=f"Accumulation {func}"):
44
+ arr._accumulate(func)
venv/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_reductions.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.core.dtypes.dtypes import DatetimeTZDtype
5
+
6
+ import pandas as pd
7
+ from pandas import NaT
8
+ import pandas._testing as tm
9
+ from pandas.core.arrays import DatetimeArray
10
+
11
+
12
+ class TestReductions:
13
+ @pytest.fixture(params=["s", "ms", "us", "ns"])
14
+ def unit(self, request):
15
+ return request.param
16
+
17
+ @pytest.fixture
18
+ def arr1d(self, tz_naive_fixture):
19
+ """Fixture returning DatetimeArray with parametrized timezones"""
20
+ tz = tz_naive_fixture
21
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
22
+ arr = DatetimeArray._from_sequence(
23
+ [
24
+ "2000-01-03",
25
+ "2000-01-03",
26
+ "NaT",
27
+ "2000-01-02",
28
+ "2000-01-05",
29
+ "2000-01-04",
30
+ ],
31
+ dtype=dtype,
32
+ )
33
+ return arr
34
+
35
+ def test_min_max(self, arr1d, unit):
36
+ arr = arr1d
37
+ arr = arr.as_unit(unit)
38
+ tz = arr.tz
39
+
40
+ result = arr.min()
41
+ expected = pd.Timestamp("2000-01-02", tz=tz).as_unit(unit)
42
+ assert result == expected
43
+ assert result.unit == expected.unit
44
+
45
+ result = arr.max()
46
+ expected = pd.Timestamp("2000-01-05", tz=tz).as_unit(unit)
47
+ assert result == expected
48
+ assert result.unit == expected.unit
49
+
50
+ result = arr.min(skipna=False)
51
+ assert result is NaT
52
+
53
+ result = arr.max(skipna=False)
54
+ assert result is NaT
55
+
56
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
57
+ @pytest.mark.parametrize("skipna", [True, False])
58
+ def test_min_max_empty(self, skipna, tz):
59
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
60
+ arr = DatetimeArray._from_sequence([], dtype=dtype)
61
+ result = arr.min(skipna=skipna)
62
+ assert result is NaT
63
+
64
+ result = arr.max(skipna=skipna)
65
+ assert result is NaT
66
+
67
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
68
+ @pytest.mark.parametrize("skipna", [True, False])
69
+ def test_median_empty(self, skipna, tz):
70
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
71
+ arr = DatetimeArray._from_sequence([], dtype=dtype)
72
+ result = arr.median(skipna=skipna)
73
+ assert result is NaT
74
+
75
+ arr = arr.reshape(0, 3)
76
+ result = arr.median(axis=0, skipna=skipna)
77
+ expected = type(arr)._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)
78
+ tm.assert_equal(result, expected)
79
+
80
+ result = arr.median(axis=1, skipna=skipna)
81
+ expected = type(arr)._from_sequence([], dtype=arr.dtype)
82
+ tm.assert_equal(result, expected)
83
+
84
+ def test_median(self, arr1d):
85
+ arr = arr1d
86
+
87
+ result = arr.median()
88
+ assert result == arr[0]
89
+ result = arr.median(skipna=False)
90
+ assert result is NaT
91
+
92
+ result = arr.dropna().median(skipna=False)
93
+ assert result == arr[0]
94
+
95
+ result = arr.median(axis=0)
96
+ assert result == arr[0]
97
+
98
+ def test_median_axis(self, arr1d):
99
+ arr = arr1d
100
+ assert arr.median(axis=0) == arr.median()
101
+ assert arr.median(axis=0, skipna=False) is NaT
102
+
103
+ msg = r"abs\(axis\) must be less than ndim"
104
+ with pytest.raises(ValueError, match=msg):
105
+ arr.median(axis=1)
106
+
107
+ @pytest.mark.filterwarnings("ignore:All-NaN slice encountered:RuntimeWarning")
108
+ def test_median_2d(self, arr1d):
109
+ arr = arr1d.reshape(1, -1)
110
+
111
+ # axis = None
112
+ assert arr.median() == arr1d.median()
113
+ assert arr.median(skipna=False) is NaT
114
+
115
+ # axis = 0
116
+ result = arr.median(axis=0)
117
+ expected = arr1d
118
+ tm.assert_equal(result, expected)
119
+
120
+ # Since column 3 is all-NaT, we get NaT there with or without skipna
121
+ result = arr.median(axis=0, skipna=False)
122
+ expected = arr1d
123
+ tm.assert_equal(result, expected)
124
+
125
+ # axis = 1
126
+ result = arr.median(axis=1)
127
+ expected = type(arr)._from_sequence([arr1d.median()], dtype=arr.dtype)
128
+ tm.assert_equal(result, expected)
129
+
130
+ result = arr.median(axis=1, skipna=False)
131
+ expected = type(arr)._from_sequence([NaT], dtype=arr.dtype)
132
+ tm.assert_equal(result, expected)
133
+
134
+ def test_mean(self, arr1d):
135
+ arr = arr1d
136
+
137
+ # manually verified result
138
+ expected = arr[0] + 0.4 * pd.Timedelta(days=1)
139
+
140
+ result = arr.mean()
141
+ assert result == expected
142
+ result = arr.mean(skipna=False)
143
+ assert result is NaT
144
+
145
+ result = arr.dropna().mean(skipna=False)
146
+ assert result == expected
147
+
148
+ result = arr.mean(axis=0)
149
+ assert result == expected
150
+
151
+ def test_mean_2d(self):
152
+ dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
153
+ dta = dti._data.reshape(3, 2)
154
+
155
+ result = dta.mean(axis=0)
156
+ expected = dta[1]
157
+ tm.assert_datetime_array_equal(result, expected)
158
+
159
+ result = dta.mean(axis=1)
160
+ expected = dta[:, 0] + pd.Timedelta(hours=12)
161
+ tm.assert_datetime_array_equal(result, expected)
162
+
163
+ result = dta.mean(axis=None)
164
+ expected = dti.mean()
165
+ assert result == expected
166
+
167
+ @pytest.mark.parametrize("skipna", [True, False])
168
+ def test_mean_empty(self, arr1d, skipna):
169
+ arr = arr1d[:0]
170
+
171
+ assert arr.mean(skipna=skipna) is NaT
172
+
173
+ arr2d = arr.reshape(0, 3)
174
+ result = arr2d.mean(axis=0, skipna=skipna)
175
+ expected = DatetimeArray._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)
176
+ tm.assert_datetime_array_equal(result, expected)
177
+
178
+ result = arr2d.mean(axis=1, skipna=skipna)
179
+ expected = arr # i.e. 1D, empty
180
+ tm.assert_datetime_array_equal(result, expected)
181
+
182
+ result = arr2d.mean(axis=None, skipna=skipna)
183
+ assert result is NaT
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/test_arithmetic.cpython-310.pyc ADDED
Binary file (6.48 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/test_arrow_compat.cpython-310.pyc ADDED
Binary file (6.35 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/test_function.cpython-310.pyc ADDED
Binary file (2.54 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (2.07 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_arithmetic.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import numpy as np
6
+ import pytest
7
+
8
+ import pandas as pd
9
+ import pandas._testing as tm
10
+
11
+ # integer dtypes
12
+ arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
13
+ scalars: list[Any] = [2] * len(arrays)
14
+ # floating dtypes
15
+ arrays += [pd.array([0.1, 0.2, 0.3, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES]
16
+ scalars += [0.2, 0.2]
17
+ # boolean
18
+ arrays += [pd.array([True, False, True, None], dtype="boolean")]
19
+ scalars += [False]
20
+
21
+
22
+ @pytest.fixture(params=zip(arrays, scalars), ids=[a.dtype.name for a in arrays])
23
+ def data(request):
24
+ """Fixture returning parametrized (array, scalar) tuple.
25
+
26
+ Used to test equivalence of scalars, numpy arrays with array ops, and the
27
+ equivalence of DataFrame and Series ops.
28
+ """
29
+ return request.param
30
+
31
+
32
+ def check_skip(data, op_name):
33
+ if isinstance(data.dtype, pd.BooleanDtype) and "sub" in op_name:
34
+ pytest.skip("subtract not implemented for boolean")
35
+
36
+
37
+ def is_bool_not_implemented(data, op_name):
38
+ # match non-masked behavior
39
+ return data.dtype.kind == "b" and op_name.strip("_").lstrip("r") in [
40
+ "pow",
41
+ "truediv",
42
+ "floordiv",
43
+ ]
44
+
45
+
46
+ # Test equivalence of scalars, numpy arrays with array ops
47
+ # -----------------------------------------------------------------------------
48
+
49
+
50
+ def test_array_scalar_like_equivalence(data, all_arithmetic_operators):
51
+ data, scalar = data
52
+ op = tm.get_op_from_name(all_arithmetic_operators)
53
+ check_skip(data, all_arithmetic_operators)
54
+
55
+ scalar_array = pd.array([scalar] * len(data), dtype=data.dtype)
56
+
57
+ # TODO also add len-1 array (np.array([scalar], dtype=data.dtype.numpy_dtype))
58
+ for scalar in [scalar, data.dtype.type(scalar)]:
59
+ if is_bool_not_implemented(data, all_arithmetic_operators):
60
+ msg = "operator '.*' not implemented for bool dtypes"
61
+ with pytest.raises(NotImplementedError, match=msg):
62
+ op(data, scalar)
63
+ with pytest.raises(NotImplementedError, match=msg):
64
+ op(data, scalar_array)
65
+ else:
66
+ result = op(data, scalar)
67
+ expected = op(data, scalar_array)
68
+ tm.assert_extension_array_equal(result, expected)
69
+
70
+
71
+ def test_array_NA(data, all_arithmetic_operators):
72
+ data, _ = data
73
+ op = tm.get_op_from_name(all_arithmetic_operators)
74
+ check_skip(data, all_arithmetic_operators)
75
+
76
+ scalar = pd.NA
77
+ scalar_array = pd.array([pd.NA] * len(data), dtype=data.dtype)
78
+
79
+ mask = data._mask.copy()
80
+
81
+ if is_bool_not_implemented(data, all_arithmetic_operators):
82
+ msg = "operator '.*' not implemented for bool dtypes"
83
+ with pytest.raises(NotImplementedError, match=msg):
84
+ op(data, scalar)
85
+ # GH#45421 check op doesn't alter data._mask inplace
86
+ tm.assert_numpy_array_equal(mask, data._mask)
87
+ return
88
+
89
+ result = op(data, scalar)
90
+ # GH#45421 check op doesn't alter data._mask inplace
91
+ tm.assert_numpy_array_equal(mask, data._mask)
92
+
93
+ expected = op(data, scalar_array)
94
+ tm.assert_numpy_array_equal(mask, data._mask)
95
+
96
+ tm.assert_extension_array_equal(result, expected)
97
+
98
+
99
+ def test_numpy_array_equivalence(data, all_arithmetic_operators):
100
+ data, scalar = data
101
+ op = tm.get_op_from_name(all_arithmetic_operators)
102
+ check_skip(data, all_arithmetic_operators)
103
+
104
+ numpy_array = np.array([scalar] * len(data), dtype=data.dtype.numpy_dtype)
105
+ pd_array = pd.array(numpy_array, dtype=data.dtype)
106
+
107
+ if is_bool_not_implemented(data, all_arithmetic_operators):
108
+ msg = "operator '.*' not implemented for bool dtypes"
109
+ with pytest.raises(NotImplementedError, match=msg):
110
+ op(data, numpy_array)
111
+ with pytest.raises(NotImplementedError, match=msg):
112
+ op(data, pd_array)
113
+ return
114
+
115
+ result = op(data, numpy_array)
116
+ expected = op(data, pd_array)
117
+ tm.assert_extension_array_equal(result, expected)
118
+
119
+
120
+ # Test equivalence with Series and DataFrame ops
121
+ # -----------------------------------------------------------------------------
122
+
123
+
124
+ def test_frame(data, all_arithmetic_operators):
125
+ data, scalar = data
126
+ op = tm.get_op_from_name(all_arithmetic_operators)
127
+ check_skip(data, all_arithmetic_operators)
128
+
129
+ # DataFrame with scalar
130
+ df = pd.DataFrame({"A": data})
131
+
132
+ if is_bool_not_implemented(data, all_arithmetic_operators):
133
+ msg = "operator '.*' not implemented for bool dtypes"
134
+ with pytest.raises(NotImplementedError, match=msg):
135
+ op(df, scalar)
136
+ with pytest.raises(NotImplementedError, match=msg):
137
+ op(data, scalar)
138
+ return
139
+
140
+ result = op(df, scalar)
141
+ expected = pd.DataFrame({"A": op(data, scalar)})
142
+ tm.assert_frame_equal(result, expected)
143
+
144
+
145
+ def test_series(data, all_arithmetic_operators):
146
+ data, scalar = data
147
+ op = tm.get_op_from_name(all_arithmetic_operators)
148
+ check_skip(data, all_arithmetic_operators)
149
+
150
+ ser = pd.Series(data)
151
+
152
+ others = [
153
+ scalar,
154
+ np.array([scalar] * len(data), dtype=data.dtype.numpy_dtype),
155
+ pd.array([scalar] * len(data), dtype=data.dtype),
156
+ pd.Series([scalar] * len(data), dtype=data.dtype),
157
+ ]
158
+
159
+ for other in others:
160
+ if is_bool_not_implemented(data, all_arithmetic_operators):
161
+ msg = "operator '.*' not implemented for bool dtypes"
162
+ with pytest.raises(NotImplementedError, match=msg):
163
+ op(ser, other)
164
+
165
+ else:
166
+ result = op(ser, other)
167
+ expected = pd.Series(op(data, other))
168
+ tm.assert_series_equal(result, expected)
169
+
170
+
171
+ # Test generic characteristics / errors
172
+ # -----------------------------------------------------------------------------
173
+
174
+
175
+ def test_error_invalid_object(data, all_arithmetic_operators):
176
+ data, _ = data
177
+
178
+ op = all_arithmetic_operators
179
+ opa = getattr(data, op)
180
+
181
+ # 2d -> return NotImplemented
182
+ result = opa(pd.DataFrame({"A": data}))
183
+ assert result is NotImplemented
184
+
185
+ msg = r"can only perform ops with 1-d structures"
186
+ with pytest.raises(NotImplementedError, match=msg):
187
+ opa(np.arange(len(data)).reshape(-1, len(data)))
188
+
189
+
190
+ def test_error_len_mismatch(data, all_arithmetic_operators):
191
+ # operating with a list-like with non-matching length raises
192
+ data, scalar = data
193
+ op = tm.get_op_from_name(all_arithmetic_operators)
194
+
195
+ other = [scalar] * (len(data) - 1)
196
+
197
+ err = ValueError
198
+ msg = "|".join(
199
+ [
200
+ r"operands could not be broadcast together with shapes \(3,\) \(4,\)",
201
+ r"operands could not be broadcast together with shapes \(4,\) \(3,\)",
202
+ ]
203
+ )
204
+ if data.dtype.kind == "b" and all_arithmetic_operators.strip("_") in [
205
+ "sub",
206
+ "rsub",
207
+ ]:
208
+ err = TypeError
209
+ msg = (
210
+ r"numpy boolean subtract, the `\-` operator, is not supported, use "
211
+ r"the bitwise_xor, the `\^` operator, or the logical_xor function instead"
212
+ )
213
+ elif is_bool_not_implemented(data, all_arithmetic_operators):
214
+ msg = "operator '.*' not implemented for bool dtypes"
215
+ err = NotImplementedError
216
+
217
+ for other in [other, np.array(other)]:
218
+ with pytest.raises(err, match=msg):
219
+ op(data, other)
220
+
221
+ s = pd.Series(data)
222
+ with pytest.raises(err, match=msg):
223
+ op(s, other)
224
+
225
+
226
+ @pytest.mark.parametrize("op", ["__neg__", "__abs__", "__invert__"])
227
+ def test_unary_op_does_not_propagate_mask(data, op):
228
+ # https://github.com/pandas-dev/pandas/issues/39943
229
+ data, _ = data
230
+ ser = pd.Series(data)
231
+
232
+ if op == "__invert__" and data.dtype.kind == "f":
233
+ # we follow numpy in raising
234
+ msg = "ufunc 'invert' not supported for the input types"
235
+ with pytest.raises(TypeError, match=msg):
236
+ getattr(ser, op)()
237
+ with pytest.raises(TypeError, match=msg):
238
+ getattr(data, op)()
239
+ with pytest.raises(TypeError, match=msg):
240
+ # Check that this is still the numpy behavior
241
+ getattr(data._data, op)()
242
+
243
+ return
244
+
245
+ result = getattr(ser, op)()
246
+ expected = result.copy(deep=True)
247
+ ser[0] = None
248
+ tm.assert_series_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_arrow_compat.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+
7
+ pytestmark = pytest.mark.filterwarnings(
8
+ "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"
9
+ )
10
+
11
+ pa = pytest.importorskip("pyarrow")
12
+
13
+ from pandas.core.arrays.arrow._arrow_utils import pyarrow_array_to_numpy_and_mask
14
+
15
+ arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
16
+ arrays += [pd.array([0.1, 0.2, 0.3, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES]
17
+ arrays += [pd.array([True, False, True, None], dtype="boolean")]
18
+
19
+
20
+ @pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])
21
+ def data(request):
22
+ """
23
+ Fixture returning parametrized array from given dtype, including integer,
24
+ float and boolean
25
+ """
26
+ return request.param
27
+
28
+
29
+ def test_arrow_array(data):
30
+ arr = pa.array(data)
31
+ expected = pa.array(
32
+ data.to_numpy(object, na_value=None),
33
+ type=pa.from_numpy_dtype(data.dtype.numpy_dtype),
34
+ )
35
+ assert arr.equals(expected)
36
+
37
+
38
+ def test_arrow_roundtrip(data):
39
+ df = pd.DataFrame({"a": data})
40
+ table = pa.table(df)
41
+ assert table.field("a").type == str(data.dtype.numpy_dtype)
42
+
43
+ result = table.to_pandas()
44
+ assert result["a"].dtype == data.dtype
45
+ tm.assert_frame_equal(result, df)
46
+
47
+
48
+ def test_dataframe_from_arrow_types_mapper():
49
+ def types_mapper(arrow_type):
50
+ if pa.types.is_boolean(arrow_type):
51
+ return pd.BooleanDtype()
52
+ elif pa.types.is_integer(arrow_type):
53
+ return pd.Int64Dtype()
54
+
55
+ bools_array = pa.array([True, None, False], type=pa.bool_())
56
+ ints_array = pa.array([1, None, 2], type=pa.int64())
57
+ small_ints_array = pa.array([-1, 0, 7], type=pa.int8())
58
+ record_batch = pa.RecordBatch.from_arrays(
59
+ [bools_array, ints_array, small_ints_array], ["bools", "ints", "small_ints"]
60
+ )
61
+ result = record_batch.to_pandas(types_mapper=types_mapper)
62
+ bools = pd.Series([True, None, False], dtype="boolean")
63
+ ints = pd.Series([1, None, 2], dtype="Int64")
64
+ small_ints = pd.Series([-1, 0, 7], dtype="Int64")
65
+ expected = pd.DataFrame({"bools": bools, "ints": ints, "small_ints": small_ints})
66
+ tm.assert_frame_equal(result, expected)
67
+
68
+
69
+ def test_arrow_load_from_zero_chunks(data):
70
+ # GH-41040
71
+
72
+ df = pd.DataFrame({"a": data[0:0]})
73
+ table = pa.table(df)
74
+ assert table.field("a").type == str(data.dtype.numpy_dtype)
75
+ table = pa.table(
76
+ [pa.chunked_array([], type=table.field("a").type)], schema=table.schema
77
+ )
78
+ result = table.to_pandas()
79
+ assert result["a"].dtype == data.dtype
80
+ tm.assert_frame_equal(result, df)
81
+
82
+
83
+ def test_arrow_from_arrow_uint():
84
+ # https://github.com/pandas-dev/pandas/issues/31896
85
+ # possible mismatch in types
86
+
87
+ dtype = pd.UInt32Dtype()
88
+ result = dtype.__from_arrow__(pa.array([1, 2, 3, 4, None], type="int64"))
89
+ expected = pd.array([1, 2, 3, 4, None], dtype="UInt32")
90
+
91
+ tm.assert_extension_array_equal(result, expected)
92
+
93
+
94
+ def test_arrow_sliced(data):
95
+ # https://github.com/pandas-dev/pandas/issues/38525
96
+
97
+ df = pd.DataFrame({"a": data})
98
+ table = pa.table(df)
99
+ result = table.slice(2, None).to_pandas()
100
+ expected = df.iloc[2:].reset_index(drop=True)
101
+ tm.assert_frame_equal(result, expected)
102
+
103
+ # no missing values
104
+ df2 = df.fillna(data[0])
105
+ table = pa.table(df2)
106
+ result = table.slice(2, None).to_pandas()
107
+ expected = df2.iloc[2:].reset_index(drop=True)
108
+ tm.assert_frame_equal(result, expected)
109
+
110
+
111
+ @pytest.fixture
112
+ def np_dtype_to_arrays(any_real_numpy_dtype):
113
+ """
114
+ Fixture returning actual and expected dtype, pandas and numpy arrays and
115
+ mask from a given numpy dtype
116
+ """
117
+ np_dtype = np.dtype(any_real_numpy_dtype)
118
+ pa_type = pa.from_numpy_dtype(np_dtype)
119
+
120
+ # None ensures the creation of a bitmask buffer.
121
+ pa_array = pa.array([0, 1, 2, None], type=pa_type)
122
+ # Since masked Arrow buffer slots are not required to contain a specific
123
+ # value, assert only the first three values of the created np.array
124
+ np_expected = np.array([0, 1, 2], dtype=np_dtype)
125
+ mask_expected = np.array([True, True, True, False])
126
+ return np_dtype, pa_array, np_expected, mask_expected
127
+
128
+
129
+ def test_pyarrow_array_to_numpy_and_mask(np_dtype_to_arrays):
130
+ """
131
+ Test conversion from pyarrow array to numpy array.
132
+
133
+ Modifies the pyarrow buffer to contain padding and offset, which are
134
+ considered valid buffers by pyarrow.
135
+
136
+ Also tests empty pyarrow arrays with non empty buffers.
137
+ See https://github.com/pandas-dev/pandas/issues/40896
138
+ """
139
+ np_dtype, pa_array, np_expected, mask_expected = np_dtype_to_arrays
140
+ data, mask = pyarrow_array_to_numpy_and_mask(pa_array, np_dtype)
141
+ tm.assert_numpy_array_equal(data[:3], np_expected)
142
+ tm.assert_numpy_array_equal(mask, mask_expected)
143
+
144
+ mask_buffer = pa_array.buffers()[0]
145
+ data_buffer = pa_array.buffers()[1]
146
+ data_buffer_bytes = pa_array.buffers()[1].to_pybytes()
147
+
148
+ # Add trailing padding to the buffer.
149
+ data_buffer_trail = pa.py_buffer(data_buffer_bytes + b"\x00")
150
+ pa_array_trail = pa.Array.from_buffers(
151
+ type=pa_array.type,
152
+ length=len(pa_array),
153
+ buffers=[mask_buffer, data_buffer_trail],
154
+ offset=pa_array.offset,
155
+ )
156
+ pa_array_trail.validate()
157
+ data, mask = pyarrow_array_to_numpy_and_mask(pa_array_trail, np_dtype)
158
+ tm.assert_numpy_array_equal(data[:3], np_expected)
159
+ tm.assert_numpy_array_equal(mask, mask_expected)
160
+
161
+ # Add offset to the buffer.
162
+ offset = b"\x00" * (pa_array.type.bit_width // 8)
163
+ data_buffer_offset = pa.py_buffer(offset + data_buffer_bytes)
164
+ mask_buffer_offset = pa.py_buffer(b"\x0E")
165
+ pa_array_offset = pa.Array.from_buffers(
166
+ type=pa_array.type,
167
+ length=len(pa_array),
168
+ buffers=[mask_buffer_offset, data_buffer_offset],
169
+ offset=pa_array.offset + 1,
170
+ )
171
+ pa_array_offset.validate()
172
+ data, mask = pyarrow_array_to_numpy_and_mask(pa_array_offset, np_dtype)
173
+ tm.assert_numpy_array_equal(data[:3], np_expected)
174
+ tm.assert_numpy_array_equal(mask, mask_expected)
175
+
176
+ # Empty array
177
+ np_expected_empty = np.array([], dtype=np_dtype)
178
+ mask_expected_empty = np.array([], dtype=np.bool_)
179
+
180
+ pa_array_offset = pa.Array.from_buffers(
181
+ type=pa_array.type,
182
+ length=0,
183
+ buffers=[mask_buffer, data_buffer],
184
+ offset=pa_array.offset,
185
+ )
186
+ pa_array_offset.validate()
187
+ data, mask = pyarrow_array_to_numpy_and_mask(pa_array_offset, np_dtype)
188
+ tm.assert_numpy_array_equal(data[:3], np_expected_empty)
189
+ tm.assert_numpy_array_equal(mask, mask_expected_empty)
190
+
191
+
192
+ @pytest.mark.parametrize(
193
+ "arr", [pa.nulls(10), pa.chunked_array([pa.nulls(4), pa.nulls(6)])]
194
+ )
195
+ def test_from_arrow_null(data, arr):
196
+ res = data.dtype.__from_arrow__(arr)
197
+ assert res.isna().all()
198
+ assert len(res) == 10
199
+
200
+
201
+ def test_from_arrow_type_error(data):
202
+ # ensure that __from_arrow__ returns a TypeError when getting a wrong
203
+ # array type
204
+
205
+ arr = pa.array(data).cast("string")
206
+ with pytest.raises(TypeError, match=None):
207
+ # we don't test the exact error message, only the fact that it raises
208
+ # a TypeError is relevant
209
+ data.dtype.__from_arrow__(arr)
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_function.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.core.dtypes.common import is_integer_dtype
5
+
6
+ import pandas as pd
7
+ import pandas._testing as tm
8
+ from pandas.core.arrays import BaseMaskedArray
9
+
10
+ arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
11
+ arrays += [
12
+ pd.array([0.141, -0.268, 5.895, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES
13
+ ]
14
+
15
+
16
+ @pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])
17
+ def data(request):
18
+ """
19
+ Fixture returning parametrized 'data' array with different integer and
20
+ floating point types
21
+ """
22
+ return request.param
23
+
24
+
25
+ @pytest.fixture()
26
+ def numpy_dtype(data):
27
+ """
28
+ Fixture returning numpy dtype from 'data' input array.
29
+ """
30
+ # For integer dtype, the numpy conversion must be done to float
31
+ if is_integer_dtype(data):
32
+ numpy_dtype = float
33
+ else:
34
+ numpy_dtype = data.dtype.type
35
+ return numpy_dtype
36
+
37
+
38
+ def test_round(data, numpy_dtype):
39
+ # No arguments
40
+ result = data.round()
41
+ expected = pd.array(
42
+ np.round(data.to_numpy(dtype=numpy_dtype, na_value=None)), dtype=data.dtype
43
+ )
44
+ tm.assert_extension_array_equal(result, expected)
45
+
46
+ # Decimals argument
47
+ result = data.round(decimals=2)
48
+ expected = pd.array(
49
+ np.round(data.to_numpy(dtype=numpy_dtype, na_value=None), decimals=2),
50
+ dtype=data.dtype,
51
+ )
52
+ tm.assert_extension_array_equal(result, expected)
53
+
54
+
55
+ def test_tolist(data):
56
+ result = data.tolist()
57
+ expected = list(data)
58
+ tm.assert_equal(result, expected)
59
+
60
+
61
+ def test_to_numpy():
62
+ # GH#56991
63
+
64
+ class MyStringArray(BaseMaskedArray):
65
+ dtype = pd.StringDtype()
66
+ _dtype_cls = pd.StringDtype
67
+ _internal_fill_value = pd.NA
68
+
69
+ arr = MyStringArray(
70
+ values=np.array(["a", "b", "c"]), mask=np.array([False, True, False])
71
+ )
72
+ result = arr.to_numpy()
73
+ expected = np.array(["a", pd.NA, "c"])
74
+ tm.assert_numpy_array_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_indexing.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+
8
+
9
+ class TestSetitemValidation:
10
+ def _check_setitem_invalid(self, arr, invalid):
11
+ msg = f"Invalid value '{str(invalid)}' for dtype {arr.dtype}"
12
+ msg = re.escape(msg)
13
+ with pytest.raises(TypeError, match=msg):
14
+ arr[0] = invalid
15
+
16
+ with pytest.raises(TypeError, match=msg):
17
+ arr[:] = invalid
18
+
19
+ with pytest.raises(TypeError, match=msg):
20
+ arr[[0]] = invalid
21
+
22
+ # FIXME: don't leave commented-out
23
+ # with pytest.raises(TypeError):
24
+ # arr[[0]] = [invalid]
25
+
26
+ # with pytest.raises(TypeError):
27
+ # arr[[0]] = np.array([invalid], dtype=object)
28
+
29
+ # Series non-coercion, behavior subject to change
30
+ ser = pd.Series(arr)
31
+ with pytest.raises(TypeError, match=msg):
32
+ ser[0] = invalid
33
+ # TODO: so, so many other variants of this...
34
+
35
+ _invalid_scalars = [
36
+ 1 + 2j,
37
+ "True",
38
+ "1",
39
+ "1.0",
40
+ pd.NaT,
41
+ np.datetime64("NaT"),
42
+ np.timedelta64("NaT"),
43
+ ]
44
+
45
+ @pytest.mark.parametrize(
46
+ "invalid", _invalid_scalars + [1, 1.0, np.int64(1), np.float64(1)]
47
+ )
48
+ def test_setitem_validation_scalar_bool(self, invalid):
49
+ arr = pd.array([True, False, None], dtype="boolean")
50
+ self._check_setitem_invalid(arr, invalid)
51
+
52
+ @pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)])
53
+ def test_setitem_validation_scalar_int(self, invalid, any_int_ea_dtype):
54
+ arr = pd.array([1, 2, None], dtype=any_int_ea_dtype)
55
+ self._check_setitem_invalid(arr, invalid)
56
+
57
+ @pytest.mark.parametrize("invalid", _invalid_scalars + [True])
58
+ def test_setitem_validation_scalar_float(self, invalid, float_ea_dtype):
59
+ arr = pd.array([1, 2, None], dtype=float_ea_dtype)
60
+ self._check_setitem_invalid(arr, invalid)
venv/lib/python3.10/site-packages/pandas/tests/arrays/masked_shared.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests shared by MaskedArray subclasses.
3
+ """
4
+ import numpy as np
5
+ import pytest
6
+
7
+ import pandas as pd
8
+ import pandas._testing as tm
9
+ from pandas.tests.extension.base import BaseOpsUtil
10
+
11
+
12
+ class ComparisonOps(BaseOpsUtil):
13
+ def _compare_other(self, data, op, other):
14
+ # array
15
+ result = pd.Series(op(data, other))
16
+ expected = pd.Series(op(data._data, other), dtype="boolean")
17
+
18
+ # fill the nan locations
19
+ expected[data._mask] = pd.NA
20
+
21
+ tm.assert_series_equal(result, expected)
22
+
23
+ # series
24
+ ser = pd.Series(data)
25
+ result = op(ser, other)
26
+
27
+ # Set nullable dtype here to avoid upcasting when setting to pd.NA below
28
+ expected = op(pd.Series(data._data), other).astype("boolean")
29
+
30
+ # fill the nan locations
31
+ expected[data._mask] = pd.NA
32
+
33
+ tm.assert_series_equal(result, expected)
34
+
35
+ # subclass will override to parametrize 'other'
36
+ def test_scalar(self, other, comparison_op, dtype):
37
+ op = comparison_op
38
+ left = pd.array([1, 0, None], dtype=dtype)
39
+
40
+ result = op(left, other)
41
+
42
+ if other is pd.NA:
43
+ expected = pd.array([None, None, None], dtype="boolean")
44
+ else:
45
+ values = op(left._data, other)
46
+ expected = pd.arrays.BooleanArray(values, left._mask, copy=True)
47
+ tm.assert_extension_array_equal(result, expected)
48
+
49
+ # ensure we haven't mutated anything inplace
50
+ result[0] = pd.NA
51
+ tm.assert_extension_array_equal(left, pd.array([1, 0, None], dtype=dtype))
52
+
53
+
54
+ class NumericOps:
55
+ # Shared by IntegerArray and FloatingArray, not BooleanArray
56
+
57
+ def test_searchsorted_nan(self, dtype):
58
+ # The base class casts to object dtype, for which searchsorted returns
59
+ # 0 from the left and 10 from the right.
60
+ arr = pd.array(range(10), dtype=dtype)
61
+
62
+ assert arr.searchsorted(np.nan, side="left") == 10
63
+ assert arr.searchsorted(np.nan, side="right") == 10
64
+
65
+ def test_no_shared_mask(self, data):
66
+ result = data + 1
67
+ assert not tm.shares_memory(result, data)
68
+
69
+ def test_array(self, comparison_op, dtype):
70
+ op = comparison_op
71
+
72
+ left = pd.array([0, 1, 2, None, None, None], dtype=dtype)
73
+ right = pd.array([0, 1, None, 0, 1, None], dtype=dtype)
74
+
75
+ result = op(left, right)
76
+ values = op(left._data, right._data)
77
+ mask = left._mask | right._mask
78
+
79
+ expected = pd.arrays.BooleanArray(values, mask)
80
+ tm.assert_extension_array_equal(result, expected)
81
+
82
+ # ensure we haven't mutated anything inplace
83
+ result[0] = pd.NA
84
+ tm.assert_extension_array_equal(
85
+ left, pd.array([0, 1, 2, None, None, None], dtype=dtype)
86
+ )
87
+ tm.assert_extension_array_equal(
88
+ right, pd.array([0, 1, None, 0, 1, None], dtype=dtype)
89
+ )
90
+
91
+ def test_compare_with_booleanarray(self, comparison_op, dtype):
92
+ op = comparison_op
93
+
94
+ left = pd.array([True, False, None] * 3, dtype="boolean")
95
+ right = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype=dtype)
96
+ other = pd.array([False] * 3 + [True] * 3 + [None] * 3, dtype="boolean")
97
+
98
+ expected = op(left, other)
99
+ result = op(left, right)
100
+ tm.assert_extension_array_equal(result, expected)
101
+
102
+ # reversed op
103
+ expected = op(other, left)
104
+ result = op(right, left)
105
+ tm.assert_extension_array_equal(result, expected)
106
+
107
+ def test_compare_to_string(self, dtype):
108
+ # GH#28930
109
+ ser = pd.Series([1, None], dtype=dtype)
110
+ result = ser == "a"
111
+ expected = pd.Series([False, pd.NA], dtype="boolean")
112
+
113
+ tm.assert_series_equal(result, expected)
114
+
115
+ def test_ufunc_with_out(self, dtype):
116
+ arr = pd.array([1, 2, 3], dtype=dtype)
117
+ arr2 = pd.array([1, 2, pd.NA], dtype=dtype)
118
+
119
+ mask = arr == arr
120
+ mask2 = arr2 == arr2
121
+
122
+ result = np.zeros(3, dtype=bool)
123
+ result |= mask
124
+ # If MaskedArray.__array_ufunc__ handled "out" appropriately,
125
+ # `result` should still be an ndarray.
126
+ assert isinstance(result, np.ndarray)
127
+ assert result.all()
128
+
129
+ # result |= mask worked because mask could be cast losslessly to
130
+ # boolean ndarray. mask2 can't, so this raises
131
+ result = np.zeros(3, dtype=bool)
132
+ msg = "Specify an appropriate 'na_value' for this dtype"
133
+ with pytest.raises(ValueError, match=msg):
134
+ result |= mask2
135
+
136
+ # addition
137
+ res = np.add(arr, arr2)
138
+ expected = pd.array([2, 4, pd.NA], dtype=dtype)
139
+ tm.assert_extension_array_equal(res, expected)
140
+
141
+ # when passing out=arr, we will modify 'arr' inplace.
142
+ res = np.add(arr, arr2, out=arr)
143
+ assert res is arr
144
+ tm.assert_extension_array_equal(res, expected)
145
+ tm.assert_extension_array_equal(arr, expected)
146
+
147
+ def test_mul_td64_array(self, dtype):
148
+ # GH#45622
149
+ arr = pd.array([1, 2, pd.NA], dtype=dtype)
150
+ other = np.arange(3, dtype=np.int64).view("m8[ns]")
151
+
152
+ result = arr * other
153
+ expected = pd.array([pd.Timedelta(0), pd.Timedelta(2), pd.NaT])
154
+ tm.assert_extension_array_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/test_array.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import decimal
3
+ import re
4
+
5
+ import numpy as np
6
+ import pytest
7
+ import pytz
8
+
9
+ import pandas as pd
10
+ import pandas._testing as tm
11
+ from pandas.api.extensions import register_extension_dtype
12
+ from pandas.arrays import (
13
+ BooleanArray,
14
+ DatetimeArray,
15
+ FloatingArray,
16
+ IntegerArray,
17
+ IntervalArray,
18
+ SparseArray,
19
+ TimedeltaArray,
20
+ )
21
+ from pandas.core.arrays import (
22
+ NumpyExtensionArray,
23
+ period_array,
24
+ )
25
+ from pandas.tests.extension.decimal import (
26
+ DecimalArray,
27
+ DecimalDtype,
28
+ to_decimal,
29
+ )
30
+
31
+
32
+ @pytest.mark.parametrize("dtype_unit", ["M8[h]", "M8[m]", "m8[h]", "M8[m]"])
33
+ def test_dt64_array(dtype_unit):
34
+ # PR 53817
35
+ dtype_var = np.dtype(dtype_unit)
36
+ msg = (
37
+ r"datetime64 and timedelta64 dtype resolutions other than "
38
+ r"'s', 'ms', 'us', and 'ns' are deprecated. "
39
+ r"In future releases passing unsupported resolutions will "
40
+ r"raise an exception."
41
+ )
42
+ with tm.assert_produces_warning(FutureWarning, match=re.escape(msg)):
43
+ pd.array([], dtype=dtype_var)
44
+
45
+
46
+ @pytest.mark.parametrize(
47
+ "data, dtype, expected",
48
+ [
49
+ # Basic NumPy defaults.
50
+ ([], None, FloatingArray._from_sequence([], dtype="Float64")),
51
+ ([1, 2], None, IntegerArray._from_sequence([1, 2], dtype="Int64")),
52
+ ([1, 2], object, NumpyExtensionArray(np.array([1, 2], dtype=object))),
53
+ (
54
+ [1, 2],
55
+ np.dtype("float32"),
56
+ NumpyExtensionArray(np.array([1.0, 2.0], dtype=np.dtype("float32"))),
57
+ ),
58
+ (
59
+ np.array([], dtype=object),
60
+ None,
61
+ NumpyExtensionArray(np.array([], dtype=object)),
62
+ ),
63
+ (
64
+ np.array([1, 2], dtype="int64"),
65
+ None,
66
+ IntegerArray._from_sequence([1, 2], dtype="Int64"),
67
+ ),
68
+ (
69
+ np.array([1.0, 2.0], dtype="float64"),
70
+ None,
71
+ FloatingArray._from_sequence([1.0, 2.0], dtype="Float64"),
72
+ ),
73
+ # String alias passes through to NumPy
74
+ ([1, 2], "float32", NumpyExtensionArray(np.array([1, 2], dtype="float32"))),
75
+ ([1, 2], "int64", NumpyExtensionArray(np.array([1, 2], dtype=np.int64))),
76
+ # GH#44715 FloatingArray does not support float16, so fall
77
+ # back to NumpyExtensionArray
78
+ (
79
+ np.array([1, 2], dtype=np.float16),
80
+ None,
81
+ NumpyExtensionArray(np.array([1, 2], dtype=np.float16)),
82
+ ),
83
+ # idempotency with e.g. pd.array(pd.array([1, 2], dtype="int64"))
84
+ (
85
+ NumpyExtensionArray(np.array([1, 2], dtype=np.int32)),
86
+ None,
87
+ NumpyExtensionArray(np.array([1, 2], dtype=np.int32)),
88
+ ),
89
+ # Period alias
90
+ (
91
+ [pd.Period("2000", "D"), pd.Period("2001", "D")],
92
+ "Period[D]",
93
+ period_array(["2000", "2001"], freq="D"),
94
+ ),
95
+ # Period dtype
96
+ (
97
+ [pd.Period("2000", "D")],
98
+ pd.PeriodDtype("D"),
99
+ period_array(["2000"], freq="D"),
100
+ ),
101
+ # Datetime (naive)
102
+ (
103
+ [1, 2],
104
+ np.dtype("datetime64[ns]"),
105
+ DatetimeArray._from_sequence(
106
+ np.array([1, 2], dtype="M8[ns]"), dtype="M8[ns]"
107
+ ),
108
+ ),
109
+ (
110
+ [1, 2],
111
+ np.dtype("datetime64[s]"),
112
+ DatetimeArray._from_sequence(
113
+ np.array([1, 2], dtype="M8[s]"), dtype="M8[s]"
114
+ ),
115
+ ),
116
+ (
117
+ np.array([1, 2], dtype="datetime64[ns]"),
118
+ None,
119
+ DatetimeArray._from_sequence(
120
+ np.array([1, 2], dtype="M8[ns]"), dtype="M8[ns]"
121
+ ),
122
+ ),
123
+ (
124
+ pd.DatetimeIndex(["2000", "2001"]),
125
+ np.dtype("datetime64[ns]"),
126
+ DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[ns]"),
127
+ ),
128
+ (
129
+ pd.DatetimeIndex(["2000", "2001"]),
130
+ None,
131
+ DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[ns]"),
132
+ ),
133
+ (
134
+ ["2000", "2001"],
135
+ np.dtype("datetime64[ns]"),
136
+ DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[ns]"),
137
+ ),
138
+ # Datetime (tz-aware)
139
+ (
140
+ ["2000", "2001"],
141
+ pd.DatetimeTZDtype(tz="CET"),
142
+ DatetimeArray._from_sequence(
143
+ ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz="CET")
144
+ ),
145
+ ),
146
+ # Timedelta
147
+ (
148
+ ["1h", "2h"],
149
+ np.dtype("timedelta64[ns]"),
150
+ TimedeltaArray._from_sequence(["1h", "2h"], dtype="m8[ns]"),
151
+ ),
152
+ (
153
+ pd.TimedeltaIndex(["1h", "2h"]),
154
+ np.dtype("timedelta64[ns]"),
155
+ TimedeltaArray._from_sequence(["1h", "2h"], dtype="m8[ns]"),
156
+ ),
157
+ (
158
+ np.array([1, 2], dtype="m8[s]"),
159
+ np.dtype("timedelta64[s]"),
160
+ TimedeltaArray._from_sequence(
161
+ np.array([1, 2], dtype="m8[s]"), dtype="m8[s]"
162
+ ),
163
+ ),
164
+ (
165
+ pd.TimedeltaIndex(["1h", "2h"]),
166
+ None,
167
+ TimedeltaArray._from_sequence(["1h", "2h"], dtype="m8[ns]"),
168
+ ),
169
+ (
170
+ # preserve non-nano, i.e. don't cast to NumpyExtensionArray
171
+ TimedeltaArray._simple_new(
172
+ np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
173
+ ),
174
+ None,
175
+ TimedeltaArray._simple_new(
176
+ np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
177
+ ),
178
+ ),
179
+ (
180
+ # preserve non-nano, i.e. don't cast to NumpyExtensionArray
181
+ TimedeltaArray._simple_new(
182
+ np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
183
+ ),
184
+ np.dtype("m8[s]"),
185
+ TimedeltaArray._simple_new(
186
+ np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
187
+ ),
188
+ ),
189
+ # Category
190
+ (["a", "b"], "category", pd.Categorical(["a", "b"])),
191
+ (
192
+ ["a", "b"],
193
+ pd.CategoricalDtype(None, ordered=True),
194
+ pd.Categorical(["a", "b"], ordered=True),
195
+ ),
196
+ # Interval
197
+ (
198
+ [pd.Interval(1, 2), pd.Interval(3, 4)],
199
+ "interval",
200
+ IntervalArray.from_tuples([(1, 2), (3, 4)]),
201
+ ),
202
+ # Sparse
203
+ ([0, 1], "Sparse[int64]", SparseArray([0, 1], dtype="int64")),
204
+ # IntegerNA
205
+ ([1, None], "Int16", pd.array([1, None], dtype="Int16")),
206
+ (
207
+ pd.Series([1, 2]),
208
+ None,
209
+ NumpyExtensionArray(np.array([1, 2], dtype=np.int64)),
210
+ ),
211
+ # String
212
+ (
213
+ ["a", None],
214
+ "string",
215
+ pd.StringDtype()
216
+ .construct_array_type()
217
+ ._from_sequence(["a", None], dtype=pd.StringDtype()),
218
+ ),
219
+ (
220
+ ["a", None],
221
+ pd.StringDtype(),
222
+ pd.StringDtype()
223
+ .construct_array_type()
224
+ ._from_sequence(["a", None], dtype=pd.StringDtype()),
225
+ ),
226
+ # Boolean
227
+ (
228
+ [True, None],
229
+ "boolean",
230
+ BooleanArray._from_sequence([True, None], dtype="boolean"),
231
+ ),
232
+ (
233
+ [True, None],
234
+ pd.BooleanDtype(),
235
+ BooleanArray._from_sequence([True, None], dtype="boolean"),
236
+ ),
237
+ # Index
238
+ (pd.Index([1, 2]), None, NumpyExtensionArray(np.array([1, 2], dtype=np.int64))),
239
+ # Series[EA] returns the EA
240
+ (
241
+ pd.Series(pd.Categorical(["a", "b"], categories=["a", "b", "c"])),
242
+ None,
243
+ pd.Categorical(["a", "b"], categories=["a", "b", "c"]),
244
+ ),
245
+ # "3rd party" EAs work
246
+ ([decimal.Decimal(0), decimal.Decimal(1)], "decimal", to_decimal([0, 1])),
247
+ # pass an ExtensionArray, but a different dtype
248
+ (
249
+ period_array(["2000", "2001"], freq="D"),
250
+ "category",
251
+ pd.Categorical([pd.Period("2000", "D"), pd.Period("2001", "D")]),
252
+ ),
253
+ ],
254
+ )
255
+ def test_array(data, dtype, expected):
256
+ result = pd.array(data, dtype=dtype)
257
+ tm.assert_equal(result, expected)
258
+
259
+
260
+ def test_array_copy():
261
+ a = np.array([1, 2])
262
+ # default is to copy
263
+ b = pd.array(a, dtype=a.dtype)
264
+ assert not tm.shares_memory(a, b)
265
+
266
+ # copy=True
267
+ b = pd.array(a, dtype=a.dtype, copy=True)
268
+ assert not tm.shares_memory(a, b)
269
+
270
+ # copy=False
271
+ b = pd.array(a, dtype=a.dtype, copy=False)
272
+ assert tm.shares_memory(a, b)
273
+
274
+
275
+ cet = pytz.timezone("CET")
276
+
277
+
278
+ @pytest.mark.parametrize(
279
+ "data, expected",
280
+ [
281
+ # period
282
+ (
283
+ [pd.Period("2000", "D"), pd.Period("2001", "D")],
284
+ period_array(["2000", "2001"], freq="D"),
285
+ ),
286
+ # interval
287
+ ([pd.Interval(0, 1), pd.Interval(1, 2)], IntervalArray.from_breaks([0, 1, 2])),
288
+ # datetime
289
+ (
290
+ [pd.Timestamp("2000"), pd.Timestamp("2001")],
291
+ DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[ns]"),
292
+ ),
293
+ (
294
+ [datetime.datetime(2000, 1, 1), datetime.datetime(2001, 1, 1)],
295
+ DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[ns]"),
296
+ ),
297
+ (
298
+ np.array([1, 2], dtype="M8[ns]"),
299
+ DatetimeArray._from_sequence(np.array([1, 2], dtype="M8[ns]")),
300
+ ),
301
+ (
302
+ np.array([1, 2], dtype="M8[us]"),
303
+ DatetimeArray._simple_new(
304
+ np.array([1, 2], dtype="M8[us]"), dtype=np.dtype("M8[us]")
305
+ ),
306
+ ),
307
+ # datetimetz
308
+ (
309
+ [pd.Timestamp("2000", tz="CET"), pd.Timestamp("2001", tz="CET")],
310
+ DatetimeArray._from_sequence(
311
+ ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz="CET", unit="ns")
312
+ ),
313
+ ),
314
+ (
315
+ [
316
+ datetime.datetime(2000, 1, 1, tzinfo=cet),
317
+ datetime.datetime(2001, 1, 1, tzinfo=cet),
318
+ ],
319
+ DatetimeArray._from_sequence(
320
+ ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz=cet, unit="ns")
321
+ ),
322
+ ),
323
+ # timedelta
324
+ (
325
+ [pd.Timedelta("1h"), pd.Timedelta("2h")],
326
+ TimedeltaArray._from_sequence(["1h", "2h"], dtype="m8[ns]"),
327
+ ),
328
+ (
329
+ np.array([1, 2], dtype="m8[ns]"),
330
+ TimedeltaArray._from_sequence(np.array([1, 2], dtype="m8[ns]")),
331
+ ),
332
+ (
333
+ np.array([1, 2], dtype="m8[us]"),
334
+ TimedeltaArray._from_sequence(np.array([1, 2], dtype="m8[us]")),
335
+ ),
336
+ # integer
337
+ ([1, 2], IntegerArray._from_sequence([1, 2], dtype="Int64")),
338
+ ([1, None], IntegerArray._from_sequence([1, None], dtype="Int64")),
339
+ ([1, pd.NA], IntegerArray._from_sequence([1, pd.NA], dtype="Int64")),
340
+ ([1, np.nan], IntegerArray._from_sequence([1, np.nan], dtype="Int64")),
341
+ # float
342
+ ([0.1, 0.2], FloatingArray._from_sequence([0.1, 0.2], dtype="Float64")),
343
+ ([0.1, None], FloatingArray._from_sequence([0.1, pd.NA], dtype="Float64")),
344
+ ([0.1, np.nan], FloatingArray._from_sequence([0.1, pd.NA], dtype="Float64")),
345
+ ([0.1, pd.NA], FloatingArray._from_sequence([0.1, pd.NA], dtype="Float64")),
346
+ # integer-like float
347
+ ([1.0, 2.0], FloatingArray._from_sequence([1.0, 2.0], dtype="Float64")),
348
+ ([1.0, None], FloatingArray._from_sequence([1.0, pd.NA], dtype="Float64")),
349
+ ([1.0, np.nan], FloatingArray._from_sequence([1.0, pd.NA], dtype="Float64")),
350
+ ([1.0, pd.NA], FloatingArray._from_sequence([1.0, pd.NA], dtype="Float64")),
351
+ # mixed-integer-float
352
+ ([1, 2.0], FloatingArray._from_sequence([1.0, 2.0], dtype="Float64")),
353
+ (
354
+ [1, np.nan, 2.0],
355
+ FloatingArray._from_sequence([1.0, None, 2.0], dtype="Float64"),
356
+ ),
357
+ # string
358
+ (
359
+ ["a", "b"],
360
+ pd.StringDtype()
361
+ .construct_array_type()
362
+ ._from_sequence(["a", "b"], dtype=pd.StringDtype()),
363
+ ),
364
+ (
365
+ ["a", None],
366
+ pd.StringDtype()
367
+ .construct_array_type()
368
+ ._from_sequence(["a", None], dtype=pd.StringDtype()),
369
+ ),
370
+ # Boolean
371
+ ([True, False], BooleanArray._from_sequence([True, False], dtype="boolean")),
372
+ ([True, None], BooleanArray._from_sequence([True, None], dtype="boolean")),
373
+ ],
374
+ )
375
+ def test_array_inference(data, expected):
376
+ result = pd.array(data)
377
+ tm.assert_equal(result, expected)
378
+
379
+
380
+ @pytest.mark.parametrize(
381
+ "data",
382
+ [
383
+ # mix of frequencies
384
+ [pd.Period("2000", "D"), pd.Period("2001", "Y")],
385
+ # mix of closed
386
+ [pd.Interval(0, 1, closed="left"), pd.Interval(1, 2, closed="right")],
387
+ # Mix of timezones
388
+ [pd.Timestamp("2000", tz="CET"), pd.Timestamp("2000", tz="UTC")],
389
+ # Mix of tz-aware and tz-naive
390
+ [pd.Timestamp("2000", tz="CET"), pd.Timestamp("2000")],
391
+ np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")]),
392
+ ],
393
+ )
394
+ def test_array_inference_fails(data):
395
+ result = pd.array(data)
396
+ expected = NumpyExtensionArray(np.array(data, dtype=object))
397
+ tm.assert_extension_array_equal(result, expected)
398
+
399
+
400
+ @pytest.mark.parametrize("data", [np.array(0)])
401
+ def test_nd_raises(data):
402
+ with pytest.raises(ValueError, match="NumpyExtensionArray must be 1-dimensional"):
403
+ pd.array(data, dtype="int64")
404
+
405
+
406
+ def test_scalar_raises():
407
+ with pytest.raises(ValueError, match="Cannot pass scalar '1'"):
408
+ pd.array(1)
409
+
410
+
411
+ def test_dataframe_raises():
412
+ # GH#51167 don't accidentally cast to StringArray by doing inference on columns
413
+ df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
414
+ msg = "Cannot pass DataFrame to 'pandas.array'"
415
+ with pytest.raises(TypeError, match=msg):
416
+ pd.array(df)
417
+
418
+
419
+ def test_bounds_check():
420
+ # GH21796
421
+ with pytest.raises(
422
+ TypeError, match=r"cannot safely cast non-equivalent int(32|64) to uint16"
423
+ ):
424
+ pd.array([-1, 2, 3], dtype="UInt16")
425
+
426
+
427
+ # ---------------------------------------------------------------------------
428
+ # A couple dummy classes to ensure that Series and Indexes are unboxed before
429
+ # getting to the EA classes.
430
+
431
+
432
+ @register_extension_dtype
433
+ class DecimalDtype2(DecimalDtype):
434
+ name = "decimal2"
435
+
436
+ @classmethod
437
+ def construct_array_type(cls):
438
+ """
439
+ Return the array type associated with this dtype.
440
+
441
+ Returns
442
+ -------
443
+ type
444
+ """
445
+ return DecimalArray2
446
+
447
+
448
+ class DecimalArray2(DecimalArray):
449
+ @classmethod
450
+ def _from_sequence(cls, scalars, *, dtype=None, copy=False):
451
+ if isinstance(scalars, (pd.Series, pd.Index)):
452
+ raise TypeError("scalars should not be of type pd.Series or pd.Index")
453
+
454
+ return super()._from_sequence(scalars, dtype=dtype, copy=copy)
455
+
456
+
457
+ def test_array_unboxes(index_or_series):
458
+ box = index_or_series
459
+
460
+ data = box([decimal.Decimal("1"), decimal.Decimal("2")])
461
+ dtype = DecimalDtype2()
462
+ # make sure it works
463
+ with pytest.raises(
464
+ TypeError, match="scalars should not be of type pd.Series or pd.Index"
465
+ ):
466
+ DecimalArray2._from_sequence(data, dtype=dtype)
467
+
468
+ result = pd.array(data, dtype="decimal2")
469
+ expected = DecimalArray2._from_sequence(data.values, dtype=dtype)
470
+ tm.assert_equal(result, expected)
471
+
472
+
473
+ def test_array_to_numpy_na():
474
+ # GH#40638
475
+ arr = pd.array([pd.NA, 1], dtype="string[python]")
476
+ result = arr.to_numpy(na_value=True, dtype=bool)
477
+ expected = np.array([True, True])
478
+ tm.assert_numpy_array_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/test_datetimelike.py ADDED
@@ -0,0 +1,1340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import warnings
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas._libs import (
10
+ NaT,
11
+ OutOfBoundsDatetime,
12
+ Timestamp,
13
+ )
14
+ from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
15
+ from pandas.compat.numpy import np_version_gt2
16
+
17
+ import pandas as pd
18
+ from pandas import (
19
+ DatetimeIndex,
20
+ Period,
21
+ PeriodIndex,
22
+ TimedeltaIndex,
23
+ )
24
+ import pandas._testing as tm
25
+ from pandas.core.arrays import (
26
+ DatetimeArray,
27
+ NumpyExtensionArray,
28
+ PeriodArray,
29
+ TimedeltaArray,
30
+ )
31
+
32
+
33
+ # TODO: more freq variants
34
+ @pytest.fixture(params=["D", "B", "W", "ME", "QE", "YE"])
35
+ def freqstr(request):
36
+ """Fixture returning parametrized frequency in string format."""
37
+ return request.param
38
+
39
+
40
+ @pytest.fixture
41
+ def period_index(freqstr):
42
+ """
43
+ A fixture to provide PeriodIndex objects with different frequencies.
44
+
45
+ Most PeriodArray behavior is already tested in PeriodIndex tests,
46
+ so here we just test that the PeriodArray behavior matches
47
+ the PeriodIndex behavior.
48
+ """
49
+ # TODO: non-monotone indexes; NaTs, different start dates
50
+ with warnings.catch_warnings():
51
+ # suppress deprecation of Period[B]
52
+ warnings.filterwarnings(
53
+ "ignore", message="Period with BDay freq", category=FutureWarning
54
+ )
55
+ freqstr = freq_to_period_freqstr(1, freqstr)
56
+ pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
57
+ return pi
58
+
59
+
60
+ @pytest.fixture
61
+ def datetime_index(freqstr):
62
+ """
63
+ A fixture to provide DatetimeIndex objects with different frequencies.
64
+
65
+ Most DatetimeArray behavior is already tested in DatetimeIndex tests,
66
+ so here we just test that the DatetimeArray behavior matches
67
+ the DatetimeIndex behavior.
68
+ """
69
+ # TODO: non-monotone indexes; NaTs, different start dates, timezones
70
+ dti = pd.date_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
71
+ return dti
72
+
73
+
74
+ @pytest.fixture
75
+ def timedelta_index():
76
+ """
77
+ A fixture to provide TimedeltaIndex objects with different frequencies.
78
+ Most TimedeltaArray behavior is already tested in TimedeltaIndex tests,
79
+ so here we just test that the TimedeltaArray behavior matches
80
+ the TimedeltaIndex behavior.
81
+ """
82
+ # TODO: flesh this out
83
+ return TimedeltaIndex(["1 Day", "3 Hours", "NaT"])
84
+
85
+
86
+ class SharedTests:
87
+ index_cls: type[DatetimeIndex | PeriodIndex | TimedeltaIndex]
88
+
89
+ @pytest.fixture
90
+ def arr1d(self):
91
+ """Fixture returning DatetimeArray with daily frequency."""
92
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
93
+ if self.array_cls is PeriodArray:
94
+ arr = self.array_cls(data, freq="D")
95
+ else:
96
+ arr = self.index_cls(data, freq="D")._data
97
+ return arr
98
+
99
+ def test_compare_len1_raises(self, arr1d):
100
+ # make sure we raise when comparing with different lengths, specific
101
+ # to the case where one has length-1, which numpy would broadcast
102
+ arr = arr1d
103
+ idx = self.index_cls(arr)
104
+
105
+ with pytest.raises(ValueError, match="Lengths must match"):
106
+ arr == arr[:1]
107
+
108
+ # test the index classes while we're at it, GH#23078
109
+ with pytest.raises(ValueError, match="Lengths must match"):
110
+ idx <= idx[[0]]
111
+
112
+ @pytest.mark.parametrize(
113
+ "result",
114
+ [
115
+ pd.date_range("2020", periods=3),
116
+ pd.date_range("2020", periods=3, tz="UTC"),
117
+ pd.timedelta_range("0 days", periods=3),
118
+ pd.period_range("2020Q1", periods=3, freq="Q"),
119
+ ],
120
+ )
121
+ def test_compare_with_Categorical(self, result):
122
+ expected = pd.Categorical(result)
123
+ assert all(result == expected)
124
+ assert not any(result != expected)
125
+
126
+ @pytest.mark.parametrize("reverse", [True, False])
127
+ @pytest.mark.parametrize("as_index", [True, False])
128
+ def test_compare_categorical_dtype(self, arr1d, as_index, reverse, ordered):
129
+ other = pd.Categorical(arr1d, ordered=ordered)
130
+ if as_index:
131
+ other = pd.CategoricalIndex(other)
132
+
133
+ left, right = arr1d, other
134
+ if reverse:
135
+ left, right = right, left
136
+
137
+ ones = np.ones(arr1d.shape, dtype=bool)
138
+ zeros = ~ones
139
+
140
+ result = left == right
141
+ tm.assert_numpy_array_equal(result, ones)
142
+
143
+ result = left != right
144
+ tm.assert_numpy_array_equal(result, zeros)
145
+
146
+ if not reverse and not as_index:
147
+ # Otherwise Categorical raises TypeError bc it is not ordered
148
+ # TODO: we should probably get the same behavior regardless?
149
+ result = left < right
150
+ tm.assert_numpy_array_equal(result, zeros)
151
+
152
+ result = left <= right
153
+ tm.assert_numpy_array_equal(result, ones)
154
+
155
+ result = left > right
156
+ tm.assert_numpy_array_equal(result, zeros)
157
+
158
+ result = left >= right
159
+ tm.assert_numpy_array_equal(result, ones)
160
+
161
+ def test_take(self):
162
+ data = np.arange(100, dtype="i8") * 24 * 3600 * 10**9
163
+ np.random.default_rng(2).shuffle(data)
164
+
165
+ if self.array_cls is PeriodArray:
166
+ arr = PeriodArray(data, dtype="period[D]")
167
+ else:
168
+ arr = self.index_cls(data)._data
169
+ idx = self.index_cls._simple_new(arr)
170
+
171
+ takers = [1, 4, 94]
172
+ result = arr.take(takers)
173
+ expected = idx.take(takers)
174
+
175
+ tm.assert_index_equal(self.index_cls(result), expected)
176
+
177
+ takers = np.array([1, 4, 94])
178
+ result = arr.take(takers)
179
+ expected = idx.take(takers)
180
+
181
+ tm.assert_index_equal(self.index_cls(result), expected)
182
+
183
+ @pytest.mark.parametrize("fill_value", [2, 2.0, Timestamp(2021, 1, 1, 12).time])
184
+ def test_take_fill_raises(self, fill_value, arr1d):
185
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
186
+ with pytest.raises(TypeError, match=msg):
187
+ arr1d.take([0, 1], allow_fill=True, fill_value=fill_value)
188
+
189
+ def test_take_fill(self, arr1d):
190
+ arr = arr1d
191
+
192
+ result = arr.take([-1, 1], allow_fill=True, fill_value=None)
193
+ assert result[0] is NaT
194
+
195
+ result = arr.take([-1, 1], allow_fill=True, fill_value=np.nan)
196
+ assert result[0] is NaT
197
+
198
+ result = arr.take([-1, 1], allow_fill=True, fill_value=NaT)
199
+ assert result[0] is NaT
200
+
201
+ @pytest.mark.filterwarnings(
202
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
203
+ )
204
+ def test_take_fill_str(self, arr1d):
205
+ # Cast str fill_value matching other fill_value-taking methods
206
+ result = arr1d.take([-1, 1], allow_fill=True, fill_value=str(arr1d[-1]))
207
+ expected = arr1d[[-1, 1]]
208
+ tm.assert_equal(result, expected)
209
+
210
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
211
+ with pytest.raises(TypeError, match=msg):
212
+ arr1d.take([-1, 1], allow_fill=True, fill_value="foo")
213
+
214
+ def test_concat_same_type(self, arr1d):
215
+ arr = arr1d
216
+ idx = self.index_cls(arr)
217
+ idx = idx.insert(0, NaT)
218
+ arr = arr1d
219
+
220
+ result = arr._concat_same_type([arr[:-1], arr[1:], arr])
221
+ arr2 = arr.astype(object)
222
+ expected = self.index_cls(np.concatenate([arr2[:-1], arr2[1:], arr2]))
223
+
224
+ tm.assert_index_equal(self.index_cls(result), expected)
225
+
226
+ def test_unbox_scalar(self, arr1d):
227
+ result = arr1d._unbox_scalar(arr1d[0])
228
+ expected = arr1d._ndarray.dtype.type
229
+ assert isinstance(result, expected)
230
+
231
+ result = arr1d._unbox_scalar(NaT)
232
+ assert isinstance(result, expected)
233
+
234
+ msg = f"'value' should be a {self.scalar_type.__name__}."
235
+ with pytest.raises(ValueError, match=msg):
236
+ arr1d._unbox_scalar("foo")
237
+
238
+ def test_check_compatible_with(self, arr1d):
239
+ arr1d._check_compatible_with(arr1d[0])
240
+ arr1d._check_compatible_with(arr1d[:1])
241
+ arr1d._check_compatible_with(NaT)
242
+
243
+ def test_scalar_from_string(self, arr1d):
244
+ result = arr1d._scalar_from_string(str(arr1d[0]))
245
+ assert result == arr1d[0]
246
+
247
+ def test_reduce_invalid(self, arr1d):
248
+ msg = "does not support reduction 'not a method'"
249
+ with pytest.raises(TypeError, match=msg):
250
+ arr1d._reduce("not a method")
251
+
252
+ @pytest.mark.parametrize("method", ["pad", "backfill"])
253
+ def test_fillna_method_doesnt_change_orig(self, method):
254
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
255
+ if self.array_cls is PeriodArray:
256
+ arr = self.array_cls(data, dtype="period[D]")
257
+ else:
258
+ arr = self.array_cls._from_sequence(data)
259
+ arr[4] = NaT
260
+
261
+ fill_value = arr[3] if method == "pad" else arr[5]
262
+
263
+ result = arr._pad_or_backfill(method=method)
264
+ assert result[4] == fill_value
265
+
266
+ # check that the original was not changed
267
+ assert arr[4] is NaT
268
+
269
+ def test_searchsorted(self):
270
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
271
+ if self.array_cls is PeriodArray:
272
+ arr = self.array_cls(data, dtype="period[D]")
273
+ else:
274
+ arr = self.array_cls._from_sequence(data)
275
+
276
+ # scalar
277
+ result = arr.searchsorted(arr[1])
278
+ assert result == 1
279
+
280
+ result = arr.searchsorted(arr[2], side="right")
281
+ assert result == 3
282
+
283
+ # own-type
284
+ result = arr.searchsorted(arr[1:3])
285
+ expected = np.array([1, 2], dtype=np.intp)
286
+ tm.assert_numpy_array_equal(result, expected)
287
+
288
+ result = arr.searchsorted(arr[1:3], side="right")
289
+ expected = np.array([2, 3], dtype=np.intp)
290
+ tm.assert_numpy_array_equal(result, expected)
291
+
292
+ # GH#29884 match numpy convention on whether NaT goes
293
+ # at the end or the beginning
294
+ result = arr.searchsorted(NaT)
295
+ assert result == 10
296
+
297
+ @pytest.mark.parametrize("box", [None, "index", "series"])
298
+ def test_searchsorted_castable_strings(self, arr1d, box, string_storage):
299
+ arr = arr1d
300
+ if box is None:
301
+ pass
302
+ elif box == "index":
303
+ # Test the equivalent Index.searchsorted method while we're here
304
+ arr = self.index_cls(arr)
305
+ else:
306
+ # Test the equivalent Series.searchsorted method while we're here
307
+ arr = pd.Series(arr)
308
+
309
+ # scalar
310
+ result = arr.searchsorted(str(arr[1]))
311
+ assert result == 1
312
+
313
+ result = arr.searchsorted(str(arr[2]), side="right")
314
+ assert result == 3
315
+
316
+ result = arr.searchsorted([str(x) for x in arr[1:3]])
317
+ expected = np.array([1, 2], dtype=np.intp)
318
+ tm.assert_numpy_array_equal(result, expected)
319
+
320
+ with pytest.raises(
321
+ TypeError,
322
+ match=re.escape(
323
+ f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', "
324
+ "or array of those. Got 'str' instead."
325
+ ),
326
+ ):
327
+ arr.searchsorted("foo")
328
+
329
+ with pd.option_context("string_storage", string_storage):
330
+ with pytest.raises(
331
+ TypeError,
332
+ match=re.escape(
333
+ f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', "
334
+ "or array of those. Got string array instead."
335
+ ),
336
+ ):
337
+ arr.searchsorted([str(arr[1]), "baz"])
338
+
339
+ def test_getitem_near_implementation_bounds(self):
340
+ # We only check tz-naive for DTA bc the bounds are slightly different
341
+ # for other tzs
342
+ i8vals = np.asarray([NaT._value + n for n in range(1, 5)], dtype="i8")
343
+ if self.array_cls is PeriodArray:
344
+ arr = self.array_cls(i8vals, dtype="period[ns]")
345
+ else:
346
+ arr = self.index_cls(i8vals, freq="ns")._data
347
+ arr[0] # should not raise OutOfBoundsDatetime
348
+
349
+ index = pd.Index(arr)
350
+ index[0] # should not raise OutOfBoundsDatetime
351
+
352
+ ser = pd.Series(arr)
353
+ ser[0] # should not raise OutOfBoundsDatetime
354
+
355
+ def test_getitem_2d(self, arr1d):
356
+ # 2d slicing on a 1D array
357
+ expected = type(arr1d)._simple_new(
358
+ arr1d._ndarray[:, np.newaxis], dtype=arr1d.dtype
359
+ )
360
+ result = arr1d[:, np.newaxis]
361
+ tm.assert_equal(result, expected)
362
+
363
+ # Lookup on a 2D array
364
+ arr2d = expected
365
+ expected = type(arr2d)._simple_new(arr2d._ndarray[:3, 0], dtype=arr2d.dtype)
366
+ result = arr2d[:3, 0]
367
+ tm.assert_equal(result, expected)
368
+
369
+ # Scalar lookup
370
+ result = arr2d[-1, 0]
371
+ expected = arr1d[-1]
372
+ assert result == expected
373
+
374
+ def test_iter_2d(self, arr1d):
375
+ data2d = arr1d._ndarray[:3, np.newaxis]
376
+ arr2d = type(arr1d)._simple_new(data2d, dtype=arr1d.dtype)
377
+ result = list(arr2d)
378
+ assert len(result) == 3
379
+ for x in result:
380
+ assert isinstance(x, type(arr1d))
381
+ assert x.ndim == 1
382
+ assert x.dtype == arr1d.dtype
383
+
384
+ def test_repr_2d(self, arr1d):
385
+ data2d = arr1d._ndarray[:3, np.newaxis]
386
+ arr2d = type(arr1d)._simple_new(data2d, dtype=arr1d.dtype)
387
+
388
+ result = repr(arr2d)
389
+
390
+ if isinstance(arr2d, TimedeltaArray):
391
+ expected = (
392
+ f"<{type(arr2d).__name__}>\n"
393
+ "[\n"
394
+ f"['{arr1d[0]._repr_base()}'],\n"
395
+ f"['{arr1d[1]._repr_base()}'],\n"
396
+ f"['{arr1d[2]._repr_base()}']\n"
397
+ "]\n"
398
+ f"Shape: (3, 1), dtype: {arr1d.dtype}"
399
+ )
400
+ else:
401
+ expected = (
402
+ f"<{type(arr2d).__name__}>\n"
403
+ "[\n"
404
+ f"['{arr1d[0]}'],\n"
405
+ f"['{arr1d[1]}'],\n"
406
+ f"['{arr1d[2]}']\n"
407
+ "]\n"
408
+ f"Shape: (3, 1), dtype: {arr1d.dtype}"
409
+ )
410
+
411
+ assert result == expected
412
+
413
+ def test_setitem(self):
414
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
415
+ if self.array_cls is PeriodArray:
416
+ arr = self.array_cls(data, dtype="period[D]")
417
+ else:
418
+ arr = self.index_cls(data, freq="D")._data
419
+
420
+ arr[0] = arr[1]
421
+ expected = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
422
+ expected[0] = expected[1]
423
+
424
+ tm.assert_numpy_array_equal(arr.asi8, expected)
425
+
426
+ arr[:2] = arr[-2:]
427
+ expected[:2] = expected[-2:]
428
+ tm.assert_numpy_array_equal(arr.asi8, expected)
429
+
430
+ @pytest.mark.parametrize(
431
+ "box",
432
+ [
433
+ pd.Index,
434
+ pd.Series,
435
+ np.array,
436
+ list,
437
+ NumpyExtensionArray,
438
+ ],
439
+ )
440
+ def test_setitem_object_dtype(self, box, arr1d):
441
+ expected = arr1d.copy()[::-1]
442
+ if expected.dtype.kind in ["m", "M"]:
443
+ expected = expected._with_freq(None)
444
+
445
+ vals = expected
446
+ if box is list:
447
+ vals = list(vals)
448
+ elif box is np.array:
449
+ # if we do np.array(x).astype(object) then dt64 and td64 cast to ints
450
+ vals = np.array(vals.astype(object))
451
+ elif box is NumpyExtensionArray:
452
+ vals = box(np.asarray(vals, dtype=object))
453
+ else:
454
+ vals = box(vals).astype(object)
455
+
456
+ arr1d[:] = vals
457
+
458
+ tm.assert_equal(arr1d, expected)
459
+
460
+ def test_setitem_strs(self, arr1d):
461
+ # Check that we parse strs in both scalar and listlike
462
+
463
+ # Setting list-like of strs
464
+ expected = arr1d.copy()
465
+ expected[[0, 1]] = arr1d[-2:]
466
+
467
+ result = arr1d.copy()
468
+ result[:2] = [str(x) for x in arr1d[-2:]]
469
+ tm.assert_equal(result, expected)
470
+
471
+ # Same thing but now for just a scalar str
472
+ expected = arr1d.copy()
473
+ expected[0] = arr1d[-1]
474
+
475
+ result = arr1d.copy()
476
+ result[0] = str(arr1d[-1])
477
+ tm.assert_equal(result, expected)
478
+
479
+ @pytest.mark.parametrize("as_index", [True, False])
480
+ def test_setitem_categorical(self, arr1d, as_index):
481
+ expected = arr1d.copy()[::-1]
482
+ if not isinstance(expected, PeriodArray):
483
+ expected = expected._with_freq(None)
484
+
485
+ cat = pd.Categorical(arr1d)
486
+ if as_index:
487
+ cat = pd.CategoricalIndex(cat)
488
+
489
+ arr1d[:] = cat[::-1]
490
+
491
+ tm.assert_equal(arr1d, expected)
492
+
493
+ def test_setitem_raises(self, arr1d):
494
+ arr = arr1d[:10]
495
+ val = arr[0]
496
+
497
+ with pytest.raises(IndexError, match="index 12 is out of bounds"):
498
+ arr[12] = val
499
+
500
+ with pytest.raises(TypeError, match="value should be a.* 'object'"):
501
+ arr[0] = object()
502
+
503
+ msg = "cannot set using a list-like indexer with a different length"
504
+ with pytest.raises(ValueError, match=msg):
505
+ # GH#36339
506
+ arr[[]] = [arr[1]]
507
+
508
+ msg = "cannot set using a slice indexer with a different length than"
509
+ with pytest.raises(ValueError, match=msg):
510
+ # GH#36339
511
+ arr[1:1] = arr[:3]
512
+
513
+ @pytest.mark.parametrize("box", [list, np.array, pd.Index, pd.Series])
514
+ def test_setitem_numeric_raises(self, arr1d, box):
515
+ # We dont case e.g. int64 to our own dtype for setitem
516
+
517
+ msg = (
518
+ f"value should be a '{arr1d._scalar_type.__name__}', "
519
+ "'NaT', or array of those. Got"
520
+ )
521
+ with pytest.raises(TypeError, match=msg):
522
+ arr1d[:2] = box([0, 1])
523
+
524
+ with pytest.raises(TypeError, match=msg):
525
+ arr1d[:2] = box([0.0, 1.0])
526
+
527
+ def test_inplace_arithmetic(self):
528
+ # GH#24115 check that iadd and isub are actually in-place
529
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
530
+ if self.array_cls is PeriodArray:
531
+ arr = self.array_cls(data, dtype="period[D]")
532
+ else:
533
+ arr = self.index_cls(data, freq="D")._data
534
+
535
+ expected = arr + pd.Timedelta(days=1)
536
+ arr += pd.Timedelta(days=1)
537
+ tm.assert_equal(arr, expected)
538
+
539
+ expected = arr - pd.Timedelta(days=1)
540
+ arr -= pd.Timedelta(days=1)
541
+ tm.assert_equal(arr, expected)
542
+
543
+ def test_shift_fill_int_deprecated(self, arr1d):
544
+ # GH#31971, enforced in 2.0
545
+ with pytest.raises(TypeError, match="value should be a"):
546
+ arr1d.shift(1, fill_value=1)
547
+
548
+ def test_median(self, arr1d):
549
+ arr = arr1d
550
+ if len(arr) % 2 == 0:
551
+ # make it easier to define `expected`
552
+ arr = arr[:-1]
553
+
554
+ expected = arr[len(arr) // 2]
555
+
556
+ result = arr.median()
557
+ assert type(result) is type(expected)
558
+ assert result == expected
559
+
560
+ arr[len(arr) // 2] = NaT
561
+ if not isinstance(expected, Period):
562
+ expected = arr[len(arr) // 2 - 1 : len(arr) // 2 + 2].mean()
563
+
564
+ assert arr.median(skipna=False) is NaT
565
+
566
+ result = arr.median()
567
+ assert type(result) is type(expected)
568
+ assert result == expected
569
+
570
+ assert arr[:0].median() is NaT
571
+ assert arr[:0].median(skipna=False) is NaT
572
+
573
+ # 2d Case
574
+ arr2 = arr.reshape(-1, 1)
575
+
576
+ result = arr2.median(axis=None)
577
+ assert type(result) is type(expected)
578
+ assert result == expected
579
+
580
+ assert arr2.median(axis=None, skipna=False) is NaT
581
+
582
+ result = arr2.median(axis=0)
583
+ expected2 = type(arr)._from_sequence([expected], dtype=arr.dtype)
584
+ tm.assert_equal(result, expected2)
585
+
586
+ result = arr2.median(axis=0, skipna=False)
587
+ expected2 = type(arr)._from_sequence([NaT], dtype=arr.dtype)
588
+ tm.assert_equal(result, expected2)
589
+
590
+ result = arr2.median(axis=1)
591
+ tm.assert_equal(result, arr)
592
+
593
+ result = arr2.median(axis=1, skipna=False)
594
+ tm.assert_equal(result, arr)
595
+
596
+ def test_from_integer_array(self):
597
+ arr = np.array([1, 2, 3], dtype=np.int64)
598
+ data = pd.array(arr, dtype="Int64")
599
+ if self.array_cls is PeriodArray:
600
+ expected = self.array_cls(arr, dtype=self.example_dtype)
601
+ result = self.array_cls(data, dtype=self.example_dtype)
602
+ else:
603
+ expected = self.array_cls._from_sequence(arr, dtype=self.example_dtype)
604
+ result = self.array_cls._from_sequence(data, dtype=self.example_dtype)
605
+
606
+ tm.assert_extension_array_equal(result, expected)
607
+
608
+
609
+ class TestDatetimeArray(SharedTests):
610
+ index_cls = DatetimeIndex
611
+ array_cls = DatetimeArray
612
+ scalar_type = Timestamp
613
+ example_dtype = "M8[ns]"
614
+
615
+ @pytest.fixture
616
+ def arr1d(self, tz_naive_fixture, freqstr):
617
+ """
618
+ Fixture returning DatetimeArray with parametrized frequency and
619
+ timezones
620
+ """
621
+ tz = tz_naive_fixture
622
+ dti = pd.date_range("2016-01-01 01:01:00", periods=5, freq=freqstr, tz=tz)
623
+ dta = dti._data
624
+ return dta
625
+
626
+ def test_round(self, arr1d):
627
+ # GH#24064
628
+ dti = self.index_cls(arr1d)
629
+
630
+ result = dti.round(freq="2min")
631
+ expected = dti - pd.Timedelta(minutes=1)
632
+ expected = expected._with_freq(None)
633
+ tm.assert_index_equal(result, expected)
634
+
635
+ dta = dti._data
636
+ result = dta.round(freq="2min")
637
+ expected = expected._data._with_freq(None)
638
+ tm.assert_datetime_array_equal(result, expected)
639
+
640
+ def test_array_interface(self, datetime_index):
641
+ arr = datetime_index._data
642
+ copy_false = None if np_version_gt2 else False
643
+
644
+ # default asarray gives the same underlying data (for tz naive)
645
+ result = np.asarray(arr)
646
+ expected = arr._ndarray
647
+ assert result is expected
648
+ tm.assert_numpy_array_equal(result, expected)
649
+ result = np.array(arr, copy=copy_false)
650
+ assert result is expected
651
+ tm.assert_numpy_array_equal(result, expected)
652
+
653
+ # specifying M8[ns] gives the same result as default
654
+ result = np.asarray(arr, dtype="datetime64[ns]")
655
+ expected = arr._ndarray
656
+ assert result is expected
657
+ tm.assert_numpy_array_equal(result, expected)
658
+ result = np.array(arr, dtype="datetime64[ns]", copy=copy_false)
659
+ assert result is expected
660
+ tm.assert_numpy_array_equal(result, expected)
661
+ result = np.array(arr, dtype="datetime64[ns]")
662
+ assert result is not expected
663
+ tm.assert_numpy_array_equal(result, expected)
664
+
665
+ # to object dtype
666
+ result = np.asarray(arr, dtype=object)
667
+ expected = np.array(list(arr), dtype=object)
668
+ tm.assert_numpy_array_equal(result, expected)
669
+
670
+ # to other dtype always copies
671
+ result = np.asarray(arr, dtype="int64")
672
+ assert result is not arr.asi8
673
+ assert not np.may_share_memory(arr, result)
674
+ expected = arr.asi8.copy()
675
+ tm.assert_numpy_array_equal(result, expected)
676
+
677
+ # other dtypes handled by numpy
678
+ for dtype in ["float64", str]:
679
+ result = np.asarray(arr, dtype=dtype)
680
+ expected = np.asarray(arr).astype(dtype)
681
+ tm.assert_numpy_array_equal(result, expected)
682
+
683
+ def test_array_object_dtype(self, arr1d):
684
+ # GH#23524
685
+ arr = arr1d
686
+ dti = self.index_cls(arr1d)
687
+
688
+ expected = np.array(list(dti))
689
+
690
+ result = np.array(arr, dtype=object)
691
+ tm.assert_numpy_array_equal(result, expected)
692
+
693
+ # also test the DatetimeIndex method while we're at it
694
+ result = np.array(dti, dtype=object)
695
+ tm.assert_numpy_array_equal(result, expected)
696
+
697
+ def test_array_tz(self, arr1d):
698
+ # GH#23524
699
+ arr = arr1d
700
+ dti = self.index_cls(arr1d)
701
+ copy_false = None if np_version_gt2 else False
702
+
703
+ expected = dti.asi8.view("M8[ns]")
704
+ result = np.array(arr, dtype="M8[ns]")
705
+ tm.assert_numpy_array_equal(result, expected)
706
+
707
+ result = np.array(arr, dtype="datetime64[ns]")
708
+ tm.assert_numpy_array_equal(result, expected)
709
+
710
+ # check that we are not making copies when setting copy=copy_false
711
+ result = np.array(arr, dtype="M8[ns]", copy=copy_false)
712
+ assert result.base is expected.base
713
+ assert result.base is not None
714
+ result = np.array(arr, dtype="datetime64[ns]", copy=copy_false)
715
+ assert result.base is expected.base
716
+ assert result.base is not None
717
+
718
+ def test_array_i8_dtype(self, arr1d):
719
+ arr = arr1d
720
+ dti = self.index_cls(arr1d)
721
+ copy_false = None if np_version_gt2 else False
722
+
723
+ expected = dti.asi8
724
+ result = np.array(arr, dtype="i8")
725
+ tm.assert_numpy_array_equal(result, expected)
726
+
727
+ result = np.array(arr, dtype=np.int64)
728
+ tm.assert_numpy_array_equal(result, expected)
729
+
730
+ # check that we are still making copies when setting copy=copy_false
731
+ result = np.array(arr, dtype="i8", copy=copy_false)
732
+ assert result.base is not expected.base
733
+ assert result.base is None
734
+
735
+ def test_from_array_keeps_base(self):
736
+ # Ensure that DatetimeArray._ndarray.base isn't lost.
737
+ arr = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]")
738
+ dta = DatetimeArray._from_sequence(arr)
739
+
740
+ assert dta._ndarray is arr
741
+ dta = DatetimeArray._from_sequence(arr[:0])
742
+ assert dta._ndarray.base is arr
743
+
744
+ def test_from_dti(self, arr1d):
745
+ arr = arr1d
746
+ dti = self.index_cls(arr1d)
747
+ assert list(dti) == list(arr)
748
+
749
+ # Check that Index.__new__ knows what to do with DatetimeArray
750
+ dti2 = pd.Index(arr)
751
+ assert isinstance(dti2, DatetimeIndex)
752
+ assert list(dti2) == list(arr)
753
+
754
+ def test_astype_object(self, arr1d):
755
+ arr = arr1d
756
+ dti = self.index_cls(arr1d)
757
+
758
+ asobj = arr.astype("O")
759
+ assert isinstance(asobj, np.ndarray)
760
+ assert asobj.dtype == "O"
761
+ assert list(asobj) == list(dti)
762
+
763
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
764
+ def test_to_period(self, datetime_index, freqstr):
765
+ dti = datetime_index
766
+ arr = dti._data
767
+
768
+ freqstr = freq_to_period_freqstr(1, freqstr)
769
+ expected = dti.to_period(freq=freqstr)
770
+ result = arr.to_period(freq=freqstr)
771
+ assert isinstance(result, PeriodArray)
772
+
773
+ tm.assert_equal(result, expected._data)
774
+
775
+ def test_to_period_2d(self, arr1d):
776
+ arr2d = arr1d.reshape(1, -1)
777
+
778
+ warn = None if arr1d.tz is None else UserWarning
779
+ with tm.assert_produces_warning(warn):
780
+ result = arr2d.to_period("D")
781
+ expected = arr1d.to_period("D").reshape(1, -1)
782
+ tm.assert_period_array_equal(result, expected)
783
+
784
+ @pytest.mark.parametrize("propname", DatetimeArray._bool_ops)
785
+ def test_bool_properties(self, arr1d, propname):
786
+ # in this case _bool_ops is just `is_leap_year`
787
+ dti = self.index_cls(arr1d)
788
+ arr = arr1d
789
+ assert dti.freq == arr.freq
790
+
791
+ result = getattr(arr, propname)
792
+ expected = np.array(getattr(dti, propname), dtype=result.dtype)
793
+
794
+ tm.assert_numpy_array_equal(result, expected)
795
+
796
+ @pytest.mark.parametrize("propname", DatetimeArray._field_ops)
797
+ def test_int_properties(self, arr1d, propname):
798
+ dti = self.index_cls(arr1d)
799
+ arr = arr1d
800
+
801
+ result = getattr(arr, propname)
802
+ expected = np.array(getattr(dti, propname), dtype=result.dtype)
803
+
804
+ tm.assert_numpy_array_equal(result, expected)
805
+
806
+ def test_take_fill_valid(self, arr1d, fixed_now_ts):
807
+ arr = arr1d
808
+ dti = self.index_cls(arr1d)
809
+
810
+ now = fixed_now_ts.tz_localize(dti.tz)
811
+ result = arr.take([-1, 1], allow_fill=True, fill_value=now)
812
+ assert result[0] == now
813
+
814
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
815
+ with pytest.raises(TypeError, match=msg):
816
+ # fill_value Timedelta invalid
817
+ arr.take([-1, 1], allow_fill=True, fill_value=now - now)
818
+
819
+ with pytest.raises(TypeError, match=msg):
820
+ # fill_value Period invalid
821
+ arr.take([-1, 1], allow_fill=True, fill_value=Period("2014Q1"))
822
+
823
+ tz = None if dti.tz is not None else "US/Eastern"
824
+ now = fixed_now_ts.tz_localize(tz)
825
+ msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
826
+ with pytest.raises(TypeError, match=msg):
827
+ # Timestamp with mismatched tz-awareness
828
+ arr.take([-1, 1], allow_fill=True, fill_value=now)
829
+
830
+ value = NaT._value
831
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
832
+ with pytest.raises(TypeError, match=msg):
833
+ # require NaT, not iNaT, as it could be confused with an integer
834
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
835
+
836
+ value = np.timedelta64("NaT", "ns")
837
+ with pytest.raises(TypeError, match=msg):
838
+ # require appropriate-dtype if we have a NA value
839
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
840
+
841
+ if arr.tz is not None:
842
+ # GH#37356
843
+ # Assuming here that arr1d fixture does not include Australia/Melbourne
844
+ value = fixed_now_ts.tz_localize("Australia/Melbourne")
845
+ result = arr.take([-1, 1], allow_fill=True, fill_value=value)
846
+
847
+ expected = arr.take(
848
+ [-1, 1],
849
+ allow_fill=True,
850
+ fill_value=value.tz_convert(arr.dtype.tz),
851
+ )
852
+ tm.assert_equal(result, expected)
853
+
854
+ def test_concat_same_type_invalid(self, arr1d):
855
+ # different timezones
856
+ arr = arr1d
857
+
858
+ if arr.tz is None:
859
+ other = arr.tz_localize("UTC")
860
+ else:
861
+ other = arr.tz_localize(None)
862
+
863
+ with pytest.raises(ValueError, match="to_concat must have the same"):
864
+ arr._concat_same_type([arr, other])
865
+
866
+ def test_concat_same_type_different_freq(self, unit):
867
+ # we *can* concatenate DTI with different freqs.
868
+ a = pd.date_range("2000", periods=2, freq="D", tz="US/Central", unit=unit)._data
869
+ b = pd.date_range("2000", periods=2, freq="h", tz="US/Central", unit=unit)._data
870
+ result = DatetimeArray._concat_same_type([a, b])
871
+ expected = (
872
+ pd.to_datetime(
873
+ [
874
+ "2000-01-01 00:00:00",
875
+ "2000-01-02 00:00:00",
876
+ "2000-01-01 00:00:00",
877
+ "2000-01-01 01:00:00",
878
+ ]
879
+ )
880
+ .tz_localize("US/Central")
881
+ .as_unit(unit)
882
+ ._data
883
+ )
884
+
885
+ tm.assert_datetime_array_equal(result, expected)
886
+
887
+ def test_strftime(self, arr1d):
888
+ arr = arr1d
889
+
890
+ result = arr.strftime("%Y %b")
891
+ expected = np.array([ts.strftime("%Y %b") for ts in arr], dtype=object)
892
+ tm.assert_numpy_array_equal(result, expected)
893
+
894
+ def test_strftime_nat(self):
895
+ # GH 29578
896
+ arr = DatetimeIndex(["2019-01-01", NaT])._data
897
+
898
+ result = arr.strftime("%Y-%m-%d")
899
+ expected = np.array(["2019-01-01", np.nan], dtype=object)
900
+ tm.assert_numpy_array_equal(result, expected)
901
+
902
+
903
+ class TestTimedeltaArray(SharedTests):
904
+ index_cls = TimedeltaIndex
905
+ array_cls = TimedeltaArray
906
+ scalar_type = pd.Timedelta
907
+ example_dtype = "m8[ns]"
908
+
909
+ def test_from_tdi(self):
910
+ tdi = TimedeltaIndex(["1 Day", "3 Hours"])
911
+ arr = tdi._data
912
+ assert list(arr) == list(tdi)
913
+
914
+ # Check that Index.__new__ knows what to do with TimedeltaArray
915
+ tdi2 = pd.Index(arr)
916
+ assert isinstance(tdi2, TimedeltaIndex)
917
+ assert list(tdi2) == list(arr)
918
+
919
+ def test_astype_object(self):
920
+ tdi = TimedeltaIndex(["1 Day", "3 Hours"])
921
+ arr = tdi._data
922
+ asobj = arr.astype("O")
923
+ assert isinstance(asobj, np.ndarray)
924
+ assert asobj.dtype == "O"
925
+ assert list(asobj) == list(tdi)
926
+
927
+ def test_to_pytimedelta(self, timedelta_index):
928
+ tdi = timedelta_index
929
+ arr = tdi._data
930
+
931
+ expected = tdi.to_pytimedelta()
932
+ result = arr.to_pytimedelta()
933
+
934
+ tm.assert_numpy_array_equal(result, expected)
935
+
936
+ def test_total_seconds(self, timedelta_index):
937
+ tdi = timedelta_index
938
+ arr = tdi._data
939
+
940
+ expected = tdi.total_seconds()
941
+ result = arr.total_seconds()
942
+
943
+ tm.assert_numpy_array_equal(result, expected.values)
944
+
945
+ @pytest.mark.parametrize("propname", TimedeltaArray._field_ops)
946
+ def test_int_properties(self, timedelta_index, propname):
947
+ tdi = timedelta_index
948
+ arr = tdi._data
949
+
950
+ result = getattr(arr, propname)
951
+ expected = np.array(getattr(tdi, propname), dtype=result.dtype)
952
+
953
+ tm.assert_numpy_array_equal(result, expected)
954
+
955
+ def test_array_interface(self, timedelta_index):
956
+ arr = timedelta_index._data
957
+ copy_false = None if np_version_gt2 else False
958
+
959
+ # default asarray gives the same underlying data
960
+ result = np.asarray(arr)
961
+ expected = arr._ndarray
962
+ assert result is expected
963
+ tm.assert_numpy_array_equal(result, expected)
964
+ result = np.array(arr, copy=copy_false)
965
+ assert result is expected
966
+ tm.assert_numpy_array_equal(result, expected)
967
+
968
+ # specifying m8[ns] gives the same result as default
969
+ result = np.asarray(arr, dtype="timedelta64[ns]")
970
+ expected = arr._ndarray
971
+ assert result is expected
972
+ tm.assert_numpy_array_equal(result, expected)
973
+ result = np.array(arr, dtype="timedelta64[ns]", copy=copy_false)
974
+ assert result is expected
975
+ tm.assert_numpy_array_equal(result, expected)
976
+ result = np.array(arr, dtype="timedelta64[ns]")
977
+ assert result is not expected
978
+ tm.assert_numpy_array_equal(result, expected)
979
+
980
+ # to object dtype
981
+ result = np.asarray(arr, dtype=object)
982
+ expected = np.array(list(arr), dtype=object)
983
+ tm.assert_numpy_array_equal(result, expected)
984
+
985
+ # to other dtype always copies
986
+ result = np.asarray(arr, dtype="int64")
987
+ assert result is not arr.asi8
988
+ assert not np.may_share_memory(arr, result)
989
+ expected = arr.asi8.copy()
990
+ tm.assert_numpy_array_equal(result, expected)
991
+
992
+ # other dtypes handled by numpy
993
+ for dtype in ["float64", str]:
994
+ result = np.asarray(arr, dtype=dtype)
995
+ expected = np.asarray(arr).astype(dtype)
996
+ tm.assert_numpy_array_equal(result, expected)
997
+
998
+ def test_take_fill_valid(self, timedelta_index, fixed_now_ts):
999
+ tdi = timedelta_index
1000
+ arr = tdi._data
1001
+
1002
+ td1 = pd.Timedelta(days=1)
1003
+ result = arr.take([-1, 1], allow_fill=True, fill_value=td1)
1004
+ assert result[0] == td1
1005
+
1006
+ value = fixed_now_ts
1007
+ msg = f"value should be a '{arr._scalar_type.__name__}' or 'NaT'. Got"
1008
+ with pytest.raises(TypeError, match=msg):
1009
+ # fill_value Timestamp invalid
1010
+ arr.take([0, 1], allow_fill=True, fill_value=value)
1011
+
1012
+ value = fixed_now_ts.to_period("D")
1013
+ with pytest.raises(TypeError, match=msg):
1014
+ # fill_value Period invalid
1015
+ arr.take([0, 1], allow_fill=True, fill_value=value)
1016
+
1017
+ value = np.datetime64("NaT", "ns")
1018
+ with pytest.raises(TypeError, match=msg):
1019
+ # require appropriate-dtype if we have a NA value
1020
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
1021
+
1022
+
1023
+ @pytest.mark.filterwarnings(r"ignore:Period with BDay freq is deprecated:FutureWarning")
1024
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
1025
+ class TestPeriodArray(SharedTests):
1026
+ index_cls = PeriodIndex
1027
+ array_cls = PeriodArray
1028
+ scalar_type = Period
1029
+ example_dtype = PeriodIndex([], freq="W").dtype
1030
+
1031
+ @pytest.fixture
1032
+ def arr1d(self, period_index):
1033
+ """
1034
+ Fixture returning DatetimeArray from parametrized PeriodIndex objects
1035
+ """
1036
+ return period_index._data
1037
+
1038
+ def test_from_pi(self, arr1d):
1039
+ pi = self.index_cls(arr1d)
1040
+ arr = arr1d
1041
+ assert list(arr) == list(pi)
1042
+
1043
+ # Check that Index.__new__ knows what to do with PeriodArray
1044
+ pi2 = pd.Index(arr)
1045
+ assert isinstance(pi2, PeriodIndex)
1046
+ assert list(pi2) == list(arr)
1047
+
1048
+ def test_astype_object(self, arr1d):
1049
+ pi = self.index_cls(arr1d)
1050
+ arr = arr1d
1051
+ asobj = arr.astype("O")
1052
+ assert isinstance(asobj, np.ndarray)
1053
+ assert asobj.dtype == "O"
1054
+ assert list(asobj) == list(pi)
1055
+
1056
+ def test_take_fill_valid(self, arr1d):
1057
+ arr = arr1d
1058
+
1059
+ value = NaT._value
1060
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
1061
+ with pytest.raises(TypeError, match=msg):
1062
+ # require NaT, not iNaT, as it could be confused with an integer
1063
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
1064
+
1065
+ value = np.timedelta64("NaT", "ns")
1066
+ with pytest.raises(TypeError, match=msg):
1067
+ # require appropriate-dtype if we have a NA value
1068
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
1069
+
1070
+ @pytest.mark.parametrize("how", ["S", "E"])
1071
+ def test_to_timestamp(self, how, arr1d):
1072
+ pi = self.index_cls(arr1d)
1073
+ arr = arr1d
1074
+
1075
+ expected = DatetimeIndex(pi.to_timestamp(how=how))._data
1076
+ result = arr.to_timestamp(how=how)
1077
+ assert isinstance(result, DatetimeArray)
1078
+
1079
+ tm.assert_equal(result, expected)
1080
+
1081
+ def test_to_timestamp_roundtrip_bday(self):
1082
+ # Case where infer_freq inside would choose "D" instead of "B"
1083
+ dta = pd.date_range("2021-10-18", periods=3, freq="B")._data
1084
+ parr = dta.to_period()
1085
+ result = parr.to_timestamp()
1086
+ assert result.freq == "B"
1087
+ tm.assert_extension_array_equal(result, dta)
1088
+
1089
+ dta2 = dta[::2]
1090
+ parr2 = dta2.to_period()
1091
+ result2 = parr2.to_timestamp()
1092
+ assert result2.freq == "2B"
1093
+ tm.assert_extension_array_equal(result2, dta2)
1094
+
1095
+ parr3 = dta.to_period("2B")
1096
+ result3 = parr3.to_timestamp()
1097
+ assert result3.freq == "B"
1098
+ tm.assert_extension_array_equal(result3, dta)
1099
+
1100
+ def test_to_timestamp_out_of_bounds(self):
1101
+ # GH#19643 previously overflowed silently
1102
+ pi = pd.period_range("1500", freq="Y", periods=3)
1103
+ msg = "Out of bounds nanosecond timestamp: 1500-01-01 00:00:00"
1104
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
1105
+ pi.to_timestamp()
1106
+
1107
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
1108
+ pi._data.to_timestamp()
1109
+
1110
+ @pytest.mark.parametrize("propname", PeriodArray._bool_ops)
1111
+ def test_bool_properties(self, arr1d, propname):
1112
+ # in this case _bool_ops is just `is_leap_year`
1113
+ pi = self.index_cls(arr1d)
1114
+ arr = arr1d
1115
+
1116
+ result = getattr(arr, propname)
1117
+ expected = np.array(getattr(pi, propname))
1118
+
1119
+ tm.assert_numpy_array_equal(result, expected)
1120
+
1121
+ @pytest.mark.parametrize("propname", PeriodArray._field_ops)
1122
+ def test_int_properties(self, arr1d, propname):
1123
+ pi = self.index_cls(arr1d)
1124
+ arr = arr1d
1125
+
1126
+ result = getattr(arr, propname)
1127
+ expected = np.array(getattr(pi, propname))
1128
+
1129
+ tm.assert_numpy_array_equal(result, expected)
1130
+
1131
+ def test_array_interface(self, arr1d):
1132
+ arr = arr1d
1133
+
1134
+ # default asarray gives objects
1135
+ result = np.asarray(arr)
1136
+ expected = np.array(list(arr), dtype=object)
1137
+ tm.assert_numpy_array_equal(result, expected)
1138
+
1139
+ # to object dtype (same as default)
1140
+ result = np.asarray(arr, dtype=object)
1141
+ tm.assert_numpy_array_equal(result, expected)
1142
+
1143
+ result = np.asarray(arr, dtype="int64")
1144
+ tm.assert_numpy_array_equal(result, arr.asi8)
1145
+
1146
+ # to other dtypes
1147
+ msg = r"float\(\) argument must be a string or a( real)? number, not 'Period'"
1148
+ with pytest.raises(TypeError, match=msg):
1149
+ np.asarray(arr, dtype="float64")
1150
+
1151
+ result = np.asarray(arr, dtype="S20")
1152
+ expected = np.asarray(arr).astype("S20")
1153
+ tm.assert_numpy_array_equal(result, expected)
1154
+
1155
+ def test_strftime(self, arr1d):
1156
+ arr = arr1d
1157
+
1158
+ result = arr.strftime("%Y")
1159
+ expected = np.array([per.strftime("%Y") for per in arr], dtype=object)
1160
+ tm.assert_numpy_array_equal(result, expected)
1161
+
1162
+ def test_strftime_nat(self):
1163
+ # GH 29578
1164
+ arr = PeriodArray(PeriodIndex(["2019-01-01", NaT], dtype="period[D]"))
1165
+
1166
+ result = arr.strftime("%Y-%m-%d")
1167
+ expected = np.array(["2019-01-01", np.nan], dtype=object)
1168
+ tm.assert_numpy_array_equal(result, expected)
1169
+
1170
+
1171
+ @pytest.mark.parametrize(
1172
+ "arr,casting_nats",
1173
+ [
1174
+ (
1175
+ TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
1176
+ (NaT, np.timedelta64("NaT", "ns")),
1177
+ ),
1178
+ (
1179
+ pd.date_range("2000-01-01", periods=3, freq="D")._data,
1180
+ (NaT, np.datetime64("NaT", "ns")),
1181
+ ),
1182
+ (pd.period_range("2000-01-01", periods=3, freq="D")._data, (NaT,)),
1183
+ ],
1184
+ ids=lambda x: type(x).__name__,
1185
+ )
1186
+ def test_casting_nat_setitem_array(arr, casting_nats):
1187
+ expected = type(arr)._from_sequence([NaT, arr[1], arr[2]], dtype=arr.dtype)
1188
+
1189
+ for nat in casting_nats:
1190
+ arr = arr.copy()
1191
+ arr[0] = nat
1192
+ tm.assert_equal(arr, expected)
1193
+
1194
+
1195
+ @pytest.mark.parametrize(
1196
+ "arr,non_casting_nats",
1197
+ [
1198
+ (
1199
+ TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
1200
+ (np.datetime64("NaT", "ns"), NaT._value),
1201
+ ),
1202
+ (
1203
+ pd.date_range("2000-01-01", periods=3, freq="D")._data,
1204
+ (np.timedelta64("NaT", "ns"), NaT._value),
1205
+ ),
1206
+ (
1207
+ pd.period_range("2000-01-01", periods=3, freq="D")._data,
1208
+ (np.datetime64("NaT", "ns"), np.timedelta64("NaT", "ns"), NaT._value),
1209
+ ),
1210
+ ],
1211
+ ids=lambda x: type(x).__name__,
1212
+ )
1213
+ def test_invalid_nat_setitem_array(arr, non_casting_nats):
1214
+ msg = (
1215
+ "value should be a '(Timestamp|Timedelta|Period)', 'NaT', or array of those. "
1216
+ "Got '(timedelta64|datetime64|int)' instead."
1217
+ )
1218
+
1219
+ for nat in non_casting_nats:
1220
+ with pytest.raises(TypeError, match=msg):
1221
+ arr[0] = nat
1222
+
1223
+
1224
+ @pytest.mark.parametrize(
1225
+ "arr",
1226
+ [
1227
+ pd.date_range("2000", periods=4).array,
1228
+ pd.timedelta_range("2000", periods=4).array,
1229
+ ],
1230
+ )
1231
+ def test_to_numpy_extra(arr):
1232
+ arr[0] = NaT
1233
+ original = arr.copy()
1234
+
1235
+ result = arr.to_numpy()
1236
+ assert np.isnan(result[0])
1237
+
1238
+ result = arr.to_numpy(dtype="int64")
1239
+ assert result[0] == -9223372036854775808
1240
+
1241
+ result = arr.to_numpy(dtype="int64", na_value=0)
1242
+ assert result[0] == 0
1243
+
1244
+ result = arr.to_numpy(na_value=arr[1].to_numpy())
1245
+ assert result[0] == result[1]
1246
+
1247
+ result = arr.to_numpy(na_value=arr[1].to_numpy(copy=False))
1248
+ assert result[0] == result[1]
1249
+
1250
+ tm.assert_equal(arr, original)
1251
+
1252
+
1253
+ @pytest.mark.parametrize("as_index", [True, False])
1254
+ @pytest.mark.parametrize(
1255
+ "values",
1256
+ [
1257
+ pd.to_datetime(["2020-01-01", "2020-02-01"]),
1258
+ pd.to_timedelta([1, 2], unit="D"),
1259
+ PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"),
1260
+ ],
1261
+ )
1262
+ @pytest.mark.parametrize(
1263
+ "klass",
1264
+ [
1265
+ list,
1266
+ np.array,
1267
+ pd.array,
1268
+ pd.Series,
1269
+ pd.Index,
1270
+ pd.Categorical,
1271
+ pd.CategoricalIndex,
1272
+ ],
1273
+ )
1274
+ def test_searchsorted_datetimelike_with_listlike(values, klass, as_index):
1275
+ # https://github.com/pandas-dev/pandas/issues/32762
1276
+ if not as_index:
1277
+ values = values._data
1278
+
1279
+ result = values.searchsorted(klass(values))
1280
+ expected = np.array([0, 1], dtype=result.dtype)
1281
+
1282
+ tm.assert_numpy_array_equal(result, expected)
1283
+
1284
+
1285
+ @pytest.mark.parametrize(
1286
+ "values",
1287
+ [
1288
+ pd.to_datetime(["2020-01-01", "2020-02-01"]),
1289
+ pd.to_timedelta([1, 2], unit="D"),
1290
+ PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"),
1291
+ ],
1292
+ )
1293
+ @pytest.mark.parametrize(
1294
+ "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2]
1295
+ )
1296
+ def test_searchsorted_datetimelike_with_listlike_invalid_dtype(values, arg):
1297
+ # https://github.com/pandas-dev/pandas/issues/32762
1298
+ msg = "[Unexpected type|Cannot compare]"
1299
+ with pytest.raises(TypeError, match=msg):
1300
+ values.searchsorted(arg)
1301
+
1302
+
1303
+ @pytest.mark.parametrize("klass", [list, tuple, np.array, pd.Series])
1304
+ def test_period_index_construction_from_strings(klass):
1305
+ # https://github.com/pandas-dev/pandas/issues/26109
1306
+ strings = ["2020Q1", "2020Q2"] * 2
1307
+ data = klass(strings)
1308
+ result = PeriodIndex(data, freq="Q")
1309
+ expected = PeriodIndex([Period(s) for s in strings])
1310
+ tm.assert_index_equal(result, expected)
1311
+
1312
+
1313
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
1314
+ def test_from_pandas_array(dtype):
1315
+ # GH#24615
1316
+ data = np.array([1, 2, 3], dtype=dtype)
1317
+ arr = NumpyExtensionArray(data)
1318
+
1319
+ cls = {"M8[ns]": DatetimeArray, "m8[ns]": TimedeltaArray}[dtype]
1320
+
1321
+ depr_msg = f"{cls.__name__}.__init__ is deprecated"
1322
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
1323
+ result = cls(arr)
1324
+ expected = cls(data)
1325
+ tm.assert_extension_array_equal(result, expected)
1326
+
1327
+ result = cls._from_sequence(arr, dtype=dtype)
1328
+ expected = cls._from_sequence(data, dtype=dtype)
1329
+ tm.assert_extension_array_equal(result, expected)
1330
+
1331
+ func = {"M8[ns]": pd.to_datetime, "m8[ns]": pd.to_timedelta}[dtype]
1332
+ result = func(arr).array
1333
+ expected = func(data).array
1334
+ tm.assert_equal(result, expected)
1335
+
1336
+ # Let's check the Indexes while we're here
1337
+ idx_cls = {"M8[ns]": DatetimeIndex, "m8[ns]": TimedeltaIndex}[dtype]
1338
+ result = idx_cls(arr)
1339
+ expected = idx_cls(data)
1340
+ tm.assert_index_equal(result, expected)