applied-ai-018 commited on
Commit
c189a0a
·
verified ·
1 Parent(s): 14a98b8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_118_mp_rank_01_optim_states.pt +3 -0
  2. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_130_mp_rank_01_optim_states.pt +3 -0
  3. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_151_mp_rank_00_optim_states.pt +3 -0
  4. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_206_mp_rank_01_optim_states.pt +3 -0
  5. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_226_mp_rank_01_optim_states.pt +3 -0
  6. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_9_mp_rank_00_optim_states.pt +3 -0
  7. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_algos.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_analytics.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_api.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_indexing.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_map.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_missing.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_operators.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_sorting.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_take.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_warnings.py +19 -0
  17. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__init__.py +0 -0
  18. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/__init__.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/conftest.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_astype.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_comparison.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_concat.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_construction.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_contains.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_function.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_repr.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_to_numpy.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/conftest.py +48 -0
  30. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_arithmetic.py +244 -0
  31. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_astype.py +128 -0
  32. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_comparison.py +65 -0
  33. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_concat.py +20 -0
  34. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_contains.py +12 -0
  35. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_function.py +194 -0
  36. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_repr.py +47 -0
  37. venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_to_numpy.py +132 -0
  38. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__init__.py +0 -0
  39. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/__init__.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_accessor.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_arithmetics.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_array.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_constructors.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_dtype.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_indexing.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_libsparse.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/test_accessor.py +253 -0
  48. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/test_arithmetics.py +514 -0
  49. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/test_array.py +480 -0
  50. venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/test_astype.py +133 -0
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_118_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11ce736f46139e8bb1a4ca551c21a1b16c3d2c0082d406e446b57b621a2f0b66
3
+ size 41830212
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_130_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e605a188bb4dbf418021f1328676b909121c48cbe680b92bea9888aa6c355831
3
+ size 41830148
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_151_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7c1f1fd247ecf958bbc383572b994d0e9c9d7c5c9ae9ca9107f60b92a9688cd
3
+ size 41830212
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_206_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f2cadbb259049f17448810ebca1523d800cfee80ec14acafcd379fe1e2854cb
3
+ size 41830148
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_226_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da37dcda622caaa5a9a392c6b00284a8f97a2c244a7be4684f5fabdec35f6df7
3
+ size 41830148
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_9_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4cc02a48e597e11d876fc659787e1d604c4544be0332dfac1007b227f914b68
3
+ size 41830192
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_algos.cpython-310.pyc ADDED
Binary file (2.84 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_analytics.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_api.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_map.cpython-310.pyc ADDED
Binary file (4.34 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_missing.cpython-310.pyc ADDED
Binary file (6.72 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_operators.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_sorting.cpython-310.pyc ADDED
Binary file (3.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_take.cpython-310.pyc ADDED
Binary file (3.89 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_warnings.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import pandas._testing as tm
4
+
5
+
6
+ class TestCategoricalWarnings:
7
+ def test_tab_complete_warning(self, ip):
8
+ # https://github.com/pandas-dev/pandas/issues/16409
9
+ pytest.importorskip("IPython", minversion="6.0.0")
10
+ from IPython.core.completer import provisionalcompleter
11
+
12
+ code = "import pandas as pd; c = pd.Categorical([])"
13
+ ip.run_cell(code)
14
+
15
+ # GH 31324 newer jedi version raises Deprecation warning;
16
+ # appears resolved 2021-02-02
17
+ with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
18
+ with provisionalcompleter("ignore"):
19
+ list(ip.Completer.completions("c.", 1))
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (196 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (1.48 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_arithmetic.cpython-310.pyc ADDED
Binary file (6.56 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_astype.cpython-310.pyc ADDED
Binary file (3.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_comparison.cpython-310.pyc ADDED
Binary file (2.12 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_concat.cpython-310.pyc ADDED
Binary file (919 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_construction.cpython-310.pyc ADDED
Binary file (6.07 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_contains.cpython-310.pyc ADDED
Binary file (488 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_function.cpython-310.pyc ADDED
Binary file (5.86 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_repr.cpython-310.pyc ADDED
Binary file (1.63 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_to_numpy.cpython-310.pyc ADDED
Binary file (4.01 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/conftest.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas.core.arrays.floating import (
6
+ Float32Dtype,
7
+ Float64Dtype,
8
+ )
9
+
10
+
11
+ @pytest.fixture(params=[Float32Dtype, Float64Dtype])
12
+ def dtype(request):
13
+ """Parametrized fixture returning a float 'dtype'"""
14
+ return request.param()
15
+
16
+
17
+ @pytest.fixture
18
+ def data(dtype):
19
+ """Fixture returning 'data' array according to parametrized float 'dtype'"""
20
+ return pd.array(
21
+ list(np.arange(0.1, 0.9, 0.1))
22
+ + [pd.NA]
23
+ + list(np.arange(1, 9.8, 0.1))
24
+ + [pd.NA]
25
+ + [9.9, 10.0],
26
+ dtype=dtype,
27
+ )
28
+
29
+
30
+ @pytest.fixture
31
+ def data_missing(dtype):
32
+ """
33
+ Fixture returning array with missing data according to parametrized float
34
+ 'dtype'.
35
+ """
36
+ return pd.array([np.nan, 0.1], dtype=dtype)
37
+
38
+
39
+ @pytest.fixture(params=["data", "data_missing"])
40
+ def all_data(request, data, data_missing):
41
+ """Parametrized fixture returning 'data' or 'data_missing' float arrays.
42
+
43
+ Used to test dtype conversion with and without missing values.
44
+ """
45
+ if request.param == "data":
46
+ return data
47
+ elif request.param == "data_missing":
48
+ return data_missing
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_arithmetic.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.core.arrays import FloatingArray
9
+
10
+ # Basic test for the arithmetic array ops
11
+ # -----------------------------------------------------------------------------
12
+
13
+
14
+ @pytest.mark.parametrize(
15
+ "opname, exp",
16
+ [
17
+ ("add", [1.1, 2.2, None, None, 5.5]),
18
+ ("mul", [0.1, 0.4, None, None, 2.5]),
19
+ ("sub", [0.9, 1.8, None, None, 4.5]),
20
+ ("truediv", [10.0, 10.0, None, None, 10.0]),
21
+ ("floordiv", [9.0, 9.0, None, None, 10.0]),
22
+ ("mod", [0.1, 0.2, None, None, 0.0]),
23
+ ],
24
+ ids=["add", "mul", "sub", "div", "floordiv", "mod"],
25
+ )
26
+ def test_array_op(dtype, opname, exp):
27
+ a = pd.array([1.0, 2.0, None, 4.0, 5.0], dtype=dtype)
28
+ b = pd.array([0.1, 0.2, 0.3, None, 0.5], dtype=dtype)
29
+
30
+ op = getattr(operator, opname)
31
+
32
+ result = op(a, b)
33
+ expected = pd.array(exp, dtype=dtype)
34
+ tm.assert_extension_array_equal(result, expected)
35
+
36
+
37
+ @pytest.mark.parametrize("zero, negative", [(0, False), (0.0, False), (-0.0, True)])
38
+ def test_divide_by_zero(dtype, zero, negative):
39
+ # TODO pending NA/NaN discussion
40
+ # https://github.com/pandas-dev/pandas/issues/32265/
41
+ a = pd.array([0, 1, -1, None], dtype=dtype)
42
+ result = a / zero
43
+ expected = FloatingArray(
44
+ np.array([np.nan, np.inf, -np.inf, np.nan], dtype=dtype.numpy_dtype),
45
+ np.array([False, False, False, True]),
46
+ )
47
+ if negative:
48
+ expected *= -1
49
+ tm.assert_extension_array_equal(result, expected)
50
+
51
+
52
+ def test_pow_scalar(dtype):
53
+ a = pd.array([-1, 0, 1, None, 2], dtype=dtype)
54
+ result = a**0
55
+ expected = pd.array([1, 1, 1, 1, 1], dtype=dtype)
56
+ tm.assert_extension_array_equal(result, expected)
57
+
58
+ result = a**1
59
+ expected = pd.array([-1, 0, 1, None, 2], dtype=dtype)
60
+ tm.assert_extension_array_equal(result, expected)
61
+
62
+ result = a**pd.NA
63
+ expected = pd.array([None, None, 1, None, None], dtype=dtype)
64
+ tm.assert_extension_array_equal(result, expected)
65
+
66
+ result = a**np.nan
67
+ # TODO np.nan should be converted to pd.NA / missing before operation?
68
+ expected = FloatingArray(
69
+ np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype=dtype.numpy_dtype),
70
+ mask=a._mask,
71
+ )
72
+ tm.assert_extension_array_equal(result, expected)
73
+
74
+ # reversed
75
+ a = a[1:] # Can't raise integers to negative powers.
76
+
77
+ result = 0**a
78
+ expected = pd.array([1, 0, None, 0], dtype=dtype)
79
+ tm.assert_extension_array_equal(result, expected)
80
+
81
+ result = 1**a
82
+ expected = pd.array([1, 1, 1, 1], dtype=dtype)
83
+ tm.assert_extension_array_equal(result, expected)
84
+
85
+ result = pd.NA**a
86
+ expected = pd.array([1, None, None, None], dtype=dtype)
87
+ tm.assert_extension_array_equal(result, expected)
88
+
89
+ result = np.nan**a
90
+ expected = FloatingArray(
91
+ np.array([1, np.nan, np.nan, np.nan], dtype=dtype.numpy_dtype), mask=a._mask
92
+ )
93
+ tm.assert_extension_array_equal(result, expected)
94
+
95
+
96
+ def test_pow_array(dtype):
97
+ a = pd.array([0, 0, 0, 1, 1, 1, None, None, None], dtype=dtype)
98
+ b = pd.array([0, 1, None, 0, 1, None, 0, 1, None], dtype=dtype)
99
+ result = a**b
100
+ expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None], dtype=dtype)
101
+ tm.assert_extension_array_equal(result, expected)
102
+
103
+
104
+ def test_rpow_one_to_na():
105
+ # https://github.com/pandas-dev/pandas/issues/22022
106
+ # https://github.com/pandas-dev/pandas/issues/29997
107
+ arr = pd.array([np.nan, np.nan], dtype="Float64")
108
+ result = np.array([1.0, 2.0]) ** arr
109
+ expected = pd.array([1.0, np.nan], dtype="Float64")
110
+ tm.assert_extension_array_equal(result, expected)
111
+
112
+
113
+ @pytest.mark.parametrize("other", [0, 0.5])
114
+ def test_arith_zero_dim_ndarray(other):
115
+ arr = pd.array([1, None, 2], dtype="Float64")
116
+ result = arr + np.array(other)
117
+ expected = arr + other
118
+ tm.assert_equal(result, expected)
119
+
120
+
121
+ # Test generic characteristics / errors
122
+ # -----------------------------------------------------------------------------
123
+
124
+
125
+ def test_error_invalid_values(data, all_arithmetic_operators, using_infer_string):
126
+ op = all_arithmetic_operators
127
+ s = pd.Series(data)
128
+ ops = getattr(s, op)
129
+
130
+ if using_infer_string:
131
+ import pyarrow as pa
132
+
133
+ errs = (TypeError, pa.lib.ArrowNotImplementedError, NotImplementedError)
134
+ else:
135
+ errs = TypeError
136
+
137
+ # invalid scalars
138
+ msg = "|".join(
139
+ [
140
+ r"can only perform ops with numeric values",
141
+ r"FloatingArray cannot perform the operation mod",
142
+ "unsupported operand type",
143
+ "not all arguments converted during string formatting",
144
+ "can't multiply sequence by non-int of type 'float'",
145
+ "ufunc 'subtract' cannot use operands with types dtype",
146
+ r"can only concatenate str \(not \"float\"\) to str",
147
+ "ufunc '.*' not supported for the input types, and the inputs could not",
148
+ "ufunc '.*' did not contain a loop with signature matching types",
149
+ "Concatenation operation is not implemented for NumPy arrays",
150
+ "has no kernel",
151
+ "not implemented",
152
+ ]
153
+ )
154
+ with pytest.raises(errs, match=msg):
155
+ ops("foo")
156
+ with pytest.raises(errs, match=msg):
157
+ ops(pd.Timestamp("20180101"))
158
+
159
+ # invalid array-likes
160
+ with pytest.raises(errs, match=msg):
161
+ ops(pd.Series("foo", index=s.index))
162
+
163
+ msg = "|".join(
164
+ [
165
+ "can only perform ops with numeric values",
166
+ "cannot perform .* with this index type: DatetimeArray",
167
+ "Addition/subtraction of integers and integer-arrays "
168
+ "with DatetimeArray is no longer supported. *",
169
+ "unsupported operand type",
170
+ "not all arguments converted during string formatting",
171
+ "can't multiply sequence by non-int of type 'float'",
172
+ "ufunc 'subtract' cannot use operands with types dtype",
173
+ (
174
+ "ufunc 'add' cannot use operands with types "
175
+ rf"dtype\('{tm.ENDIAN}M8\[ns\]'\)"
176
+ ),
177
+ r"ufunc 'add' cannot use operands with types dtype\('float\d{2}'\)",
178
+ "cannot subtract DatetimeArray from ndarray",
179
+ "has no kernel",
180
+ "not implemented",
181
+ ]
182
+ )
183
+ with pytest.raises(errs, match=msg):
184
+ ops(pd.Series(pd.date_range("20180101", periods=len(s))))
185
+
186
+
187
+ # Various
188
+ # -----------------------------------------------------------------------------
189
+
190
+
191
+ def test_cross_type_arithmetic():
192
+ df = pd.DataFrame(
193
+ {
194
+ "A": pd.array([1, 2, np.nan], dtype="Float64"),
195
+ "B": pd.array([1, np.nan, 3], dtype="Float32"),
196
+ "C": np.array([1, 2, 3], dtype="float64"),
197
+ }
198
+ )
199
+
200
+ result = df.A + df.C
201
+ expected = pd.Series([2, 4, np.nan], dtype="Float64")
202
+ tm.assert_series_equal(result, expected)
203
+
204
+ result = (df.A + df.C) * 3 == 12
205
+ expected = pd.Series([False, True, None], dtype="boolean")
206
+ tm.assert_series_equal(result, expected)
207
+
208
+ result = df.A + df.B
209
+ expected = pd.Series([2, np.nan, np.nan], dtype="Float64")
210
+ tm.assert_series_equal(result, expected)
211
+
212
+
213
+ @pytest.mark.parametrize(
214
+ "source, neg_target, abs_target",
215
+ [
216
+ ([1.1, 2.2, 3.3], [-1.1, -2.2, -3.3], [1.1, 2.2, 3.3]),
217
+ ([1.1, 2.2, None], [-1.1, -2.2, None], [1.1, 2.2, None]),
218
+ ([-1.1, 0.0, 1.1], [1.1, 0.0, -1.1], [1.1, 0.0, 1.1]),
219
+ ],
220
+ )
221
+ def test_unary_float_operators(float_ea_dtype, source, neg_target, abs_target):
222
+ # GH38794
223
+ dtype = float_ea_dtype
224
+ arr = pd.array(source, dtype=dtype)
225
+ neg_result, pos_result, abs_result = -arr, +arr, abs(arr)
226
+ neg_target = pd.array(neg_target, dtype=dtype)
227
+ abs_target = pd.array(abs_target, dtype=dtype)
228
+
229
+ tm.assert_extension_array_equal(neg_result, neg_target)
230
+ tm.assert_extension_array_equal(pos_result, arr)
231
+ assert not tm.shares_memory(pos_result, arr)
232
+ tm.assert_extension_array_equal(abs_result, abs_target)
233
+
234
+
235
+ def test_bitwise(dtype):
236
+ left = pd.array([1, None, 3, 4], dtype=dtype)
237
+ right = pd.array([None, 3, 5, 4], dtype=dtype)
238
+
239
+ with pytest.raises(TypeError, match="unsupported operand type"):
240
+ left | right
241
+ with pytest.raises(TypeError, match="unsupported operand type"):
242
+ left & right
243
+ with pytest.raises(TypeError, match="unsupported operand type"):
244
+ left ^ right
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_astype.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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([0.1, 0.2, None], dtype="Float64")
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 bool"):
16
+ arr.astype("bool")
17
+
18
+ result = arr.astype("float64")
19
+ expected = np.array([0.1, 0.2, np.nan], dtype="float64")
20
+ tm.assert_numpy_array_equal(result, expected)
21
+
22
+ # no missing values
23
+ arr = pd.array([0.0, 1.0, 0.5], dtype="Float64")
24
+ result = arr.astype("int64")
25
+ expected = np.array([0, 1, 0], dtype="int64")
26
+ tm.assert_numpy_array_equal(result, expected)
27
+
28
+ result = arr.astype("bool")
29
+ expected = np.array([False, True, True], dtype="bool")
30
+ tm.assert_numpy_array_equal(result, expected)
31
+
32
+
33
+ def test_astype_to_floating_array():
34
+ # astype to FloatingArray
35
+ arr = pd.array([0.0, 1.0, None], dtype="Float64")
36
+
37
+ result = arr.astype("Float64")
38
+ tm.assert_extension_array_equal(result, arr)
39
+ result = arr.astype(pd.Float64Dtype())
40
+ tm.assert_extension_array_equal(result, arr)
41
+ result = arr.astype("Float32")
42
+ expected = pd.array([0.0, 1.0, None], dtype="Float32")
43
+ tm.assert_extension_array_equal(result, expected)
44
+
45
+
46
+ def test_astype_to_boolean_array():
47
+ # astype to BooleanArray
48
+ arr = pd.array([0.0, 1.0, None], dtype="Float64")
49
+
50
+ result = arr.astype("boolean")
51
+ expected = pd.array([False, True, None], dtype="boolean")
52
+ tm.assert_extension_array_equal(result, expected)
53
+ result = arr.astype(pd.BooleanDtype())
54
+ tm.assert_extension_array_equal(result, expected)
55
+
56
+
57
+ def test_astype_to_integer_array():
58
+ # astype to IntegerArray
59
+ arr = pd.array([0.0, 1.5, None], dtype="Float64")
60
+
61
+ result = arr.astype("Int64")
62
+ expected = pd.array([0, 1, None], dtype="Int64")
63
+ tm.assert_extension_array_equal(result, expected)
64
+
65
+
66
+ def test_astype_str():
67
+ a = pd.array([0.1, 0.2, None], dtype="Float64")
68
+ expected = np.array(["0.1", "0.2", "<NA>"], dtype="U32")
69
+
70
+ tm.assert_numpy_array_equal(a.astype(str), expected)
71
+ tm.assert_numpy_array_equal(a.astype("str"), expected)
72
+
73
+
74
+ def test_astype_copy():
75
+ arr = pd.array([0.1, 0.2, None], dtype="Float64")
76
+ orig = pd.array([0.1, 0.2, None], dtype="Float64")
77
+
78
+ # copy=True -> ensure both data and mask are actual copies
79
+ result = arr.astype("Float64", copy=True)
80
+ assert result is not arr
81
+ assert not tm.shares_memory(result, arr)
82
+ result[0] = 10
83
+ tm.assert_extension_array_equal(arr, orig)
84
+ result[0] = pd.NA
85
+ tm.assert_extension_array_equal(arr, orig)
86
+
87
+ # copy=False
88
+ result = arr.astype("Float64", copy=False)
89
+ assert result is arr
90
+ assert np.shares_memory(result._data, arr._data)
91
+ assert np.shares_memory(result._mask, arr._mask)
92
+ result[0] = 10
93
+ assert arr[0] == 10
94
+ result[0] = pd.NA
95
+ assert arr[0] is pd.NA
96
+
97
+ # astype to different dtype -> always needs a copy -> even with copy=False
98
+ # we need to ensure that also the mask is actually copied
99
+ arr = pd.array([0.1, 0.2, None], dtype="Float64")
100
+ orig = pd.array([0.1, 0.2, None], dtype="Float64")
101
+
102
+ result = arr.astype("Float32", copy=False)
103
+ assert not tm.shares_memory(result, arr)
104
+ result[0] = 10
105
+ tm.assert_extension_array_equal(arr, orig)
106
+ result[0] = pd.NA
107
+ tm.assert_extension_array_equal(arr, orig)
108
+
109
+
110
+ def test_astype_object(dtype):
111
+ arr = pd.array([1.0, pd.NA], dtype=dtype)
112
+
113
+ result = arr.astype(object)
114
+ expected = np.array([1.0, pd.NA], dtype=object)
115
+ tm.assert_numpy_array_equal(result, expected)
116
+ # check exact element types
117
+ assert isinstance(result[0], float)
118
+ assert result[1] is pd.NA
119
+
120
+
121
+ def test_Float64_conversion():
122
+ # GH#40729
123
+ testseries = pd.Series(["1", "2", "3", "4"], dtype="object")
124
+ result = testseries.astype(pd.Float64Dtype())
125
+
126
+ expected = pd.Series([1.0, 2.0, 3.0, 4.0], dtype=pd.Float64Dtype())
127
+
128
+ tm.assert_series_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_comparison.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+ from pandas.core.arrays import FloatingArray
7
+ from pandas.tests.arrays.masked_shared import (
8
+ ComparisonOps,
9
+ NumericOps,
10
+ )
11
+
12
+
13
+ class TestComparisonOps(NumericOps, ComparisonOps):
14
+ @pytest.mark.parametrize("other", [True, False, pd.NA, -1.0, 0.0, 1])
15
+ def test_scalar(self, other, comparison_op, dtype):
16
+ ComparisonOps.test_scalar(self, other, comparison_op, dtype)
17
+
18
+ def test_compare_with_integerarray(self, comparison_op):
19
+ op = comparison_op
20
+ a = pd.array([0, 1, None] * 3, dtype="Int64")
21
+ b = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype="Float64")
22
+ other = b.astype("Int64")
23
+ expected = op(a, other)
24
+ result = op(a, b)
25
+ tm.assert_extension_array_equal(result, expected)
26
+ expected = op(other, a)
27
+ result = op(b, a)
28
+ tm.assert_extension_array_equal(result, expected)
29
+
30
+
31
+ def test_equals():
32
+ # GH-30652
33
+ # equals is generally tested in /tests/extension/base/methods, but this
34
+ # specifically tests that two arrays of the same class but different dtype
35
+ # do not evaluate equal
36
+ a1 = pd.array([1, 2, None], dtype="Float64")
37
+ a2 = pd.array([1, 2, None], dtype="Float32")
38
+ assert a1.equals(a2) is False
39
+
40
+
41
+ def test_equals_nan_vs_na():
42
+ # GH#44382
43
+
44
+ mask = np.zeros(3, dtype=bool)
45
+ data = np.array([1.0, np.nan, 3.0], dtype=np.float64)
46
+
47
+ left = FloatingArray(data, mask)
48
+ assert left.equals(left)
49
+ tm.assert_extension_array_equal(left, left)
50
+
51
+ assert left.equals(left.copy())
52
+ assert left.equals(FloatingArray(data.copy(), mask.copy()))
53
+
54
+ mask2 = np.array([False, True, False], dtype=bool)
55
+ data2 = np.array([1.0, 2.0, 3.0], dtype=np.float64)
56
+ right = FloatingArray(data2, mask2)
57
+ assert right.equals(right)
58
+ tm.assert_extension_array_equal(right, right)
59
+
60
+ assert not left.equals(right)
61
+
62
+ # with mask[1] = True, the only difference is data[1], which should
63
+ # not matter for equals
64
+ mask[1] = True
65
+ assert left.equals(right)
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_concat.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import pandas as pd
4
+ import pandas._testing as tm
5
+
6
+
7
+ @pytest.mark.parametrize(
8
+ "to_concat_dtypes, result_dtype",
9
+ [
10
+ (["Float64", "Float64"], "Float64"),
11
+ (["Float32", "Float64"], "Float64"),
12
+ (["Float32", "Float32"], "Float32"),
13
+ ],
14
+ )
15
+ def test_concat_series(to_concat_dtypes, result_dtype):
16
+ result = pd.concat([pd.Series([1, 2, pd.NA], dtype=t) for t in to_concat_dtypes])
17
+ expected = pd.concat([pd.Series([1, 2, pd.NA], dtype=object)] * 2).astype(
18
+ result_dtype
19
+ )
20
+ tm.assert_series_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_contains.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import pandas as pd
4
+
5
+
6
+ def test_contains_nan():
7
+ # GH#52840
8
+ arr = pd.array(range(5)) / 0
9
+
10
+ assert np.isnan(arr._data[0])
11
+ assert not arr.isna()[0]
12
+ assert np.nan in arr
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_function.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.compat import IS64
5
+
6
+ import pandas as pd
7
+ import pandas._testing as tm
8
+
9
+
10
+ @pytest.mark.parametrize("ufunc", [np.abs, np.sign])
11
+ # np.sign emits a warning with nans, <https://github.com/numpy/numpy/issues/15127>
12
+ @pytest.mark.filterwarnings("ignore:invalid value encountered in sign:RuntimeWarning")
13
+ def test_ufuncs_single(ufunc):
14
+ a = pd.array([1, 2, -3, np.nan], dtype="Float64")
15
+ result = ufunc(a)
16
+ expected = pd.array(ufunc(a.astype(float)), dtype="Float64")
17
+ tm.assert_extension_array_equal(result, expected)
18
+
19
+ s = pd.Series(a)
20
+ result = ufunc(s)
21
+ expected = pd.Series(expected)
22
+ tm.assert_series_equal(result, expected)
23
+
24
+
25
+ @pytest.mark.parametrize("ufunc", [np.log, np.exp, np.sin, np.cos, np.sqrt])
26
+ def test_ufuncs_single_float(ufunc):
27
+ a = pd.array([1.0, 0.2, 3.0, np.nan], dtype="Float64")
28
+ with np.errstate(invalid="ignore"):
29
+ result = ufunc(a)
30
+ expected = pd.array(ufunc(a.astype(float)), dtype="Float64")
31
+ tm.assert_extension_array_equal(result, expected)
32
+
33
+ s = pd.Series(a)
34
+ with np.errstate(invalid="ignore"):
35
+ result = ufunc(s)
36
+ expected = pd.Series(ufunc(s.astype(float)), dtype="Float64")
37
+ tm.assert_series_equal(result, expected)
38
+
39
+
40
+ @pytest.mark.parametrize("ufunc", [np.add, np.subtract])
41
+ def test_ufuncs_binary_float(ufunc):
42
+ # two FloatingArrays
43
+ a = pd.array([1, 0.2, -3, np.nan], dtype="Float64")
44
+ result = ufunc(a, a)
45
+ expected = pd.array(ufunc(a.astype(float), a.astype(float)), dtype="Float64")
46
+ tm.assert_extension_array_equal(result, expected)
47
+
48
+ # FloatingArray with numpy array
49
+ arr = np.array([1, 2, 3, 4])
50
+ result = ufunc(a, arr)
51
+ expected = pd.array(ufunc(a.astype(float), arr), dtype="Float64")
52
+ tm.assert_extension_array_equal(result, expected)
53
+
54
+ result = ufunc(arr, a)
55
+ expected = pd.array(ufunc(arr, a.astype(float)), dtype="Float64")
56
+ tm.assert_extension_array_equal(result, expected)
57
+
58
+ # FloatingArray with scalar
59
+ result = ufunc(a, 1)
60
+ expected = pd.array(ufunc(a.astype(float), 1), dtype="Float64")
61
+ tm.assert_extension_array_equal(result, expected)
62
+
63
+ result = ufunc(1, a)
64
+ expected = pd.array(ufunc(1, a.astype(float)), dtype="Float64")
65
+ tm.assert_extension_array_equal(result, expected)
66
+
67
+
68
+ @pytest.mark.parametrize("values", [[0, 1], [0, None]])
69
+ def test_ufunc_reduce_raises(values):
70
+ arr = pd.array(values, dtype="Float64")
71
+
72
+ res = np.add.reduce(arr)
73
+ expected = arr.sum(skipna=False)
74
+ tm.assert_almost_equal(res, expected)
75
+
76
+
77
+ @pytest.mark.skipif(not IS64, reason="GH 36579: fail on 32-bit system")
78
+ @pytest.mark.parametrize(
79
+ "pandasmethname, kwargs",
80
+ [
81
+ ("var", {"ddof": 0}),
82
+ ("var", {"ddof": 1}),
83
+ ("std", {"ddof": 0}),
84
+ ("std", {"ddof": 1}),
85
+ ("kurtosis", {}),
86
+ ("skew", {}),
87
+ ("sem", {}),
88
+ ],
89
+ )
90
+ def test_stat_method(pandasmethname, kwargs):
91
+ s = pd.Series(data=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, np.nan, np.nan], dtype="Float64")
92
+ pandasmeth = getattr(s, pandasmethname)
93
+ result = pandasmeth(**kwargs)
94
+ s2 = pd.Series(data=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dtype="float64")
95
+ pandasmeth = getattr(s2, pandasmethname)
96
+ expected = pandasmeth(**kwargs)
97
+ assert expected == result
98
+
99
+
100
+ def test_value_counts_na():
101
+ arr = pd.array([0.1, 0.2, 0.1, pd.NA], dtype="Float64")
102
+ result = arr.value_counts(dropna=False)
103
+ idx = pd.Index([0.1, 0.2, pd.NA], dtype=arr.dtype)
104
+ assert idx.dtype == arr.dtype
105
+ expected = pd.Series([2, 1, 1], index=idx, dtype="Int64", name="count")
106
+ tm.assert_series_equal(result, expected)
107
+
108
+ result = arr.value_counts(dropna=True)
109
+ expected = pd.Series([2, 1], index=idx[:-1], dtype="Int64", name="count")
110
+ tm.assert_series_equal(result, expected)
111
+
112
+
113
+ def test_value_counts_empty():
114
+ ser = pd.Series([], dtype="Float64")
115
+ result = ser.value_counts()
116
+ idx = pd.Index([], dtype="Float64")
117
+ assert idx.dtype == "Float64"
118
+ expected = pd.Series([], index=idx, dtype="Int64", name="count")
119
+ tm.assert_series_equal(result, expected)
120
+
121
+
122
+ def test_value_counts_with_normalize():
123
+ ser = pd.Series([0.1, 0.2, 0.1, pd.NA], dtype="Float64")
124
+ result = ser.value_counts(normalize=True)
125
+ expected = pd.Series([2, 1], index=ser[:2], dtype="Float64", name="proportion") / 3
126
+ assert expected.index.dtype == ser.dtype
127
+ tm.assert_series_equal(result, expected)
128
+
129
+
130
+ @pytest.mark.parametrize("skipna", [True, False])
131
+ @pytest.mark.parametrize("min_count", [0, 4])
132
+ def test_floating_array_sum(skipna, min_count, dtype):
133
+ arr = pd.array([1, 2, 3, None], dtype=dtype)
134
+ result = arr.sum(skipna=skipna, min_count=min_count)
135
+ if skipna and min_count == 0:
136
+ assert result == 6.0
137
+ else:
138
+ assert result is pd.NA
139
+
140
+
141
+ @pytest.mark.parametrize(
142
+ "values, expected", [([1, 2, 3], 6.0), ([1, 2, 3, None], 6.0), ([None], 0.0)]
143
+ )
144
+ def test_floating_array_numpy_sum(values, expected):
145
+ arr = pd.array(values, dtype="Float64")
146
+ result = np.sum(arr)
147
+ assert result == expected
148
+
149
+
150
+ @pytest.mark.parametrize("op", ["sum", "min", "max", "prod"])
151
+ def test_preserve_dtypes(op):
152
+ df = pd.DataFrame(
153
+ {
154
+ "A": ["a", "b", "b"],
155
+ "B": [1, None, 3],
156
+ "C": pd.array([0.1, None, 3.0], dtype="Float64"),
157
+ }
158
+ )
159
+
160
+ # op
161
+ result = getattr(df.C, op)()
162
+ assert isinstance(result, np.float64)
163
+
164
+ # groupby
165
+ result = getattr(df.groupby("A"), op)()
166
+
167
+ expected = pd.DataFrame(
168
+ {"B": np.array([1.0, 3.0]), "C": pd.array([0.1, 3], dtype="Float64")},
169
+ index=pd.Index(["a", "b"], name="A"),
170
+ )
171
+ tm.assert_frame_equal(result, expected)
172
+
173
+
174
+ @pytest.mark.parametrize("skipna", [True, False])
175
+ @pytest.mark.parametrize("method", ["min", "max"])
176
+ def test_floating_array_min_max(skipna, method, dtype):
177
+ arr = pd.array([0.0, 1.0, None], dtype=dtype)
178
+ func = getattr(arr, method)
179
+ result = func(skipna=skipna)
180
+ if skipna:
181
+ assert result == (0 if method == "min" else 1)
182
+ else:
183
+ assert result is pd.NA
184
+
185
+
186
+ @pytest.mark.parametrize("skipna", [True, False])
187
+ @pytest.mark.parametrize("min_count", [0, 9])
188
+ def test_floating_array_prod(skipna, min_count, dtype):
189
+ arr = pd.array([1.0, 2.0, None], dtype=dtype)
190
+ result = arr.prod(skipna=skipna, min_count=min_count)
191
+ if skipna and min_count == 0:
192
+ assert result == 2
193
+ else:
194
+ assert result is pd.NA
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_repr.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas.core.arrays.floating import (
6
+ Float32Dtype,
7
+ Float64Dtype,
8
+ )
9
+
10
+
11
+ def test_dtypes(dtype):
12
+ # smoke tests on auto dtype construction
13
+
14
+ np.dtype(dtype.type).kind == "f"
15
+ assert dtype.name is not None
16
+
17
+
18
+ @pytest.mark.parametrize(
19
+ "dtype, expected",
20
+ [(Float32Dtype(), "Float32Dtype()"), (Float64Dtype(), "Float64Dtype()")],
21
+ )
22
+ def test_repr_dtype(dtype, expected):
23
+ assert repr(dtype) == expected
24
+
25
+
26
+ def test_repr_array():
27
+ result = repr(pd.array([1.0, None, 3.0]))
28
+ expected = "<FloatingArray>\n[1.0, <NA>, 3.0]\nLength: 3, dtype: Float64"
29
+ assert result == expected
30
+
31
+
32
+ def test_repr_array_long():
33
+ data = pd.array([1.0, 2.0, None] * 1000)
34
+ expected = """<FloatingArray>
35
+ [ 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0,
36
+ ...
37
+ <NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>]
38
+ Length: 3000, dtype: Float64"""
39
+ result = repr(data)
40
+ assert result == expected
41
+
42
+
43
+ def test_frame_repr(data_missing):
44
+ df = pd.DataFrame({"A": data_missing})
45
+ result = repr(df)
46
+ expected = " A\n0 <NA>\n1 0.1"
47
+ assert result == expected
venv/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_to_numpy.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+ from pandas.core.arrays import FloatingArray
7
+
8
+
9
+ @pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
10
+ def test_to_numpy(box):
11
+ con = pd.Series if box else pd.array
12
+
13
+ # default (with or without missing values) -> object dtype
14
+ arr = con([0.1, 0.2, 0.3], dtype="Float64")
15
+ result = arr.to_numpy()
16
+ expected = np.array([0.1, 0.2, 0.3], dtype="float64")
17
+ tm.assert_numpy_array_equal(result, expected)
18
+
19
+ arr = con([0.1, 0.2, None], dtype="Float64")
20
+ result = arr.to_numpy()
21
+ expected = np.array([0.1, 0.2, np.nan], dtype="float64")
22
+ tm.assert_numpy_array_equal(result, expected)
23
+
24
+
25
+ @pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
26
+ def test_to_numpy_float(box):
27
+ con = pd.Series if box else pd.array
28
+
29
+ # no missing values -> can convert to float, otherwise raises
30
+ arr = con([0.1, 0.2, 0.3], dtype="Float64")
31
+ result = arr.to_numpy(dtype="float64")
32
+ expected = np.array([0.1, 0.2, 0.3], dtype="float64")
33
+ tm.assert_numpy_array_equal(result, expected)
34
+
35
+ arr = con([0.1, 0.2, None], dtype="Float64")
36
+ result = arr.to_numpy(dtype="float64")
37
+ expected = np.array([0.1, 0.2, np.nan], dtype="float64")
38
+ tm.assert_numpy_array_equal(result, expected)
39
+
40
+ result = arr.to_numpy(dtype="float64", na_value=np.nan)
41
+ expected = np.array([0.1, 0.2, np.nan], dtype="float64")
42
+ tm.assert_numpy_array_equal(result, expected)
43
+
44
+
45
+ @pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
46
+ def test_to_numpy_int(box):
47
+ con = pd.Series if box else pd.array
48
+
49
+ # no missing values -> can convert to int, otherwise raises
50
+ arr = con([1.0, 2.0, 3.0], dtype="Float64")
51
+ result = arr.to_numpy(dtype="int64")
52
+ expected = np.array([1, 2, 3], dtype="int64")
53
+ tm.assert_numpy_array_equal(result, expected)
54
+
55
+ arr = con([1.0, 2.0, None], dtype="Float64")
56
+ with pytest.raises(ValueError, match="cannot convert to 'int64'-dtype"):
57
+ result = arr.to_numpy(dtype="int64")
58
+
59
+ # automatic casting (floors the values)
60
+ arr = con([0.1, 0.9, 1.1], dtype="Float64")
61
+ result = arr.to_numpy(dtype="int64")
62
+ expected = np.array([0, 0, 1], dtype="int64")
63
+ tm.assert_numpy_array_equal(result, expected)
64
+
65
+
66
+ @pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
67
+ def test_to_numpy_na_value(box):
68
+ con = pd.Series if box else pd.array
69
+
70
+ arr = con([0.0, 1.0, None], dtype="Float64")
71
+ result = arr.to_numpy(dtype=object, na_value=None)
72
+ expected = np.array([0.0, 1.0, None], dtype="object")
73
+ tm.assert_numpy_array_equal(result, expected)
74
+
75
+ result = arr.to_numpy(dtype=bool, na_value=False)
76
+ expected = np.array([False, True, False], dtype="bool")
77
+ tm.assert_numpy_array_equal(result, expected)
78
+
79
+ result = arr.to_numpy(dtype="int64", na_value=-99)
80
+ expected = np.array([0, 1, -99], dtype="int64")
81
+ tm.assert_numpy_array_equal(result, expected)
82
+
83
+
84
+ def test_to_numpy_na_value_with_nan():
85
+ # array with both NaN and NA -> only fill NA with `na_value`
86
+ arr = FloatingArray(np.array([0.0, np.nan, 0.0]), np.array([False, False, True]))
87
+ result = arr.to_numpy(dtype="float64", na_value=-1)
88
+ expected = np.array([0.0, np.nan, -1.0], dtype="float64")
89
+ tm.assert_numpy_array_equal(result, expected)
90
+
91
+
92
+ @pytest.mark.parametrize("dtype", ["float64", "float32", "int32", "int64", "bool"])
93
+ @pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
94
+ def test_to_numpy_dtype(box, dtype):
95
+ con = pd.Series if box else pd.array
96
+ arr = con([0.0, 1.0], dtype="Float64")
97
+
98
+ result = arr.to_numpy(dtype=dtype)
99
+ expected = np.array([0, 1], dtype=dtype)
100
+ tm.assert_numpy_array_equal(result, expected)
101
+
102
+
103
+ @pytest.mark.parametrize("dtype", ["int32", "int64", "bool"])
104
+ @pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
105
+ def test_to_numpy_na_raises(box, dtype):
106
+ con = pd.Series if box else pd.array
107
+ arr = con([0.0, 1.0, None], dtype="Float64")
108
+ with pytest.raises(ValueError, match=dtype):
109
+ arr.to_numpy(dtype=dtype)
110
+
111
+
112
+ @pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
113
+ def test_to_numpy_string(box, dtype):
114
+ con = pd.Series if box else pd.array
115
+ arr = con([0.0, 1.0, None], dtype="Float64")
116
+
117
+ result = arr.to_numpy(dtype="str")
118
+ expected = np.array([0.0, 1.0, pd.NA], dtype=f"{tm.ENDIAN}U32")
119
+ tm.assert_numpy_array_equal(result, expected)
120
+
121
+
122
+ def test_to_numpy_copy():
123
+ # to_numpy can be zero-copy if no missing values
124
+ arr = pd.array([0.1, 0.2, 0.3], dtype="Float64")
125
+ result = arr.to_numpy(dtype="float64")
126
+ result[0] = 10
127
+ tm.assert_extension_array_equal(arr, pd.array([10, 0.2, 0.3], dtype="Float64"))
128
+
129
+ arr = pd.array([0.1, 0.2, 0.3], dtype="Float64")
130
+ result = arr.to_numpy(dtype="float64", copy=True)
131
+ result[0] = 10
132
+ tm.assert_extension_array_equal(arr, pd.array([0.1, 0.2, 0.3], dtype="Float64"))
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_accessor.cpython-310.pyc ADDED
Binary file (9.09 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_arithmetics.cpython-310.pyc ADDED
Binary file (14.1 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_array.cpython-310.pyc ADDED
Binary file (14.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_dtype.cpython-310.pyc ADDED
Binary file (5.73 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_libsparse.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/test_accessor.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import string
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+ from pandas import SparseDtype
8
+ import pandas._testing as tm
9
+ from pandas.core.arrays.sparse import SparseArray
10
+
11
+
12
+ class TestSeriesAccessor:
13
+ def test_to_dense(self):
14
+ ser = pd.Series([0, 1, 0, 10], dtype="Sparse[int64]")
15
+ result = ser.sparse.to_dense()
16
+ expected = pd.Series([0, 1, 0, 10])
17
+ tm.assert_series_equal(result, expected)
18
+
19
+ @pytest.mark.parametrize("attr", ["npoints", "density", "fill_value", "sp_values"])
20
+ def test_get_attributes(self, attr):
21
+ arr = SparseArray([0, 1])
22
+ ser = pd.Series(arr)
23
+
24
+ result = getattr(ser.sparse, attr)
25
+ expected = getattr(arr, attr)
26
+ assert result == expected
27
+
28
+ def test_from_coo(self):
29
+ scipy_sparse = pytest.importorskip("scipy.sparse")
30
+
31
+ row = [0, 3, 1, 0]
32
+ col = [0, 3, 1, 2]
33
+ data = [4, 5, 7, 9]
34
+
35
+ sp_array = scipy_sparse.coo_matrix((data, (row, col)))
36
+ result = pd.Series.sparse.from_coo(sp_array)
37
+
38
+ index = pd.MultiIndex.from_arrays(
39
+ [
40
+ np.array([0, 0, 1, 3], dtype=np.int32),
41
+ np.array([0, 2, 1, 3], dtype=np.int32),
42
+ ],
43
+ )
44
+ expected = pd.Series([4, 9, 7, 5], index=index, dtype="Sparse[int]")
45
+ tm.assert_series_equal(result, expected)
46
+
47
+ @pytest.mark.parametrize(
48
+ "sort_labels, expected_rows, expected_cols, expected_values_pos",
49
+ [
50
+ (
51
+ False,
52
+ [("b", 2), ("a", 2), ("b", 1), ("a", 1)],
53
+ [("z", 1), ("z", 2), ("x", 2), ("z", 0)],
54
+ {1: (1, 0), 3: (3, 3)},
55
+ ),
56
+ (
57
+ True,
58
+ [("a", 1), ("a", 2), ("b", 1), ("b", 2)],
59
+ [("x", 2), ("z", 0), ("z", 1), ("z", 2)],
60
+ {1: (1, 2), 3: (0, 1)},
61
+ ),
62
+ ],
63
+ )
64
+ def test_to_coo(
65
+ self, sort_labels, expected_rows, expected_cols, expected_values_pos
66
+ ):
67
+ sp_sparse = pytest.importorskip("scipy.sparse")
68
+
69
+ values = SparseArray([0, np.nan, 1, 0, None, 3], fill_value=0)
70
+ index = pd.MultiIndex.from_tuples(
71
+ [
72
+ ("b", 2, "z", 1),
73
+ ("a", 2, "z", 2),
74
+ ("a", 2, "z", 1),
75
+ ("a", 2, "x", 2),
76
+ ("b", 1, "z", 1),
77
+ ("a", 1, "z", 0),
78
+ ]
79
+ )
80
+ ss = pd.Series(values, index=index)
81
+
82
+ expected_A = np.zeros((4, 4))
83
+ for value, (row, col) in expected_values_pos.items():
84
+ expected_A[row, col] = value
85
+
86
+ A, rows, cols = ss.sparse.to_coo(
87
+ row_levels=(0, 1), column_levels=(2, 3), sort_labels=sort_labels
88
+ )
89
+ assert isinstance(A, sp_sparse.coo_matrix)
90
+ tm.assert_numpy_array_equal(A.toarray(), expected_A)
91
+ assert rows == expected_rows
92
+ assert cols == expected_cols
93
+
94
+ def test_non_sparse_raises(self):
95
+ ser = pd.Series([1, 2, 3])
96
+ with pytest.raises(AttributeError, match=".sparse"):
97
+ ser.sparse.density
98
+
99
+
100
+ class TestFrameAccessor:
101
+ def test_accessor_raises(self):
102
+ df = pd.DataFrame({"A": [0, 1]})
103
+ with pytest.raises(AttributeError, match="sparse"):
104
+ df.sparse
105
+
106
+ @pytest.mark.parametrize("format", ["csc", "csr", "coo"])
107
+ @pytest.mark.parametrize("labels", [None, list(string.ascii_letters[:10])])
108
+ @pytest.mark.parametrize("dtype", ["float64", "int64"])
109
+ def test_from_spmatrix(self, format, labels, dtype):
110
+ sp_sparse = pytest.importorskip("scipy.sparse")
111
+
112
+ sp_dtype = SparseDtype(dtype, np.array(0, dtype=dtype).item())
113
+
114
+ mat = sp_sparse.eye(10, format=format, dtype=dtype)
115
+ result = pd.DataFrame.sparse.from_spmatrix(mat, index=labels, columns=labels)
116
+ expected = pd.DataFrame(
117
+ np.eye(10, dtype=dtype), index=labels, columns=labels
118
+ ).astype(sp_dtype)
119
+ tm.assert_frame_equal(result, expected)
120
+
121
+ @pytest.mark.parametrize("format", ["csc", "csr", "coo"])
122
+ def test_from_spmatrix_including_explicit_zero(self, format):
123
+ sp_sparse = pytest.importorskip("scipy.sparse")
124
+
125
+ mat = sp_sparse.random(10, 2, density=0.5, format=format)
126
+ mat.data[0] = 0
127
+ result = pd.DataFrame.sparse.from_spmatrix(mat)
128
+ dtype = SparseDtype("float64", 0.0)
129
+ expected = pd.DataFrame(mat.todense()).astype(dtype)
130
+ tm.assert_frame_equal(result, expected)
131
+
132
+ @pytest.mark.parametrize(
133
+ "columns",
134
+ [["a", "b"], pd.MultiIndex.from_product([["A"], ["a", "b"]]), ["a", "a"]],
135
+ )
136
+ def test_from_spmatrix_columns(self, columns):
137
+ sp_sparse = pytest.importorskip("scipy.sparse")
138
+
139
+ dtype = SparseDtype("float64", 0.0)
140
+
141
+ mat = sp_sparse.random(10, 2, density=0.5)
142
+ result = pd.DataFrame.sparse.from_spmatrix(mat, columns=columns)
143
+ expected = pd.DataFrame(mat.toarray(), columns=columns).astype(dtype)
144
+ tm.assert_frame_equal(result, expected)
145
+
146
+ @pytest.mark.parametrize(
147
+ "colnames", [("A", "B"), (1, 2), (1, pd.NA), (0.1, 0.2), ("x", "x"), (0, 0)]
148
+ )
149
+ def test_to_coo(self, colnames):
150
+ sp_sparse = pytest.importorskip("scipy.sparse")
151
+
152
+ df = pd.DataFrame(
153
+ {colnames[0]: [0, 1, 0], colnames[1]: [1, 0, 0]}, dtype="Sparse[int64, 0]"
154
+ )
155
+ result = df.sparse.to_coo()
156
+ expected = sp_sparse.coo_matrix(np.asarray(df))
157
+ assert (result != expected).nnz == 0
158
+
159
+ @pytest.mark.parametrize("fill_value", [1, np.nan])
160
+ def test_to_coo_nonzero_fill_val_raises(self, fill_value):
161
+ pytest.importorskip("scipy")
162
+ df = pd.DataFrame(
163
+ {
164
+ "A": SparseArray(
165
+ [fill_value, fill_value, fill_value, 2], fill_value=fill_value
166
+ ),
167
+ "B": SparseArray(
168
+ [fill_value, 2, fill_value, fill_value], fill_value=fill_value
169
+ ),
170
+ }
171
+ )
172
+ with pytest.raises(ValueError, match="fill value must be 0"):
173
+ df.sparse.to_coo()
174
+
175
+ def test_to_coo_midx_categorical(self):
176
+ # GH#50996
177
+ sp_sparse = pytest.importorskip("scipy.sparse")
178
+
179
+ midx = pd.MultiIndex.from_arrays(
180
+ [
181
+ pd.CategoricalIndex(list("ab"), name="x"),
182
+ pd.CategoricalIndex([0, 1], name="y"),
183
+ ]
184
+ )
185
+
186
+ ser = pd.Series(1, index=midx, dtype="Sparse[int]")
187
+ result = ser.sparse.to_coo(row_levels=["x"], column_levels=["y"])[0]
188
+ expected = sp_sparse.coo_matrix(
189
+ (np.array([1, 1]), (np.array([0, 1]), np.array([0, 1]))), shape=(2, 2)
190
+ )
191
+ assert (result != expected).nnz == 0
192
+
193
+ def test_to_dense(self):
194
+ df = pd.DataFrame(
195
+ {
196
+ "A": SparseArray([1, 0], dtype=SparseDtype("int64", 0)),
197
+ "B": SparseArray([1, 0], dtype=SparseDtype("int64", 1)),
198
+ "C": SparseArray([1.0, 0.0], dtype=SparseDtype("float64", 0.0)),
199
+ },
200
+ index=["b", "a"],
201
+ )
202
+ result = df.sparse.to_dense()
203
+ expected = pd.DataFrame(
204
+ {"A": [1, 0], "B": [1, 0], "C": [1.0, 0.0]}, index=["b", "a"]
205
+ )
206
+ tm.assert_frame_equal(result, expected)
207
+
208
+ def test_density(self):
209
+ df = pd.DataFrame(
210
+ {
211
+ "A": SparseArray([1, 0, 2, 1], fill_value=0),
212
+ "B": SparseArray([0, 1, 1, 1], fill_value=0),
213
+ }
214
+ )
215
+ res = df.sparse.density
216
+ expected = 0.75
217
+ assert res == expected
218
+
219
+ @pytest.mark.parametrize("dtype", ["int64", "float64"])
220
+ @pytest.mark.parametrize("dense_index", [True, False])
221
+ def test_series_from_coo(self, dtype, dense_index):
222
+ sp_sparse = pytest.importorskip("scipy.sparse")
223
+
224
+ A = sp_sparse.eye(3, format="coo", dtype=dtype)
225
+ result = pd.Series.sparse.from_coo(A, dense_index=dense_index)
226
+
227
+ index = pd.MultiIndex.from_tuples(
228
+ [
229
+ np.array([0, 0], dtype=np.int32),
230
+ np.array([1, 1], dtype=np.int32),
231
+ np.array([2, 2], dtype=np.int32),
232
+ ],
233
+ )
234
+ expected = pd.Series(SparseArray(np.array([1, 1, 1], dtype=dtype)), index=index)
235
+ if dense_index:
236
+ expected = expected.reindex(pd.MultiIndex.from_product(index.levels))
237
+
238
+ tm.assert_series_equal(result, expected)
239
+
240
+ def test_series_from_coo_incorrect_format_raises(self):
241
+ # gh-26554
242
+ sp_sparse = pytest.importorskip("scipy.sparse")
243
+
244
+ m = sp_sparse.csr_matrix(np.array([[0, 1], [0, 0]]))
245
+ with pytest.raises(
246
+ TypeError, match="Expected coo_matrix. Got csr_matrix instead."
247
+ ):
248
+ pd.Series.sparse.from_coo(m)
249
+
250
+ def test_with_column_named_sparse(self):
251
+ # https://github.com/pandas-dev/pandas/issues/30758
252
+ df = pd.DataFrame({"sparse": pd.arrays.SparseArray([1, 2])})
253
+ assert isinstance(df.sparse, pd.core.arrays.sparse.accessor.SparseFrameAccessor)
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/test_arithmetics.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+ from pandas import SparseDtype
8
+ import pandas._testing as tm
9
+ from pandas.core.arrays.sparse import SparseArray
10
+
11
+
12
+ @pytest.fixture(params=["integer", "block"])
13
+ def kind(request):
14
+ """kind kwarg to pass to SparseArray"""
15
+ return request.param
16
+
17
+
18
+ @pytest.fixture(params=[True, False])
19
+ def mix(request):
20
+ """
21
+ Fixture returning True or False, determining whether to operate
22
+ op(sparse, dense) instead of op(sparse, sparse)
23
+ """
24
+ return request.param
25
+
26
+
27
+ class TestSparseArrayArithmetics:
28
+ def _assert(self, a, b):
29
+ # We have to use tm.assert_sp_array_equal. See GH #45126
30
+ tm.assert_numpy_array_equal(a, b)
31
+
32
+ def _check_numeric_ops(self, a, b, a_dense, b_dense, mix: bool, op):
33
+ # Check that arithmetic behavior matches non-Sparse Series arithmetic
34
+
35
+ if isinstance(a_dense, np.ndarray):
36
+ expected = op(pd.Series(a_dense), b_dense).values
37
+ elif isinstance(b_dense, np.ndarray):
38
+ expected = op(a_dense, pd.Series(b_dense)).values
39
+ else:
40
+ raise NotImplementedError
41
+
42
+ with np.errstate(invalid="ignore", divide="ignore"):
43
+ if mix:
44
+ result = op(a, b_dense).to_dense()
45
+ else:
46
+ result = op(a, b).to_dense()
47
+
48
+ self._assert(result, expected)
49
+
50
+ def _check_bool_result(self, res):
51
+ assert isinstance(res, SparseArray)
52
+ assert isinstance(res.dtype, SparseDtype)
53
+ assert res.dtype.subtype == np.bool_
54
+ assert isinstance(res.fill_value, bool)
55
+
56
+ def _check_comparison_ops(self, a, b, a_dense, b_dense):
57
+ with np.errstate(invalid="ignore"):
58
+ # Unfortunately, trying to wrap the computation of each expected
59
+ # value is with np.errstate() is too tedious.
60
+ #
61
+ # sparse & sparse
62
+ self._check_bool_result(a == b)
63
+ self._assert((a == b).to_dense(), a_dense == b_dense)
64
+
65
+ self._check_bool_result(a != b)
66
+ self._assert((a != b).to_dense(), a_dense != b_dense)
67
+
68
+ self._check_bool_result(a >= b)
69
+ self._assert((a >= b).to_dense(), a_dense >= b_dense)
70
+
71
+ self._check_bool_result(a <= b)
72
+ self._assert((a <= b).to_dense(), a_dense <= b_dense)
73
+
74
+ self._check_bool_result(a > b)
75
+ self._assert((a > b).to_dense(), a_dense > b_dense)
76
+
77
+ self._check_bool_result(a < b)
78
+ self._assert((a < b).to_dense(), a_dense < b_dense)
79
+
80
+ # sparse & dense
81
+ self._check_bool_result(a == b_dense)
82
+ self._assert((a == b_dense).to_dense(), a_dense == b_dense)
83
+
84
+ self._check_bool_result(a != b_dense)
85
+ self._assert((a != b_dense).to_dense(), a_dense != b_dense)
86
+
87
+ self._check_bool_result(a >= b_dense)
88
+ self._assert((a >= b_dense).to_dense(), a_dense >= b_dense)
89
+
90
+ self._check_bool_result(a <= b_dense)
91
+ self._assert((a <= b_dense).to_dense(), a_dense <= b_dense)
92
+
93
+ self._check_bool_result(a > b_dense)
94
+ self._assert((a > b_dense).to_dense(), a_dense > b_dense)
95
+
96
+ self._check_bool_result(a < b_dense)
97
+ self._assert((a < b_dense).to_dense(), a_dense < b_dense)
98
+
99
+ def _check_logical_ops(self, a, b, a_dense, b_dense):
100
+ # sparse & sparse
101
+ self._check_bool_result(a & b)
102
+ self._assert((a & b).to_dense(), a_dense & b_dense)
103
+
104
+ self._check_bool_result(a | b)
105
+ self._assert((a | b).to_dense(), a_dense | b_dense)
106
+ # sparse & dense
107
+ self._check_bool_result(a & b_dense)
108
+ self._assert((a & b_dense).to_dense(), a_dense & b_dense)
109
+
110
+ self._check_bool_result(a | b_dense)
111
+ self._assert((a | b_dense).to_dense(), a_dense | b_dense)
112
+
113
+ @pytest.mark.parametrize("scalar", [0, 1, 3])
114
+ @pytest.mark.parametrize("fill_value", [None, 0, 2])
115
+ def test_float_scalar(
116
+ self, kind, mix, all_arithmetic_functions, fill_value, scalar, request
117
+ ):
118
+ op = all_arithmetic_functions
119
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
120
+ a = SparseArray(values, kind=kind, fill_value=fill_value)
121
+ self._check_numeric_ops(a, scalar, values, scalar, mix, op)
122
+
123
+ def test_float_scalar_comparison(self, kind):
124
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
125
+
126
+ a = SparseArray(values, kind=kind)
127
+ self._check_comparison_ops(a, 1, values, 1)
128
+ self._check_comparison_ops(a, 0, values, 0)
129
+ self._check_comparison_ops(a, 3, values, 3)
130
+
131
+ a = SparseArray(values, kind=kind, fill_value=0)
132
+ self._check_comparison_ops(a, 1, values, 1)
133
+ self._check_comparison_ops(a, 0, values, 0)
134
+ self._check_comparison_ops(a, 3, values, 3)
135
+
136
+ a = SparseArray(values, kind=kind, fill_value=2)
137
+ self._check_comparison_ops(a, 1, values, 1)
138
+ self._check_comparison_ops(a, 0, values, 0)
139
+ self._check_comparison_ops(a, 3, values, 3)
140
+
141
+ def test_float_same_index_without_nans(self, kind, mix, all_arithmetic_functions):
142
+ # when sp_index are the same
143
+ op = all_arithmetic_functions
144
+
145
+ values = np.array([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0])
146
+ rvalues = np.array([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0])
147
+
148
+ a = SparseArray(values, kind=kind, fill_value=0)
149
+ b = SparseArray(rvalues, kind=kind, fill_value=0)
150
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
151
+
152
+ def test_float_same_index_with_nans(
153
+ self, kind, mix, all_arithmetic_functions, request
154
+ ):
155
+ # when sp_index are the same
156
+ op = all_arithmetic_functions
157
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
158
+ rvalues = np.array([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan])
159
+
160
+ a = SparseArray(values, kind=kind)
161
+ b = SparseArray(rvalues, kind=kind)
162
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
163
+
164
+ def test_float_same_index_comparison(self, kind):
165
+ # when sp_index are the same
166
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
167
+ rvalues = np.array([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan])
168
+
169
+ a = SparseArray(values, kind=kind)
170
+ b = SparseArray(rvalues, kind=kind)
171
+ self._check_comparison_ops(a, b, values, rvalues)
172
+
173
+ values = np.array([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0])
174
+ rvalues = np.array([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0])
175
+
176
+ a = SparseArray(values, kind=kind, fill_value=0)
177
+ b = SparseArray(rvalues, kind=kind, fill_value=0)
178
+ self._check_comparison_ops(a, b, values, rvalues)
179
+
180
+ def test_float_array(self, kind, mix, all_arithmetic_functions):
181
+ op = all_arithmetic_functions
182
+
183
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
184
+ rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])
185
+
186
+ a = SparseArray(values, kind=kind)
187
+ b = SparseArray(rvalues, kind=kind)
188
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
189
+ self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op)
190
+
191
+ a = SparseArray(values, kind=kind, fill_value=0)
192
+ b = SparseArray(rvalues, kind=kind)
193
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
194
+
195
+ a = SparseArray(values, kind=kind, fill_value=0)
196
+ b = SparseArray(rvalues, kind=kind, fill_value=0)
197
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
198
+
199
+ a = SparseArray(values, kind=kind, fill_value=1)
200
+ b = SparseArray(rvalues, kind=kind, fill_value=2)
201
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
202
+
203
+ def test_float_array_different_kind(self, mix, all_arithmetic_functions):
204
+ op = all_arithmetic_functions
205
+
206
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
207
+ rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])
208
+
209
+ a = SparseArray(values, kind="integer")
210
+ b = SparseArray(rvalues, kind="block")
211
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
212
+ self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op)
213
+
214
+ a = SparseArray(values, kind="integer", fill_value=0)
215
+ b = SparseArray(rvalues, kind="block")
216
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
217
+
218
+ a = SparseArray(values, kind="integer", fill_value=0)
219
+ b = SparseArray(rvalues, kind="block", fill_value=0)
220
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
221
+
222
+ a = SparseArray(values, kind="integer", fill_value=1)
223
+ b = SparseArray(rvalues, kind="block", fill_value=2)
224
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
225
+
226
+ def test_float_array_comparison(self, kind):
227
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
228
+ rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])
229
+
230
+ a = SparseArray(values, kind=kind)
231
+ b = SparseArray(rvalues, kind=kind)
232
+ self._check_comparison_ops(a, b, values, rvalues)
233
+ self._check_comparison_ops(a, b * 0, values, rvalues * 0)
234
+
235
+ a = SparseArray(values, kind=kind, fill_value=0)
236
+ b = SparseArray(rvalues, kind=kind)
237
+ self._check_comparison_ops(a, b, values, rvalues)
238
+
239
+ a = SparseArray(values, kind=kind, fill_value=0)
240
+ b = SparseArray(rvalues, kind=kind, fill_value=0)
241
+ self._check_comparison_ops(a, b, values, rvalues)
242
+
243
+ a = SparseArray(values, kind=kind, fill_value=1)
244
+ b = SparseArray(rvalues, kind=kind, fill_value=2)
245
+ self._check_comparison_ops(a, b, values, rvalues)
246
+
247
+ def test_int_array(self, kind, mix, all_arithmetic_functions):
248
+ op = all_arithmetic_functions
249
+
250
+ # have to specify dtype explicitly until fixing GH 667
251
+ dtype = np.int64
252
+
253
+ values = np.array([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype)
254
+ rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype)
255
+
256
+ a = SparseArray(values, dtype=dtype, kind=kind)
257
+ assert a.dtype == SparseDtype(dtype)
258
+ b = SparseArray(rvalues, dtype=dtype, kind=kind)
259
+ assert b.dtype == SparseDtype(dtype)
260
+
261
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
262
+ self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op)
263
+
264
+ a = SparseArray(values, fill_value=0, dtype=dtype, kind=kind)
265
+ assert a.dtype == SparseDtype(dtype)
266
+ b = SparseArray(rvalues, dtype=dtype, kind=kind)
267
+ assert b.dtype == SparseDtype(dtype)
268
+
269
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
270
+
271
+ a = SparseArray(values, fill_value=0, dtype=dtype, kind=kind)
272
+ assert a.dtype == SparseDtype(dtype)
273
+ b = SparseArray(rvalues, fill_value=0, dtype=dtype, kind=kind)
274
+ assert b.dtype == SparseDtype(dtype)
275
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
276
+
277
+ a = SparseArray(values, fill_value=1, dtype=dtype, kind=kind)
278
+ assert a.dtype == SparseDtype(dtype, fill_value=1)
279
+ b = SparseArray(rvalues, fill_value=2, dtype=dtype, kind=kind)
280
+ assert b.dtype == SparseDtype(dtype, fill_value=2)
281
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
282
+
283
+ def test_int_array_comparison(self, kind):
284
+ dtype = "int64"
285
+ # int32 NI ATM
286
+
287
+ values = np.array([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype)
288
+ rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype)
289
+
290
+ a = SparseArray(values, dtype=dtype, kind=kind)
291
+ b = SparseArray(rvalues, dtype=dtype, kind=kind)
292
+ self._check_comparison_ops(a, b, values, rvalues)
293
+ self._check_comparison_ops(a, b * 0, values, rvalues * 0)
294
+
295
+ a = SparseArray(values, dtype=dtype, kind=kind, fill_value=0)
296
+ b = SparseArray(rvalues, dtype=dtype, kind=kind)
297
+ self._check_comparison_ops(a, b, values, rvalues)
298
+
299
+ a = SparseArray(values, dtype=dtype, kind=kind, fill_value=0)
300
+ b = SparseArray(rvalues, dtype=dtype, kind=kind, fill_value=0)
301
+ self._check_comparison_ops(a, b, values, rvalues)
302
+
303
+ a = SparseArray(values, dtype=dtype, kind=kind, fill_value=1)
304
+ b = SparseArray(rvalues, dtype=dtype, kind=kind, fill_value=2)
305
+ self._check_comparison_ops(a, b, values, rvalues)
306
+
307
+ @pytest.mark.parametrize("fill_value", [True, False, np.nan])
308
+ def test_bool_same_index(self, kind, fill_value):
309
+ # GH 14000
310
+ # when sp_index are the same
311
+ values = np.array([True, False, True, True], dtype=np.bool_)
312
+ rvalues = np.array([True, False, True, True], dtype=np.bool_)
313
+
314
+ a = SparseArray(values, kind=kind, dtype=np.bool_, fill_value=fill_value)
315
+ b = SparseArray(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value)
316
+ self._check_logical_ops(a, b, values, rvalues)
317
+
318
+ @pytest.mark.parametrize("fill_value", [True, False, np.nan])
319
+ def test_bool_array_logical(self, kind, fill_value):
320
+ # GH 14000
321
+ # when sp_index are the same
322
+ values = np.array([True, False, True, False, True, True], dtype=np.bool_)
323
+ rvalues = np.array([True, False, False, True, False, True], dtype=np.bool_)
324
+
325
+ a = SparseArray(values, kind=kind, dtype=np.bool_, fill_value=fill_value)
326
+ b = SparseArray(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value)
327
+ self._check_logical_ops(a, b, values, rvalues)
328
+
329
+ def test_mixed_array_float_int(self, kind, mix, all_arithmetic_functions, request):
330
+ op = all_arithmetic_functions
331
+ rdtype = "int64"
332
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
333
+ rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype)
334
+
335
+ a = SparseArray(values, kind=kind)
336
+ b = SparseArray(rvalues, kind=kind)
337
+ assert b.dtype == SparseDtype(rdtype)
338
+
339
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
340
+ self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op)
341
+
342
+ a = SparseArray(values, kind=kind, fill_value=0)
343
+ b = SparseArray(rvalues, kind=kind)
344
+ assert b.dtype == SparseDtype(rdtype)
345
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
346
+
347
+ a = SparseArray(values, kind=kind, fill_value=0)
348
+ b = SparseArray(rvalues, kind=kind, fill_value=0)
349
+ assert b.dtype == SparseDtype(rdtype)
350
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
351
+
352
+ a = SparseArray(values, kind=kind, fill_value=1)
353
+ b = SparseArray(rvalues, kind=kind, fill_value=2)
354
+ assert b.dtype == SparseDtype(rdtype, fill_value=2)
355
+ self._check_numeric_ops(a, b, values, rvalues, mix, op)
356
+
357
+ def test_mixed_array_comparison(self, kind):
358
+ rdtype = "int64"
359
+ # int32 NI ATM
360
+
361
+ values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
362
+ rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype)
363
+
364
+ a = SparseArray(values, kind=kind)
365
+ b = SparseArray(rvalues, kind=kind)
366
+ assert b.dtype == SparseDtype(rdtype)
367
+
368
+ self._check_comparison_ops(a, b, values, rvalues)
369
+ self._check_comparison_ops(a, b * 0, values, rvalues * 0)
370
+
371
+ a = SparseArray(values, kind=kind, fill_value=0)
372
+ b = SparseArray(rvalues, kind=kind)
373
+ assert b.dtype == SparseDtype(rdtype)
374
+ self._check_comparison_ops(a, b, values, rvalues)
375
+
376
+ a = SparseArray(values, kind=kind, fill_value=0)
377
+ b = SparseArray(rvalues, kind=kind, fill_value=0)
378
+ assert b.dtype == SparseDtype(rdtype)
379
+ self._check_comparison_ops(a, b, values, rvalues)
380
+
381
+ a = SparseArray(values, kind=kind, fill_value=1)
382
+ b = SparseArray(rvalues, kind=kind, fill_value=2)
383
+ assert b.dtype == SparseDtype(rdtype, fill_value=2)
384
+ self._check_comparison_ops(a, b, values, rvalues)
385
+
386
+ def test_xor(self):
387
+ s = SparseArray([True, True, False, False])
388
+ t = SparseArray([True, False, True, False])
389
+ result = s ^ t
390
+ sp_index = pd.core.arrays.sparse.IntIndex(4, np.array([0, 1, 2], dtype="int32"))
391
+ expected = SparseArray([False, True, True], sparse_index=sp_index)
392
+ tm.assert_sp_array_equal(result, expected)
393
+
394
+
395
+ @pytest.mark.parametrize("op", [operator.eq, operator.add])
396
+ def test_with_list(op):
397
+ arr = SparseArray([0, 1], fill_value=0)
398
+ result = op(arr, [0, 1])
399
+ expected = op(arr, SparseArray([0, 1]))
400
+ tm.assert_sp_array_equal(result, expected)
401
+
402
+
403
+ def test_with_dataframe():
404
+ # GH#27910
405
+ arr = SparseArray([0, 1], fill_value=0)
406
+ df = pd.DataFrame([[1, 2], [3, 4]])
407
+ result = arr.__add__(df)
408
+ assert result is NotImplemented
409
+
410
+
411
+ def test_with_zerodim_ndarray():
412
+ # GH#27910
413
+ arr = SparseArray([0, 1], fill_value=0)
414
+
415
+ result = arr * np.array(2)
416
+ expected = arr * 2
417
+ tm.assert_sp_array_equal(result, expected)
418
+
419
+
420
+ @pytest.mark.parametrize("ufunc", [np.abs, np.exp])
421
+ @pytest.mark.parametrize(
422
+ "arr", [SparseArray([0, 0, -1, 1]), SparseArray([None, None, -1, 1])]
423
+ )
424
+ def test_ufuncs(ufunc, arr):
425
+ result = ufunc(arr)
426
+ fill_value = ufunc(arr.fill_value)
427
+ expected = SparseArray(ufunc(np.asarray(arr)), fill_value=fill_value)
428
+ tm.assert_sp_array_equal(result, expected)
429
+
430
+
431
+ @pytest.mark.parametrize(
432
+ "a, b",
433
+ [
434
+ (SparseArray([0, 0, 0]), np.array([0, 1, 2])),
435
+ (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),
436
+ (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),
437
+ (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),
438
+ (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),
439
+ ],
440
+ )
441
+ @pytest.mark.parametrize("ufunc", [np.add, np.greater])
442
+ def test_binary_ufuncs(ufunc, a, b):
443
+ # can't say anything about fill value here.
444
+ result = ufunc(a, b)
445
+ expected = ufunc(np.asarray(a), np.asarray(b))
446
+ assert isinstance(result, SparseArray)
447
+ tm.assert_numpy_array_equal(np.asarray(result), expected)
448
+
449
+
450
+ def test_ndarray_inplace():
451
+ sparray = SparseArray([0, 2, 0, 0])
452
+ ndarray = np.array([0, 1, 2, 3])
453
+ ndarray += sparray
454
+ expected = np.array([0, 3, 2, 3])
455
+ tm.assert_numpy_array_equal(ndarray, expected)
456
+
457
+
458
+ def test_sparray_inplace():
459
+ sparray = SparseArray([0, 2, 0, 0])
460
+ ndarray = np.array([0, 1, 2, 3])
461
+ sparray += ndarray
462
+ expected = SparseArray([0, 3, 2, 3], fill_value=0)
463
+ tm.assert_sp_array_equal(sparray, expected)
464
+
465
+
466
+ @pytest.mark.parametrize("cons", [list, np.array, SparseArray])
467
+ def test_mismatched_length_cmp_op(cons):
468
+ left = SparseArray([True, True])
469
+ right = cons([True, True, True])
470
+ with pytest.raises(ValueError, match="operands have mismatched length"):
471
+ left & right
472
+
473
+
474
+ @pytest.mark.parametrize("op", ["add", "sub", "mul", "truediv", "floordiv", "pow"])
475
+ @pytest.mark.parametrize("fill_value", [np.nan, 3])
476
+ def test_binary_operators(op, fill_value):
477
+ op = getattr(operator, op)
478
+ data1 = np.random.default_rng(2).standard_normal(20)
479
+ data2 = np.random.default_rng(2).standard_normal(20)
480
+
481
+ data1[::2] = fill_value
482
+ data2[::3] = fill_value
483
+
484
+ first = SparseArray(data1, fill_value=fill_value)
485
+ second = SparseArray(data2, fill_value=fill_value)
486
+
487
+ with np.errstate(all="ignore"):
488
+ res = op(first, second)
489
+ exp = SparseArray(
490
+ op(first.to_dense(), second.to_dense()), fill_value=first.fill_value
491
+ )
492
+ assert isinstance(res, SparseArray)
493
+ tm.assert_almost_equal(res.to_dense(), exp.to_dense())
494
+
495
+ res2 = op(first, second.to_dense())
496
+ assert isinstance(res2, SparseArray)
497
+ tm.assert_sp_array_equal(res, res2)
498
+
499
+ res3 = op(first.to_dense(), second)
500
+ assert isinstance(res3, SparseArray)
501
+ tm.assert_sp_array_equal(res, res3)
502
+
503
+ res4 = op(first, 4)
504
+ assert isinstance(res4, SparseArray)
505
+
506
+ # Ignore this if the actual op raises (e.g. pow).
507
+ try:
508
+ exp = op(first.to_dense(), 4)
509
+ exp_fv = op(first.fill_value, 4)
510
+ except ValueError:
511
+ pass
512
+ else:
513
+ tm.assert_almost_equal(res4.fill_value, exp_fv)
514
+ tm.assert_almost_equal(res4.to_dense(), exp)
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/test_array.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas._libs.sparse import IntIndex
7
+
8
+ import pandas as pd
9
+ from pandas import (
10
+ SparseDtype,
11
+ isna,
12
+ )
13
+ import pandas._testing as tm
14
+ from pandas.core.arrays.sparse import SparseArray
15
+
16
+
17
+ @pytest.fixture
18
+ def arr_data():
19
+ """Fixture returning numpy array with valid and missing entries"""
20
+ return np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6])
21
+
22
+
23
+ @pytest.fixture
24
+ def arr(arr_data):
25
+ """Fixture returning SparseArray from 'arr_data'"""
26
+ return SparseArray(arr_data)
27
+
28
+
29
+ @pytest.fixture
30
+ def zarr():
31
+ """Fixture returning SparseArray with integer entries and 'fill_value=0'"""
32
+ return SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0)
33
+
34
+
35
+ class TestSparseArray:
36
+ @pytest.mark.parametrize("fill_value", [0, None, np.nan])
37
+ def test_shift_fill_value(self, fill_value):
38
+ # GH #24128
39
+ sparse = SparseArray(np.array([1, 0, 0, 3, 0]), fill_value=8.0)
40
+ res = sparse.shift(1, fill_value=fill_value)
41
+ if isna(fill_value):
42
+ fill_value = res.dtype.na_value
43
+ exp = SparseArray(np.array([fill_value, 1, 0, 0, 3]), fill_value=8.0)
44
+ tm.assert_sp_array_equal(res, exp)
45
+
46
+ def test_set_fill_value(self):
47
+ arr = SparseArray([1.0, np.nan, 2.0], fill_value=np.nan)
48
+ arr.fill_value = 2
49
+ assert arr.fill_value == 2
50
+
51
+ arr = SparseArray([1, 0, 2], fill_value=0, dtype=np.int64)
52
+ arr.fill_value = 2
53
+ assert arr.fill_value == 2
54
+
55
+ msg = "Allowing arbitrary scalar fill_value in SparseDtype is deprecated"
56
+ with tm.assert_produces_warning(FutureWarning, match=msg):
57
+ arr.fill_value = 3.1
58
+ assert arr.fill_value == 3.1
59
+
60
+ arr.fill_value = np.nan
61
+ assert np.isnan(arr.fill_value)
62
+
63
+ arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_)
64
+ arr.fill_value = True
65
+ assert arr.fill_value is True
66
+
67
+ with tm.assert_produces_warning(FutureWarning, match=msg):
68
+ arr.fill_value = 0
69
+
70
+ arr.fill_value = np.nan
71
+ assert np.isnan(arr.fill_value)
72
+
73
+ @pytest.mark.parametrize("val", [[1, 2, 3], np.array([1, 2]), (1, 2, 3)])
74
+ def test_set_fill_invalid_non_scalar(self, val):
75
+ arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_)
76
+ msg = "fill_value must be a scalar"
77
+
78
+ with pytest.raises(ValueError, match=msg):
79
+ arr.fill_value = val
80
+
81
+ def test_copy(self, arr):
82
+ arr2 = arr.copy()
83
+ assert arr2.sp_values is not arr.sp_values
84
+ assert arr2.sp_index is arr.sp_index
85
+
86
+ def test_values_asarray(self, arr_data, arr):
87
+ tm.assert_almost_equal(arr.to_dense(), arr_data)
88
+
89
+ @pytest.mark.parametrize(
90
+ "data,shape,dtype",
91
+ [
92
+ ([0, 0, 0, 0, 0], (5,), None),
93
+ ([], (0,), None),
94
+ ([0], (1,), None),
95
+ (["A", "A", np.nan, "B"], (4,), object),
96
+ ],
97
+ )
98
+ def test_shape(self, data, shape, dtype):
99
+ # GH 21126
100
+ out = SparseArray(data, dtype=dtype)
101
+ assert out.shape == shape
102
+
103
+ @pytest.mark.parametrize(
104
+ "vals",
105
+ [
106
+ [np.nan, np.nan, np.nan, np.nan, np.nan],
107
+ [1, np.nan, np.nan, 3, np.nan],
108
+ [1, np.nan, 0, 3, 0],
109
+ ],
110
+ )
111
+ @pytest.mark.parametrize("fill_value", [None, 0])
112
+ def test_dense_repr(self, vals, fill_value):
113
+ vals = np.array(vals)
114
+ arr = SparseArray(vals, fill_value=fill_value)
115
+
116
+ res = arr.to_dense()
117
+ tm.assert_numpy_array_equal(res, vals)
118
+
119
+ @pytest.mark.parametrize("fix", ["arr", "zarr"])
120
+ def test_pickle(self, fix, request):
121
+ obj = request.getfixturevalue(fix)
122
+ unpickled = tm.round_trip_pickle(obj)
123
+ tm.assert_sp_array_equal(unpickled, obj)
124
+
125
+ def test_generator_warnings(self):
126
+ sp_arr = SparseArray([1, 2, 3])
127
+ with tm.assert_produces_warning(None):
128
+ for _ in sp_arr:
129
+ pass
130
+
131
+ def test_where_retain_fill_value(self):
132
+ # GH#45691 don't lose fill_value on _where
133
+ arr = SparseArray([np.nan, 1.0], fill_value=0)
134
+
135
+ mask = np.array([True, False])
136
+
137
+ res = arr._where(~mask, 1)
138
+ exp = SparseArray([1, 1.0], fill_value=0)
139
+ tm.assert_sp_array_equal(res, exp)
140
+
141
+ ser = pd.Series(arr)
142
+ res = ser.where(~mask, 1)
143
+ tm.assert_series_equal(res, pd.Series(exp))
144
+
145
+ def test_fillna(self):
146
+ s = SparseArray([1, np.nan, np.nan, 3, np.nan])
147
+ res = s.fillna(-1)
148
+ exp = SparseArray([1, -1, -1, 3, -1], fill_value=-1, dtype=np.float64)
149
+ tm.assert_sp_array_equal(res, exp)
150
+
151
+ s = SparseArray([1, np.nan, np.nan, 3, np.nan], fill_value=0)
152
+ res = s.fillna(-1)
153
+ exp = SparseArray([1, -1, -1, 3, -1], fill_value=0, dtype=np.float64)
154
+ tm.assert_sp_array_equal(res, exp)
155
+
156
+ s = SparseArray([1, np.nan, 0, 3, 0])
157
+ res = s.fillna(-1)
158
+ exp = SparseArray([1, -1, 0, 3, 0], fill_value=-1, dtype=np.float64)
159
+ tm.assert_sp_array_equal(res, exp)
160
+
161
+ s = SparseArray([1, np.nan, 0, 3, 0], fill_value=0)
162
+ res = s.fillna(-1)
163
+ exp = SparseArray([1, -1, 0, 3, 0], fill_value=0, dtype=np.float64)
164
+ tm.assert_sp_array_equal(res, exp)
165
+
166
+ s = SparseArray([np.nan, np.nan, np.nan, np.nan])
167
+ res = s.fillna(-1)
168
+ exp = SparseArray([-1, -1, -1, -1], fill_value=-1, dtype=np.float64)
169
+ tm.assert_sp_array_equal(res, exp)
170
+
171
+ s = SparseArray([np.nan, np.nan, np.nan, np.nan], fill_value=0)
172
+ res = s.fillna(-1)
173
+ exp = SparseArray([-1, -1, -1, -1], fill_value=0, dtype=np.float64)
174
+ tm.assert_sp_array_equal(res, exp)
175
+
176
+ # float dtype's fill_value is np.nan, replaced by -1
177
+ s = SparseArray([0.0, 0.0, 0.0, 0.0])
178
+ res = s.fillna(-1)
179
+ exp = SparseArray([0.0, 0.0, 0.0, 0.0], fill_value=-1)
180
+ tm.assert_sp_array_equal(res, exp)
181
+
182
+ # int dtype shouldn't have missing. No changes.
183
+ s = SparseArray([0, 0, 0, 0])
184
+ assert s.dtype == SparseDtype(np.int64)
185
+ assert s.fill_value == 0
186
+ res = s.fillna(-1)
187
+ tm.assert_sp_array_equal(res, s)
188
+
189
+ s = SparseArray([0, 0, 0, 0], fill_value=0)
190
+ assert s.dtype == SparseDtype(np.int64)
191
+ assert s.fill_value == 0
192
+ res = s.fillna(-1)
193
+ exp = SparseArray([0, 0, 0, 0], fill_value=0)
194
+ tm.assert_sp_array_equal(res, exp)
195
+
196
+ # fill_value can be nan if there is no missing hole.
197
+ # only fill_value will be changed
198
+ s = SparseArray([0, 0, 0, 0], fill_value=np.nan)
199
+ assert s.dtype == SparseDtype(np.int64, fill_value=np.nan)
200
+ assert np.isnan(s.fill_value)
201
+ res = s.fillna(-1)
202
+ exp = SparseArray([0, 0, 0, 0], fill_value=-1)
203
+ tm.assert_sp_array_equal(res, exp)
204
+
205
+ def test_fillna_overlap(self):
206
+ s = SparseArray([1, np.nan, np.nan, 3, np.nan])
207
+ # filling with existing value doesn't replace existing value with
208
+ # fill_value, i.e. existing 3 remains in sp_values
209
+ res = s.fillna(3)
210
+ exp = np.array([1, 3, 3, 3, 3], dtype=np.float64)
211
+ tm.assert_numpy_array_equal(res.to_dense(), exp)
212
+
213
+ s = SparseArray([1, np.nan, np.nan, 3, np.nan], fill_value=0)
214
+ res = s.fillna(3)
215
+ exp = SparseArray([1, 3, 3, 3, 3], fill_value=0, dtype=np.float64)
216
+ tm.assert_sp_array_equal(res, exp)
217
+
218
+ def test_nonzero(self):
219
+ # Tests regression #21172.
220
+ sa = SparseArray([float("nan"), float("nan"), 1, 0, 0, 2, 0, 0, 0, 3, 0, 0])
221
+ expected = np.array([2, 5, 9], dtype=np.int32)
222
+ (result,) = sa.nonzero()
223
+ tm.assert_numpy_array_equal(expected, result)
224
+
225
+ sa = SparseArray([0, 0, 1, 0, 0, 2, 0, 0, 0, 3, 0, 0])
226
+ (result,) = sa.nonzero()
227
+ tm.assert_numpy_array_equal(expected, result)
228
+
229
+
230
+ class TestSparseArrayAnalytics:
231
+ @pytest.mark.parametrize(
232
+ "data,expected",
233
+ [
234
+ (
235
+ np.array([1, 2, 3, 4, 5], dtype=float), # non-null data
236
+ SparseArray(np.array([1.0, 3.0, 6.0, 10.0, 15.0])),
237
+ ),
238
+ (
239
+ np.array([1, 2, np.nan, 4, 5], dtype=float), # null data
240
+ SparseArray(np.array([1.0, 3.0, np.nan, 7.0, 12.0])),
241
+ ),
242
+ ],
243
+ )
244
+ @pytest.mark.parametrize("numpy", [True, False])
245
+ def test_cumsum(self, data, expected, numpy):
246
+ cumsum = np.cumsum if numpy else lambda s: s.cumsum()
247
+
248
+ out = cumsum(SparseArray(data))
249
+ tm.assert_sp_array_equal(out, expected)
250
+
251
+ out = cumsum(SparseArray(data, fill_value=np.nan))
252
+ tm.assert_sp_array_equal(out, expected)
253
+
254
+ out = cumsum(SparseArray(data, fill_value=2))
255
+ tm.assert_sp_array_equal(out, expected)
256
+
257
+ if numpy: # numpy compatibility checks.
258
+ msg = "the 'dtype' parameter is not supported"
259
+ with pytest.raises(ValueError, match=msg):
260
+ np.cumsum(SparseArray(data), dtype=np.int64)
261
+
262
+ msg = "the 'out' parameter is not supported"
263
+ with pytest.raises(ValueError, match=msg):
264
+ np.cumsum(SparseArray(data), out=out)
265
+ else:
266
+ axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid.
267
+ msg = re.escape(f"axis(={axis}) out of bounds")
268
+ with pytest.raises(ValueError, match=msg):
269
+ SparseArray(data).cumsum(axis=axis)
270
+
271
+ def test_ufunc(self):
272
+ # GH 13853 make sure ufunc is applied to fill_value
273
+ sparse = SparseArray([1, np.nan, 2, np.nan, -2])
274
+ result = SparseArray([1, np.nan, 2, np.nan, 2])
275
+ tm.assert_sp_array_equal(abs(sparse), result)
276
+ tm.assert_sp_array_equal(np.abs(sparse), result)
277
+
278
+ sparse = SparseArray([1, -1, 2, -2], fill_value=1)
279
+ result = SparseArray([1, 2, 2], sparse_index=sparse.sp_index, fill_value=1)
280
+ tm.assert_sp_array_equal(abs(sparse), result)
281
+ tm.assert_sp_array_equal(np.abs(sparse), result)
282
+
283
+ sparse = SparseArray([1, -1, 2, -2], fill_value=-1)
284
+ exp = SparseArray([1, 1, 2, 2], fill_value=1)
285
+ tm.assert_sp_array_equal(abs(sparse), exp)
286
+ tm.assert_sp_array_equal(np.abs(sparse), exp)
287
+
288
+ sparse = SparseArray([1, np.nan, 2, np.nan, -2])
289
+ result = SparseArray(np.sin([1, np.nan, 2, np.nan, -2]))
290
+ tm.assert_sp_array_equal(np.sin(sparse), result)
291
+
292
+ sparse = SparseArray([1, -1, 2, -2], fill_value=1)
293
+ result = SparseArray(np.sin([1, -1, 2, -2]), fill_value=np.sin(1))
294
+ tm.assert_sp_array_equal(np.sin(sparse), result)
295
+
296
+ sparse = SparseArray([1, -1, 0, -2], fill_value=0)
297
+ result = SparseArray(np.sin([1, -1, 0, -2]), fill_value=np.sin(0))
298
+ tm.assert_sp_array_equal(np.sin(sparse), result)
299
+
300
+ def test_ufunc_args(self):
301
+ # GH 13853 make sure ufunc is applied to fill_value, including its arg
302
+ sparse = SparseArray([1, np.nan, 2, np.nan, -2])
303
+ result = SparseArray([2, np.nan, 3, np.nan, -1])
304
+ tm.assert_sp_array_equal(np.add(sparse, 1), result)
305
+
306
+ sparse = SparseArray([1, -1, 2, -2], fill_value=1)
307
+ result = SparseArray([2, 0, 3, -1], fill_value=2)
308
+ tm.assert_sp_array_equal(np.add(sparse, 1), result)
309
+
310
+ sparse = SparseArray([1, -1, 0, -2], fill_value=0)
311
+ result = SparseArray([2, 0, 1, -1], fill_value=1)
312
+ tm.assert_sp_array_equal(np.add(sparse, 1), result)
313
+
314
+ @pytest.mark.parametrize("fill_value", [0.0, np.nan])
315
+ def test_modf(self, fill_value):
316
+ # https://github.com/pandas-dev/pandas/issues/26946
317
+ sparse = SparseArray([fill_value] * 10 + [1.1, 2.2], fill_value=fill_value)
318
+ r1, r2 = np.modf(sparse)
319
+ e1, e2 = np.modf(np.asarray(sparse))
320
+ tm.assert_sp_array_equal(r1, SparseArray(e1, fill_value=fill_value))
321
+ tm.assert_sp_array_equal(r2, SparseArray(e2, fill_value=fill_value))
322
+
323
+ def test_nbytes_integer(self):
324
+ arr = SparseArray([1, 0, 0, 0, 2], kind="integer")
325
+ result = arr.nbytes
326
+ # (2 * 8) + 2 * 4
327
+ assert result == 24
328
+
329
+ def test_nbytes_block(self):
330
+ arr = SparseArray([1, 2, 0, 0, 0], kind="block")
331
+ result = arr.nbytes
332
+ # (2 * 8) + 4 + 4
333
+ # sp_values, blocs, blengths
334
+ assert result == 24
335
+
336
+ def test_asarray_datetime64(self):
337
+ s = SparseArray(pd.to_datetime(["2012", None, None, "2013"]))
338
+ np.asarray(s)
339
+
340
+ def test_density(self):
341
+ arr = SparseArray([0, 1])
342
+ assert arr.density == 0.5
343
+
344
+ def test_npoints(self):
345
+ arr = SparseArray([0, 1])
346
+ assert arr.npoints == 1
347
+
348
+
349
+ def test_setting_fill_value_fillna_still_works():
350
+ # This is why letting users update fill_value / dtype is bad
351
+ # astype has the same problem.
352
+ arr = SparseArray([1.0, np.nan, 1.0], fill_value=0.0)
353
+ arr.fill_value = np.nan
354
+ result = arr.isna()
355
+ # Can't do direct comparison, since the sp_index will be different
356
+ # So let's convert to ndarray and check there.
357
+ result = np.asarray(result)
358
+
359
+ expected = np.array([False, True, False])
360
+ tm.assert_numpy_array_equal(result, expected)
361
+
362
+
363
+ def test_setting_fill_value_updates():
364
+ arr = SparseArray([0.0, np.nan], fill_value=0)
365
+ arr.fill_value = np.nan
366
+ # use private constructor to get the index right
367
+ # otherwise both nans would be un-stored.
368
+ expected = SparseArray._simple_new(
369
+ sparse_array=np.array([np.nan]),
370
+ sparse_index=IntIndex(2, [1]),
371
+ dtype=SparseDtype(float, np.nan),
372
+ )
373
+ tm.assert_sp_array_equal(arr, expected)
374
+
375
+
376
+ @pytest.mark.parametrize(
377
+ "arr,fill_value,loc",
378
+ [
379
+ ([None, 1, 2], None, 0),
380
+ ([0, None, 2], None, 1),
381
+ ([0, 1, None], None, 2),
382
+ ([0, 1, 1, None, None], None, 3),
383
+ ([1, 1, 1, 2], None, -1),
384
+ ([], None, -1),
385
+ ([None, 1, 0, 0, None, 2], None, 0),
386
+ ([None, 1, 0, 0, None, 2], 1, 1),
387
+ ([None, 1, 0, 0, None, 2], 2, 5),
388
+ ([None, 1, 0, 0, None, 2], 3, -1),
389
+ ([None, 0, 0, 1, 2, 1], 0, 1),
390
+ ([None, 0, 0, 1, 2, 1], 1, 3),
391
+ ],
392
+ )
393
+ def test_first_fill_value_loc(arr, fill_value, loc):
394
+ result = SparseArray(arr, fill_value=fill_value)._first_fill_value_loc()
395
+ assert result == loc
396
+
397
+
398
+ @pytest.mark.parametrize(
399
+ "arr",
400
+ [
401
+ [1, 2, np.nan, np.nan],
402
+ [1, np.nan, 2, np.nan],
403
+ [1, 2, np.nan],
404
+ [np.nan, 1, 0, 0, np.nan, 2],
405
+ [np.nan, 0, 0, 1, 2, 1],
406
+ ],
407
+ )
408
+ @pytest.mark.parametrize("fill_value", [np.nan, 0, 1])
409
+ def test_unique_na_fill(arr, fill_value):
410
+ a = SparseArray(arr, fill_value=fill_value).unique()
411
+ b = pd.Series(arr).unique()
412
+ assert isinstance(a, SparseArray)
413
+ a = np.asarray(a)
414
+ tm.assert_numpy_array_equal(a, b)
415
+
416
+
417
+ def test_unique_all_sparse():
418
+ # https://github.com/pandas-dev/pandas/issues/23168
419
+ arr = SparseArray([0, 0])
420
+ result = arr.unique()
421
+ expected = SparseArray([0])
422
+ tm.assert_sp_array_equal(result, expected)
423
+
424
+
425
+ def test_map():
426
+ arr = SparseArray([0, 1, 2])
427
+ expected = SparseArray([10, 11, 12], fill_value=10)
428
+
429
+ # dict
430
+ result = arr.map({0: 10, 1: 11, 2: 12})
431
+ tm.assert_sp_array_equal(result, expected)
432
+
433
+ # series
434
+ result = arr.map(pd.Series({0: 10, 1: 11, 2: 12}))
435
+ tm.assert_sp_array_equal(result, expected)
436
+
437
+ # function
438
+ result = arr.map(pd.Series({0: 10, 1: 11, 2: 12}))
439
+ expected = SparseArray([10, 11, 12], fill_value=10)
440
+ tm.assert_sp_array_equal(result, expected)
441
+
442
+
443
+ def test_map_missing():
444
+ arr = SparseArray([0, 1, 2])
445
+ expected = SparseArray([10, 11, None], fill_value=10)
446
+
447
+ result = arr.map({0: 10, 1: 11})
448
+ tm.assert_sp_array_equal(result, expected)
449
+
450
+
451
+ @pytest.mark.parametrize("fill_value", [np.nan, 1])
452
+ def test_dropna(fill_value):
453
+ # GH-28287
454
+ arr = SparseArray([np.nan, 1], fill_value=fill_value)
455
+ exp = SparseArray([1.0], fill_value=fill_value)
456
+ tm.assert_sp_array_equal(arr.dropna(), exp)
457
+
458
+ df = pd.DataFrame({"a": [0, 1], "b": arr})
459
+ expected_df = pd.DataFrame({"a": [1], "b": exp}, index=pd.Index([1]))
460
+ tm.assert_equal(df.dropna(), expected_df)
461
+
462
+
463
+ def test_drop_duplicates_fill_value():
464
+ # GH 11726
465
+ df = pd.DataFrame(np.zeros((5, 5))).apply(lambda x: SparseArray(x, fill_value=0))
466
+ result = df.drop_duplicates()
467
+ expected = pd.DataFrame({i: SparseArray([0.0], fill_value=0) for i in range(5)})
468
+ tm.assert_frame_equal(result, expected)
469
+
470
+
471
+ def test_zero_sparse_column():
472
+ # GH 27781
473
+ df1 = pd.DataFrame({"A": SparseArray([0, 0, 0]), "B": [1, 2, 3]})
474
+ df2 = pd.DataFrame({"A": SparseArray([0, 1, 0]), "B": [1, 2, 3]})
475
+ result = df1.loc[df1["B"] != 2]
476
+ expected = df2.loc[df2["B"] != 2]
477
+ tm.assert_frame_equal(result, expected)
478
+
479
+ expected = pd.DataFrame({"A": SparseArray([0, 0]), "B": [1, 3]}, index=[0, 2])
480
+ tm.assert_frame_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/test_astype.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._libs.sparse import IntIndex
5
+
6
+ from pandas import (
7
+ SparseDtype,
8
+ Timestamp,
9
+ )
10
+ import pandas._testing as tm
11
+ from pandas.core.arrays.sparse import SparseArray
12
+
13
+
14
+ class TestAstype:
15
+ def test_astype(self):
16
+ # float -> float
17
+ arr = SparseArray([None, None, 0, 2])
18
+ result = arr.astype("Sparse[float32]")
19
+ expected = SparseArray([None, None, 0, 2], dtype=np.dtype("float32"))
20
+ tm.assert_sp_array_equal(result, expected)
21
+
22
+ dtype = SparseDtype("float64", fill_value=0)
23
+ result = arr.astype(dtype)
24
+ expected = SparseArray._simple_new(
25
+ np.array([0.0, 2.0], dtype=dtype.subtype), IntIndex(4, [2, 3]), dtype
26
+ )
27
+ tm.assert_sp_array_equal(result, expected)
28
+
29
+ dtype = SparseDtype("int64", 0)
30
+ result = arr.astype(dtype)
31
+ expected = SparseArray._simple_new(
32
+ np.array([0, 2], dtype=np.int64), IntIndex(4, [2, 3]), dtype
33
+ )
34
+ tm.assert_sp_array_equal(result, expected)
35
+
36
+ arr = SparseArray([0, np.nan, 0, 1], fill_value=0)
37
+ with pytest.raises(ValueError, match="NA"):
38
+ arr.astype("Sparse[i8]")
39
+
40
+ def test_astype_bool(self):
41
+ a = SparseArray([1, 0, 0, 1], dtype=SparseDtype(int, 0))
42
+ result = a.astype(bool)
43
+ expected = np.array([1, 0, 0, 1], dtype=bool)
44
+ tm.assert_numpy_array_equal(result, expected)
45
+
46
+ # update fill value
47
+ result = a.astype(SparseDtype(bool, False))
48
+ expected = SparseArray(
49
+ [True, False, False, True], dtype=SparseDtype(bool, False)
50
+ )
51
+ tm.assert_sp_array_equal(result, expected)
52
+
53
+ def test_astype_all(self, any_real_numpy_dtype):
54
+ vals = np.array([1, 2, 3])
55
+ arr = SparseArray(vals, fill_value=1)
56
+ typ = np.dtype(any_real_numpy_dtype)
57
+ res = arr.astype(typ)
58
+ tm.assert_numpy_array_equal(res, vals.astype(any_real_numpy_dtype))
59
+
60
+ @pytest.mark.parametrize(
61
+ "arr, dtype, expected",
62
+ [
63
+ (
64
+ SparseArray([0, 1]),
65
+ "float",
66
+ SparseArray([0.0, 1.0], dtype=SparseDtype(float, 0.0)),
67
+ ),
68
+ (SparseArray([0, 1]), bool, SparseArray([False, True])),
69
+ (
70
+ SparseArray([0, 1], fill_value=1),
71
+ bool,
72
+ SparseArray([False, True], dtype=SparseDtype(bool, True)),
73
+ ),
74
+ pytest.param(
75
+ SparseArray([0, 1]),
76
+ "datetime64[ns]",
77
+ SparseArray(
78
+ np.array([0, 1], dtype="datetime64[ns]"),
79
+ dtype=SparseDtype("datetime64[ns]", Timestamp("1970")),
80
+ ),
81
+ ),
82
+ (
83
+ SparseArray([0, 1, 10]),
84
+ str,
85
+ SparseArray(["0", "1", "10"], dtype=SparseDtype(str, "0")),
86
+ ),
87
+ (SparseArray(["10", "20"]), float, SparseArray([10.0, 20.0])),
88
+ (
89
+ SparseArray([0, 1, 0]),
90
+ object,
91
+ SparseArray([0, 1, 0], dtype=SparseDtype(object, 0)),
92
+ ),
93
+ ],
94
+ )
95
+ def test_astype_more(self, arr, dtype, expected):
96
+ result = arr.astype(arr.dtype.update_dtype(dtype))
97
+ tm.assert_sp_array_equal(result, expected)
98
+
99
+ def test_astype_nan_raises(self):
100
+ arr = SparseArray([1.0, np.nan])
101
+ with pytest.raises(ValueError, match="Cannot convert non-finite"):
102
+ arr.astype(int)
103
+
104
+ def test_astype_copy_false(self):
105
+ # GH#34456 bug caused by using .view instead of .astype in astype_nansafe
106
+ arr = SparseArray([1, 2, 3])
107
+
108
+ dtype = SparseDtype(float, 0)
109
+
110
+ result = arr.astype(dtype, copy=False)
111
+ expected = SparseArray([1.0, 2.0, 3.0], fill_value=0.0)
112
+ tm.assert_sp_array_equal(result, expected)
113
+
114
+ def test_astype_dt64_to_int64(self):
115
+ # GH#49631 match non-sparse behavior
116
+ values = np.array(["NaT", "2016-01-02", "2016-01-03"], dtype="M8[ns]")
117
+
118
+ arr = SparseArray(values)
119
+ result = arr.astype("int64")
120
+ expected = values.astype("int64")
121
+ tm.assert_numpy_array_equal(result, expected)
122
+
123
+ # we should also be able to cast to equivalent Sparse[int64]
124
+ dtype_int64 = SparseDtype("int64", np.iinfo(np.int64).min)
125
+ result2 = arr.astype(dtype_int64)
126
+ tm.assert_numpy_array_equal(result2.to_numpy(), expected)
127
+
128
+ # GH#50087 we should match the non-sparse behavior regardless of
129
+ # if we have a fill_value other than NaT
130
+ dtype = SparseDtype("datetime64[ns]", values[1])
131
+ arr3 = SparseArray(values, dtype=dtype)
132
+ result3 = arr3.astype("int64")
133
+ tm.assert_numpy_array_equal(result3, expected)