applied-ai-018 commited on
Commit
55a1ea5
·
verified ·
1 Parent(s): 1da99b6

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_154_mp_rank_02_optim_states.pt +3 -0
  2. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_21_mp_rank_00_optim_states.pt +3 -0
  3. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_239_mp_rank_02_optim_states.pt +3 -0
  4. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_78_mp_rank_00_optim_states.pt +3 -0
  5. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_92_mp_rank_01_optim_states.pt +3 -0
  6. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/conftest.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_at.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_categorical.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_chaining_and_caching.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_coercion.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_floats.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iat.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iloc.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexing.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_loc.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_na_indexing.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_partial.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/__init__.py +0 -0
  19. venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval.py +227 -0
  20. venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_multiindex.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_slice.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/pandas/tests/internals/__init__.py +0 -0
  23. venv/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/__init__.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_api.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_internals.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_managers.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/pandas/tests/internals/test_api.py +86 -0
  28. venv/lib/python3.10/site-packages/pandas/tests/internals/test_internals.py +1422 -0
  29. venv/lib/python3.10/site-packages/pandas/tests/internals/test_managers.py +103 -0
  30. venv/lib/python3.10/site-packages/pandas/tests/series/__init__.py +0 -0
  31. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/__init__.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_api.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_constructors.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_cumulative.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_formats.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_iteration.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_logical_ops.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_missing.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_npfuncs.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_reductions.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_subclass.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_ufunc.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_unary.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_validate.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__init__.py +0 -0
  47. venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__pycache__/__init__.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__pycache__/test_cat_accessor.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__pycache__/test_list_accessor.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__pycache__/test_sparse_accessor.cpython-310.pyc +0 -0
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_154_mp_rank_02_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c12da66071dd9401416b3c8580432ab018803543ac3dbc698b984a5b303b3fa
3
+ size 41830340
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_21_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76bb8375dc5d377e2c83c124898c72eca4a971cba91b03ea93e055f3ba6c1777
3
+ size 41830138
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_239_mp_rank_02_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d00a94ebaf98e3cb257ca75c5b6f08b5eff9390a9820a9a17764a6ce4927de4
3
+ size 41830340
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_78_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9358076afb92f578440362e7ab096cd1a880fef74a9270b1fc9326b25e27ad3
3
+ size 41830138
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_92_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d6deaa2e1ee352bdaaa3e9a3a4df2f2fbea38cca99fbbffec5c29f28b62d5b5
3
+ size 41830202
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (3.54 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_at.cpython-310.pyc ADDED
Binary file (8.55 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_categorical.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_chaining_and_caching.cpython-310.pyc ADDED
Binary file (19.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_coercion.cpython-310.pyc ADDED
Binary file (25.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_floats.cpython-310.pyc ADDED
Binary file (14.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iat.cpython-310.pyc ADDED
Binary file (1.73 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iloc.cpython-310.pyc ADDED
Binary file (44.7 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (31.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_loc.cpython-310.pyc ADDED
Binary file (108 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_na_indexing.cpython-310.pyc ADDED
Binary file (1.95 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_partial.cpython-310.pyc ADDED
Binary file (19.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._libs import index as libindex
5
+ from pandas.compat import IS64
6
+
7
+ import pandas as pd
8
+ from pandas import (
9
+ DataFrame,
10
+ IntervalIndex,
11
+ Series,
12
+ )
13
+ import pandas._testing as tm
14
+
15
+
16
+ class TestIntervalIndex:
17
+ @pytest.fixture
18
+ def series_with_interval_index(self):
19
+ return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
20
+
21
+ def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl):
22
+ ser = series_with_interval_index.copy()
23
+
24
+ expected = ser.iloc[:3]
25
+ tm.assert_series_equal(expected, indexer_sl(ser)[:3])
26
+ tm.assert_series_equal(expected, indexer_sl(ser)[:2.5])
27
+ tm.assert_series_equal(expected, indexer_sl(ser)[0.1:2.5])
28
+ if indexer_sl is tm.loc:
29
+ tm.assert_series_equal(expected, ser.loc[-1:3])
30
+
31
+ expected = ser.iloc[1:4]
32
+ tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]])
33
+ tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]])
34
+ tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]])
35
+
36
+ expected = ser.iloc[2:5]
37
+ tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2])
38
+
39
+ @pytest.mark.parametrize("direction", ["increasing", "decreasing"])
40
+ def test_getitem_nonoverlapping_monotonic(self, direction, closed, indexer_sl):
41
+ tpls = [(0, 1), (2, 3), (4, 5)]
42
+ if direction == "decreasing":
43
+ tpls = tpls[::-1]
44
+
45
+ idx = IntervalIndex.from_tuples(tpls, closed=closed)
46
+ ser = Series(list("abc"), idx)
47
+
48
+ for key, expected in zip(idx.left, ser):
49
+ if idx.closed_left:
50
+ assert indexer_sl(ser)[key] == expected
51
+ else:
52
+ with pytest.raises(KeyError, match=str(key)):
53
+ indexer_sl(ser)[key]
54
+
55
+ for key, expected in zip(idx.right, ser):
56
+ if idx.closed_right:
57
+ assert indexer_sl(ser)[key] == expected
58
+ else:
59
+ with pytest.raises(KeyError, match=str(key)):
60
+ indexer_sl(ser)[key]
61
+
62
+ for key, expected in zip(idx.mid, ser):
63
+ assert indexer_sl(ser)[key] == expected
64
+
65
+ def test_getitem_non_matching(self, series_with_interval_index, indexer_sl):
66
+ ser = series_with_interval_index.copy()
67
+
68
+ # this is a departure from our current
69
+ # indexing scheme, but simpler
70
+ with pytest.raises(KeyError, match=r"\[-1\] not in index"):
71
+ indexer_sl(ser)[[-1, 3, 4, 5]]
72
+
73
+ with pytest.raises(KeyError, match=r"\[-1\] not in index"):
74
+ indexer_sl(ser)[[-1, 3]]
75
+
76
+ def test_loc_getitem_large_series(self, monkeypatch):
77
+ size_cutoff = 20
78
+ with monkeypatch.context():
79
+ monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff)
80
+ ser = Series(
81
+ np.arange(size_cutoff),
82
+ index=IntervalIndex.from_breaks(np.arange(size_cutoff + 1)),
83
+ )
84
+
85
+ result1 = ser.loc[:8]
86
+ result2 = ser.loc[0:8]
87
+ result3 = ser.loc[0:8:1]
88
+ tm.assert_series_equal(result1, result2)
89
+ tm.assert_series_equal(result1, result3)
90
+
91
+ def test_loc_getitem_frame(self):
92
+ # CategoricalIndex with IntervalIndex categories
93
+ df = DataFrame({"A": range(10)})
94
+ ser = pd.cut(df.A, 5)
95
+ df["B"] = ser
96
+ df = df.set_index("B")
97
+
98
+ result = df.loc[4]
99
+ expected = df.iloc[4:6]
100
+ tm.assert_frame_equal(result, expected)
101
+
102
+ with pytest.raises(KeyError, match="10"):
103
+ df.loc[10]
104
+
105
+ # single list-like
106
+ result = df.loc[[4]]
107
+ expected = df.iloc[4:6]
108
+ tm.assert_frame_equal(result, expected)
109
+
110
+ # non-unique
111
+ result = df.loc[[4, 5]]
112
+ expected = df.take([4, 5, 4, 5])
113
+ tm.assert_frame_equal(result, expected)
114
+
115
+ msg = (
116
+ r"None of \[Index\(\[10\], dtype='object', name='B'\)\] "
117
+ r"are in the \[index\]"
118
+ )
119
+ with pytest.raises(KeyError, match=msg):
120
+ df.loc[[10]]
121
+
122
+ # partial missing
123
+ with pytest.raises(KeyError, match=r"\[10\] not in index"):
124
+ df.loc[[10, 4]]
125
+
126
+ def test_getitem_interval_with_nans(self, frame_or_series, indexer_sl):
127
+ # GH#41831
128
+
129
+ index = IntervalIndex([np.nan, np.nan])
130
+ key = index[:-1]
131
+
132
+ obj = frame_or_series(range(2), index=index)
133
+ if frame_or_series is DataFrame and indexer_sl is tm.setitem:
134
+ obj = obj.T
135
+
136
+ result = indexer_sl(obj)[key]
137
+ expected = obj
138
+
139
+ tm.assert_equal(result, expected)
140
+
141
+ def test_setitem_interval_with_slice(self):
142
+ # GH#54722
143
+ ii = IntervalIndex.from_breaks(range(4, 15))
144
+ ser = Series(range(10), index=ii)
145
+
146
+ orig = ser.copy()
147
+
148
+ # This should be a no-op (used to raise)
149
+ ser.loc[1:3] = 20
150
+ tm.assert_series_equal(ser, orig)
151
+
152
+ ser.loc[6:8] = 19
153
+ orig.iloc[1:4] = 19
154
+ tm.assert_series_equal(ser, orig)
155
+
156
+ ser2 = Series(range(5), index=ii[::2])
157
+ orig2 = ser2.copy()
158
+
159
+ # this used to raise
160
+ ser2.loc[6:8] = 22 # <- raises on main, sets on branch
161
+ orig2.iloc[1] = 22
162
+ tm.assert_series_equal(ser2, orig2)
163
+
164
+ ser2.loc[5:7] = 21
165
+ orig2.iloc[:2] = 21
166
+ tm.assert_series_equal(ser2, orig2)
167
+
168
+
169
+ class TestIntervalIndexInsideMultiIndex:
170
+ def test_mi_intervalindex_slicing_with_scalar(self):
171
+ # GH#27456
172
+ ii = IntervalIndex.from_arrays(
173
+ [0, 1, 10, 11, 0, 1, 10, 11], [1, 2, 11, 12, 1, 2, 11, 12], name="MP"
174
+ )
175
+ idx = pd.MultiIndex.from_arrays(
176
+ [
177
+ pd.Index(["FC", "FC", "FC", "FC", "OWNER", "OWNER", "OWNER", "OWNER"]),
178
+ pd.Index(
179
+ ["RID1", "RID1", "RID2", "RID2", "RID1", "RID1", "RID2", "RID2"]
180
+ ),
181
+ ii,
182
+ ]
183
+ )
184
+
185
+ idx.names = ["Item", "RID", "MP"]
186
+ df = DataFrame({"value": [1, 2, 3, 4, 5, 6, 7, 8]})
187
+ df.index = idx
188
+
189
+ query_df = DataFrame(
190
+ {
191
+ "Item": ["FC", "OWNER", "FC", "OWNER", "OWNER"],
192
+ "RID": ["RID1", "RID1", "RID1", "RID2", "RID2"],
193
+ "MP": [0.2, 1.5, 1.6, 11.1, 10.9],
194
+ }
195
+ )
196
+
197
+ query_df = query_df.sort_index()
198
+
199
+ idx = pd.MultiIndex.from_arrays([query_df.Item, query_df.RID, query_df.MP])
200
+ query_df.index = idx
201
+ result = df.value.loc[query_df.index]
202
+
203
+ # the IntervalIndex level is indexed with floats, which map to
204
+ # the intervals containing them. Matching the behavior we would get
205
+ # with _only_ an IntervalIndex, we get an IntervalIndex level back.
206
+ sliced_level = ii.take([0, 1, 1, 3, 2])
207
+ expected_index = pd.MultiIndex.from_arrays(
208
+ [idx.get_level_values(0), idx.get_level_values(1), sliced_level]
209
+ )
210
+ expected = Series([1, 6, 2, 8, 7], index=expected_index, name="value")
211
+ tm.assert_series_equal(result, expected)
212
+
213
+ @pytest.mark.xfail(not IS64, reason="GH 23440")
214
+ @pytest.mark.parametrize(
215
+ "base",
216
+ [101, 1010],
217
+ )
218
+ def test_reindex_behavior_with_interval_index(self, base):
219
+ # GH 51826
220
+
221
+ ser = Series(
222
+ range(base),
223
+ index=IntervalIndex.from_arrays(range(base), range(1, base + 1)),
224
+ )
225
+ expected_result = Series([np.nan, 0], index=[np.nan, 1.0], dtype=float)
226
+ result = ser.reindex(index=[np.nan, 1.0])
227
+ tm.assert_series_equal(result, expected_result)
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_multiindex.cpython-310.pyc ADDED
Binary file (7.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_slice.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/internals/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_api.cpython-310.pyc ADDED
Binary file (2.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_internals.cpython-310.pyc ADDED
Binary file (40.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_managers.cpython-310.pyc ADDED
Binary file (3.08 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/internals/test_api.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for the pseudo-public API implemented in internals/api.py and exposed
3
+ in core.internals
4
+ """
5
+
6
+ import pytest
7
+
8
+ import pandas as pd
9
+ import pandas._testing as tm
10
+ from pandas.core import internals
11
+ from pandas.core.internals import api
12
+
13
+
14
+ def test_internals_api():
15
+ assert internals.make_block is api.make_block
16
+
17
+
18
+ def test_namespace():
19
+ # SUBJECT TO CHANGE
20
+
21
+ modules = [
22
+ "blocks",
23
+ "concat",
24
+ "managers",
25
+ "construction",
26
+ "array_manager",
27
+ "base",
28
+ "api",
29
+ "ops",
30
+ ]
31
+ expected = [
32
+ "make_block",
33
+ "DataManager",
34
+ "ArrayManager",
35
+ "BlockManager",
36
+ "SingleDataManager",
37
+ "SingleBlockManager",
38
+ "SingleArrayManager",
39
+ "concatenate_managers",
40
+ ]
41
+
42
+ result = [x for x in dir(internals) if not x.startswith("__")]
43
+ assert set(result) == set(expected + modules)
44
+
45
+
46
+ @pytest.mark.parametrize(
47
+ "name",
48
+ [
49
+ "NumericBlock",
50
+ "ObjectBlock",
51
+ "Block",
52
+ "ExtensionBlock",
53
+ "DatetimeTZBlock",
54
+ ],
55
+ )
56
+ def test_deprecations(name):
57
+ # GH#55139
58
+ msg = f"{name} is deprecated.* Use public APIs instead"
59
+ with tm.assert_produces_warning(DeprecationWarning, match=msg):
60
+ getattr(internals, name)
61
+
62
+ if name not in ["NumericBlock", "ObjectBlock"]:
63
+ # NumericBlock and ObjectBlock are not in the internals.api namespace
64
+ with tm.assert_produces_warning(DeprecationWarning, match=msg):
65
+ getattr(api, name)
66
+
67
+
68
+ def test_make_block_2d_with_dti():
69
+ # GH#41168
70
+ dti = pd.date_range("2012", periods=3, tz="UTC")
71
+ blk = api.make_block(dti, placement=[0])
72
+
73
+ assert blk.shape == (1, 3)
74
+ assert blk.values.shape == (1, 3)
75
+
76
+
77
+ def test_create_block_manager_from_blocks_deprecated():
78
+ # GH#33892
79
+ # If they must, downstream packages should get this from internals.api,
80
+ # not internals.
81
+ msg = (
82
+ "create_block_manager_from_blocks is deprecated and will be "
83
+ "removed in a future version. Use public APIs instead"
84
+ )
85
+ with tm.assert_produces_warning(DeprecationWarning, match=msg):
86
+ internals.create_block_manager_from_blocks
venv/lib/python3.10/site-packages/pandas/tests/internals/test_internals.py ADDED
@@ -0,0 +1,1422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ date,
3
+ datetime,
4
+ )
5
+ import itertools
6
+ import re
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from pandas._libs.internals import BlockPlacement
12
+ from pandas.compat import IS64
13
+ import pandas.util._test_decorators as td
14
+
15
+ from pandas.core.dtypes.common import is_scalar
16
+
17
+ import pandas as pd
18
+ from pandas import (
19
+ Categorical,
20
+ DataFrame,
21
+ DatetimeIndex,
22
+ Index,
23
+ IntervalIndex,
24
+ Series,
25
+ Timedelta,
26
+ Timestamp,
27
+ period_range,
28
+ )
29
+ import pandas._testing as tm
30
+ import pandas.core.algorithms as algos
31
+ from pandas.core.arrays import (
32
+ DatetimeArray,
33
+ SparseArray,
34
+ TimedeltaArray,
35
+ )
36
+ from pandas.core.internals import (
37
+ BlockManager,
38
+ SingleBlockManager,
39
+ make_block,
40
+ )
41
+ from pandas.core.internals.blocks import (
42
+ ensure_block_shape,
43
+ maybe_coerce_values,
44
+ new_block,
45
+ )
46
+
47
+ # this file contains BlockManager specific tests
48
+ # TODO(ArrayManager) factor out interleave_dtype tests
49
+ pytestmark = td.skip_array_manager_invalid_test
50
+
51
+
52
+ @pytest.fixture(params=[new_block, make_block])
53
+ def block_maker(request):
54
+ """
55
+ Fixture to test both the internal new_block and pseudo-public make_block.
56
+ """
57
+ return request.param
58
+
59
+
60
+ @pytest.fixture
61
+ def mgr():
62
+ return create_mgr(
63
+ "a: f8; b: object; c: f8; d: object; e: f8;"
64
+ "f: bool; g: i8; h: complex; i: datetime-1; j: datetime-2;"
65
+ "k: M8[ns, US/Eastern]; l: M8[ns, CET];"
66
+ )
67
+
68
+
69
+ def assert_block_equal(left, right):
70
+ tm.assert_numpy_array_equal(left.values, right.values)
71
+ assert left.dtype == right.dtype
72
+ assert isinstance(left.mgr_locs, BlockPlacement)
73
+ assert isinstance(right.mgr_locs, BlockPlacement)
74
+ tm.assert_numpy_array_equal(left.mgr_locs.as_array, right.mgr_locs.as_array)
75
+
76
+
77
+ def get_numeric_mat(shape):
78
+ arr = np.arange(shape[0])
79
+ return np.lib.stride_tricks.as_strided(
80
+ x=arr, shape=shape, strides=(arr.itemsize,) + (0,) * (len(shape) - 1)
81
+ ).copy()
82
+
83
+
84
+ N = 10
85
+
86
+
87
+ def create_block(typestr, placement, item_shape=None, num_offset=0, maker=new_block):
88
+ """
89
+ Supported typestr:
90
+
91
+ * float, f8, f4, f2
92
+ * int, i8, i4, i2, i1
93
+ * uint, u8, u4, u2, u1
94
+ * complex, c16, c8
95
+ * bool
96
+ * object, string, O
97
+ * datetime, dt, M8[ns], M8[ns, tz]
98
+ * timedelta, td, m8[ns]
99
+ * sparse (SparseArray with fill_value=0.0)
100
+ * sparse_na (SparseArray with fill_value=np.nan)
101
+ * category, category2
102
+
103
+ """
104
+ placement = BlockPlacement(placement)
105
+ num_items = len(placement)
106
+
107
+ if item_shape is None:
108
+ item_shape = (N,)
109
+
110
+ shape = (num_items,) + item_shape
111
+
112
+ mat = get_numeric_mat(shape)
113
+
114
+ if typestr in (
115
+ "float",
116
+ "f8",
117
+ "f4",
118
+ "f2",
119
+ "int",
120
+ "i8",
121
+ "i4",
122
+ "i2",
123
+ "i1",
124
+ "uint",
125
+ "u8",
126
+ "u4",
127
+ "u2",
128
+ "u1",
129
+ ):
130
+ values = mat.astype(typestr) + num_offset
131
+ elif typestr in ("complex", "c16", "c8"):
132
+ values = 1.0j * (mat.astype(typestr) + num_offset)
133
+ elif typestr in ("object", "string", "O"):
134
+ values = np.reshape([f"A{i:d}" for i in mat.ravel() + num_offset], shape)
135
+ elif typestr in ("b", "bool"):
136
+ values = np.ones(shape, dtype=np.bool_)
137
+ elif typestr in ("datetime", "dt", "M8[ns]"):
138
+ values = (mat * 1e9).astype("M8[ns]")
139
+ elif typestr.startswith("M8[ns"):
140
+ # datetime with tz
141
+ m = re.search(r"M8\[ns,\s*(\w+\/?\w*)\]", typestr)
142
+ assert m is not None, f"incompatible typestr -> {typestr}"
143
+ tz = m.groups()[0]
144
+ assert num_items == 1, "must have only 1 num items for a tz-aware"
145
+ values = DatetimeIndex(np.arange(N) * 10**9, tz=tz)._data
146
+ values = ensure_block_shape(values, ndim=len(shape))
147
+ elif typestr in ("timedelta", "td", "m8[ns]"):
148
+ values = (mat * 1).astype("m8[ns]")
149
+ elif typestr in ("category",):
150
+ values = Categorical([1, 1, 2, 2, 3, 3, 3, 3, 4, 4])
151
+ elif typestr in ("category2",):
152
+ values = Categorical(["a", "a", "a", "a", "b", "b", "c", "c", "c", "d"])
153
+ elif typestr in ("sparse", "sparse_na"):
154
+ if shape[-1] != 10:
155
+ # We also are implicitly assuming this in the category cases above
156
+ raise NotImplementedError
157
+
158
+ assert all(s == 1 for s in shape[:-1])
159
+ if typestr.endswith("_na"):
160
+ fill_value = np.nan
161
+ else:
162
+ fill_value = 0.0
163
+ values = SparseArray(
164
+ [fill_value, fill_value, 1, 2, 3, fill_value, 4, 5, fill_value, 6],
165
+ fill_value=fill_value,
166
+ )
167
+ arr = values.sp_values.view()
168
+ arr += num_offset - 1
169
+ else:
170
+ raise ValueError(f'Unsupported typestr: "{typestr}"')
171
+
172
+ values = maybe_coerce_values(values)
173
+ return maker(values, placement=placement, ndim=len(shape))
174
+
175
+
176
+ def create_single_mgr(typestr, num_rows=None):
177
+ if num_rows is None:
178
+ num_rows = N
179
+
180
+ return SingleBlockManager(
181
+ create_block(typestr, placement=slice(0, num_rows), item_shape=()),
182
+ Index(np.arange(num_rows)),
183
+ )
184
+
185
+
186
+ def create_mgr(descr, item_shape=None):
187
+ """
188
+ Construct BlockManager from string description.
189
+
190
+ String description syntax looks similar to np.matrix initializer. It looks
191
+ like this::
192
+
193
+ a,b,c: f8; d,e,f: i8
194
+
195
+ Rules are rather simple:
196
+
197
+ * see list of supported datatypes in `create_block` method
198
+ * components are semicolon-separated
199
+ * each component is `NAME,NAME,NAME: DTYPE_ID`
200
+ * whitespace around colons & semicolons are removed
201
+ * components with same DTYPE_ID are combined into single block
202
+ * to force multiple blocks with same dtype, use '-SUFFIX'::
203
+
204
+ 'a:f8-1; b:f8-2; c:f8-foobar'
205
+
206
+ """
207
+ if item_shape is None:
208
+ item_shape = (N,)
209
+
210
+ offset = 0
211
+ mgr_items = []
212
+ block_placements = {}
213
+ for d in descr.split(";"):
214
+ d = d.strip()
215
+ if not len(d):
216
+ continue
217
+ names, blockstr = d.partition(":")[::2]
218
+ blockstr = blockstr.strip()
219
+ names = names.strip().split(",")
220
+
221
+ mgr_items.extend(names)
222
+ placement = list(np.arange(len(names)) + offset)
223
+ try:
224
+ block_placements[blockstr].extend(placement)
225
+ except KeyError:
226
+ block_placements[blockstr] = placement
227
+ offset += len(names)
228
+
229
+ mgr_items = Index(mgr_items)
230
+
231
+ blocks = []
232
+ num_offset = 0
233
+ for blockstr, placement in block_placements.items():
234
+ typestr = blockstr.split("-")[0]
235
+ blocks.append(
236
+ create_block(
237
+ typestr, placement, item_shape=item_shape, num_offset=num_offset
238
+ )
239
+ )
240
+ num_offset += len(placement)
241
+
242
+ sblocks = sorted(blocks, key=lambda b: b.mgr_locs[0])
243
+ return BlockManager(
244
+ tuple(sblocks),
245
+ [mgr_items] + [Index(np.arange(n)) for n in item_shape],
246
+ )
247
+
248
+
249
+ @pytest.fixture
250
+ def fblock():
251
+ return create_block("float", [0, 2, 4])
252
+
253
+
254
+ class TestBlock:
255
+ def test_constructor(self):
256
+ int32block = create_block("i4", [0])
257
+ assert int32block.dtype == np.int32
258
+
259
+ @pytest.mark.parametrize(
260
+ "typ, data",
261
+ [
262
+ ["float", [0, 2, 4]],
263
+ ["complex", [7]],
264
+ ["object", [1, 3]],
265
+ ["bool", [5]],
266
+ ],
267
+ )
268
+ def test_pickle(self, typ, data):
269
+ blk = create_block(typ, data)
270
+ assert_block_equal(tm.round_trip_pickle(blk), blk)
271
+
272
+ def test_mgr_locs(self, fblock):
273
+ assert isinstance(fblock.mgr_locs, BlockPlacement)
274
+ tm.assert_numpy_array_equal(
275
+ fblock.mgr_locs.as_array, np.array([0, 2, 4], dtype=np.intp)
276
+ )
277
+
278
+ def test_attrs(self, fblock):
279
+ assert fblock.shape == fblock.values.shape
280
+ assert fblock.dtype == fblock.values.dtype
281
+ assert len(fblock) == len(fblock.values)
282
+
283
+ def test_copy(self, fblock):
284
+ cop = fblock.copy()
285
+ assert cop is not fblock
286
+ assert_block_equal(fblock, cop)
287
+
288
+ def test_delete(self, fblock):
289
+ newb = fblock.copy()
290
+ locs = newb.mgr_locs
291
+ nb = newb.delete(0)[0]
292
+ assert newb.mgr_locs is locs
293
+
294
+ assert nb is not newb
295
+
296
+ tm.assert_numpy_array_equal(
297
+ nb.mgr_locs.as_array, np.array([2, 4], dtype=np.intp)
298
+ )
299
+ assert not (newb.values[0] == 1).all()
300
+ assert (nb.values[0] == 1).all()
301
+
302
+ newb = fblock.copy()
303
+ locs = newb.mgr_locs
304
+ nb = newb.delete(1)
305
+ assert len(nb) == 2
306
+ assert newb.mgr_locs is locs
307
+
308
+ tm.assert_numpy_array_equal(
309
+ nb[0].mgr_locs.as_array, np.array([0], dtype=np.intp)
310
+ )
311
+ tm.assert_numpy_array_equal(
312
+ nb[1].mgr_locs.as_array, np.array([4], dtype=np.intp)
313
+ )
314
+ assert not (newb.values[1] == 2).all()
315
+ assert (nb[1].values[0] == 2).all()
316
+
317
+ newb = fblock.copy()
318
+ nb = newb.delete(2)
319
+ assert len(nb) == 1
320
+ tm.assert_numpy_array_equal(
321
+ nb[0].mgr_locs.as_array, np.array([0, 2], dtype=np.intp)
322
+ )
323
+ assert (nb[0].values[1] == 1).all()
324
+
325
+ newb = fblock.copy()
326
+
327
+ with pytest.raises(IndexError, match=None):
328
+ newb.delete(3)
329
+
330
+ def test_delete_datetimelike(self):
331
+ # dont use np.delete on values, as that will coerce from DTA/TDA to ndarray
332
+ arr = np.arange(20, dtype="i8").reshape(5, 4).view("m8[ns]")
333
+ df = DataFrame(arr)
334
+ blk = df._mgr.blocks[0]
335
+ assert isinstance(blk.values, TimedeltaArray)
336
+
337
+ nb = blk.delete(1)
338
+ assert len(nb) == 2
339
+ assert isinstance(nb[0].values, TimedeltaArray)
340
+ assert isinstance(nb[1].values, TimedeltaArray)
341
+
342
+ df = DataFrame(arr.view("M8[ns]"))
343
+ blk = df._mgr.blocks[0]
344
+ assert isinstance(blk.values, DatetimeArray)
345
+
346
+ nb = blk.delete([1, 3])
347
+ assert len(nb) == 2
348
+ assert isinstance(nb[0].values, DatetimeArray)
349
+ assert isinstance(nb[1].values, DatetimeArray)
350
+
351
+ def test_split(self):
352
+ # GH#37799
353
+ values = np.random.default_rng(2).standard_normal((3, 4))
354
+ blk = new_block(values, placement=BlockPlacement([3, 1, 6]), ndim=2)
355
+ result = blk._split()
356
+
357
+ # check that we get views, not copies
358
+ values[:] = -9999
359
+ assert (blk.values == -9999).all()
360
+
361
+ assert len(result) == 3
362
+ expected = [
363
+ new_block(values[[0]], placement=BlockPlacement([3]), ndim=2),
364
+ new_block(values[[1]], placement=BlockPlacement([1]), ndim=2),
365
+ new_block(values[[2]], placement=BlockPlacement([6]), ndim=2),
366
+ ]
367
+ for res, exp in zip(result, expected):
368
+ assert_block_equal(res, exp)
369
+
370
+
371
+ class TestBlockManager:
372
+ def test_attrs(self):
373
+ mgr = create_mgr("a,b,c: f8-1; d,e,f: f8-2")
374
+ assert mgr.nblocks == 2
375
+ assert len(mgr) == 6
376
+
377
+ def test_duplicate_ref_loc_failure(self):
378
+ tmp_mgr = create_mgr("a:bool; a: f8")
379
+
380
+ axes, blocks = tmp_mgr.axes, tmp_mgr.blocks
381
+
382
+ blocks[0].mgr_locs = BlockPlacement(np.array([0]))
383
+ blocks[1].mgr_locs = BlockPlacement(np.array([0]))
384
+
385
+ # test trying to create block manager with overlapping ref locs
386
+
387
+ msg = "Gaps in blk ref_locs"
388
+
389
+ with pytest.raises(AssertionError, match=msg):
390
+ mgr = BlockManager(blocks, axes)
391
+ mgr._rebuild_blknos_and_blklocs()
392
+
393
+ blocks[0].mgr_locs = BlockPlacement(np.array([0]))
394
+ blocks[1].mgr_locs = BlockPlacement(np.array([1]))
395
+ mgr = BlockManager(blocks, axes)
396
+ mgr.iget(1)
397
+
398
+ def test_pickle(self, mgr):
399
+ mgr2 = tm.round_trip_pickle(mgr)
400
+ tm.assert_frame_equal(
401
+ DataFrame._from_mgr(mgr, axes=mgr.axes),
402
+ DataFrame._from_mgr(mgr2, axes=mgr2.axes),
403
+ )
404
+
405
+ # GH2431
406
+ assert hasattr(mgr2, "_is_consolidated")
407
+ assert hasattr(mgr2, "_known_consolidated")
408
+
409
+ # reset to False on load
410
+ assert not mgr2._is_consolidated
411
+ assert not mgr2._known_consolidated
412
+
413
+ @pytest.mark.parametrize("mgr_string", ["a,a,a:f8", "a: f8; a: i8"])
414
+ def test_non_unique_pickle(self, mgr_string):
415
+ mgr = create_mgr(mgr_string)
416
+ mgr2 = tm.round_trip_pickle(mgr)
417
+ tm.assert_frame_equal(
418
+ DataFrame._from_mgr(mgr, axes=mgr.axes),
419
+ DataFrame._from_mgr(mgr2, axes=mgr2.axes),
420
+ )
421
+
422
+ def test_categorical_block_pickle(self):
423
+ mgr = create_mgr("a: category")
424
+ mgr2 = tm.round_trip_pickle(mgr)
425
+ tm.assert_frame_equal(
426
+ DataFrame._from_mgr(mgr, axes=mgr.axes),
427
+ DataFrame._from_mgr(mgr2, axes=mgr2.axes),
428
+ )
429
+
430
+ smgr = create_single_mgr("category")
431
+ smgr2 = tm.round_trip_pickle(smgr)
432
+ tm.assert_series_equal(
433
+ Series()._constructor_from_mgr(smgr, axes=smgr.axes),
434
+ Series()._constructor_from_mgr(smgr2, axes=smgr2.axes),
435
+ )
436
+
437
+ def test_iget(self):
438
+ cols = Index(list("abc"))
439
+ values = np.random.default_rng(2).random((3, 3))
440
+ block = new_block(
441
+ values=values.copy(),
442
+ placement=BlockPlacement(np.arange(3, dtype=np.intp)),
443
+ ndim=values.ndim,
444
+ )
445
+ mgr = BlockManager(blocks=(block,), axes=[cols, Index(np.arange(3))])
446
+
447
+ tm.assert_almost_equal(mgr.iget(0).internal_values(), values[0])
448
+ tm.assert_almost_equal(mgr.iget(1).internal_values(), values[1])
449
+ tm.assert_almost_equal(mgr.iget(2).internal_values(), values[2])
450
+
451
+ def test_set(self):
452
+ mgr = create_mgr("a,b,c: int", item_shape=(3,))
453
+
454
+ mgr.insert(len(mgr.items), "d", np.array(["foo"] * 3))
455
+ mgr.iset(1, np.array(["bar"] * 3))
456
+ tm.assert_numpy_array_equal(mgr.iget(0).internal_values(), np.array([0] * 3))
457
+ tm.assert_numpy_array_equal(
458
+ mgr.iget(1).internal_values(), np.array(["bar"] * 3, dtype=np.object_)
459
+ )
460
+ tm.assert_numpy_array_equal(mgr.iget(2).internal_values(), np.array([2] * 3))
461
+ tm.assert_numpy_array_equal(
462
+ mgr.iget(3).internal_values(), np.array(["foo"] * 3, dtype=np.object_)
463
+ )
464
+
465
+ def test_set_change_dtype(self, mgr):
466
+ mgr.insert(len(mgr.items), "baz", np.zeros(N, dtype=bool))
467
+
468
+ mgr.iset(mgr.items.get_loc("baz"), np.repeat("foo", N))
469
+ idx = mgr.items.get_loc("baz")
470
+ assert mgr.iget(idx).dtype == np.object_
471
+
472
+ mgr2 = mgr.consolidate()
473
+ mgr2.iset(mgr2.items.get_loc("baz"), np.repeat("foo", N))
474
+ idx = mgr2.items.get_loc("baz")
475
+ assert mgr2.iget(idx).dtype == np.object_
476
+
477
+ mgr2.insert(
478
+ len(mgr2.items),
479
+ "quux",
480
+ np.random.default_rng(2).standard_normal(N).astype(int),
481
+ )
482
+ idx = mgr2.items.get_loc("quux")
483
+ assert mgr2.iget(idx).dtype == np.dtype(int)
484
+
485
+ mgr2.iset(
486
+ mgr2.items.get_loc("quux"), np.random.default_rng(2).standard_normal(N)
487
+ )
488
+ assert mgr2.iget(idx).dtype == np.float64
489
+
490
+ def test_copy(self, mgr):
491
+ cp = mgr.copy(deep=False)
492
+ for blk, cp_blk in zip(mgr.blocks, cp.blocks):
493
+ # view assertion
494
+ tm.assert_equal(cp_blk.values, blk.values)
495
+ if isinstance(blk.values, np.ndarray):
496
+ assert cp_blk.values.base is blk.values.base
497
+ else:
498
+ # DatetimeTZBlock has DatetimeIndex values
499
+ assert cp_blk.values._ndarray.base is blk.values._ndarray.base
500
+
501
+ # copy(deep=True) consolidates, so the block-wise assertions will
502
+ # fail is mgr is not consolidated
503
+ mgr._consolidate_inplace()
504
+ cp = mgr.copy(deep=True)
505
+ for blk, cp_blk in zip(mgr.blocks, cp.blocks):
506
+ bvals = blk.values
507
+ cpvals = cp_blk.values
508
+
509
+ tm.assert_equal(cpvals, bvals)
510
+
511
+ if isinstance(cpvals, np.ndarray):
512
+ lbase = cpvals.base
513
+ rbase = bvals.base
514
+ else:
515
+ lbase = cpvals._ndarray.base
516
+ rbase = bvals._ndarray.base
517
+
518
+ # copy assertion we either have a None for a base or in case of
519
+ # some blocks it is an array (e.g. datetimetz), but was copied
520
+ if isinstance(cpvals, DatetimeArray):
521
+ assert (lbase is None and rbase is None) or (lbase is not rbase)
522
+ elif not isinstance(cpvals, np.ndarray):
523
+ assert lbase is not rbase
524
+ else:
525
+ assert lbase is None and rbase is None
526
+
527
+ def test_sparse(self):
528
+ mgr = create_mgr("a: sparse-1; b: sparse-2")
529
+ assert mgr.as_array().dtype == np.float64
530
+
531
+ def test_sparse_mixed(self):
532
+ mgr = create_mgr("a: sparse-1; b: sparse-2; c: f8")
533
+ assert len(mgr.blocks) == 3
534
+ assert isinstance(mgr, BlockManager)
535
+
536
+ @pytest.mark.parametrize(
537
+ "mgr_string, dtype",
538
+ [("c: f4; d: f2", np.float32), ("c: f4; d: f2; e: f8", np.float64)],
539
+ )
540
+ def test_as_array_float(self, mgr_string, dtype):
541
+ mgr = create_mgr(mgr_string)
542
+ assert mgr.as_array().dtype == dtype
543
+
544
+ @pytest.mark.parametrize(
545
+ "mgr_string, dtype",
546
+ [
547
+ ("a: bool-1; b: bool-2", np.bool_),
548
+ ("a: i8-1; b: i8-2; c: i4; d: i2; e: u1", np.int64),
549
+ ("c: i4; d: i2; e: u1", np.int32),
550
+ ],
551
+ )
552
+ def test_as_array_int_bool(self, mgr_string, dtype):
553
+ mgr = create_mgr(mgr_string)
554
+ assert mgr.as_array().dtype == dtype
555
+
556
+ def test_as_array_datetime(self):
557
+ mgr = create_mgr("h: datetime-1; g: datetime-2")
558
+ assert mgr.as_array().dtype == "M8[ns]"
559
+
560
+ def test_as_array_datetime_tz(self):
561
+ mgr = create_mgr("h: M8[ns, US/Eastern]; g: M8[ns, CET]")
562
+ assert mgr.iget(0).dtype == "datetime64[ns, US/Eastern]"
563
+ assert mgr.iget(1).dtype == "datetime64[ns, CET]"
564
+ assert mgr.as_array().dtype == "object"
565
+
566
+ @pytest.mark.parametrize("t", ["float16", "float32", "float64", "int32", "int64"])
567
+ def test_astype(self, t):
568
+ # coerce all
569
+ mgr = create_mgr("c: f4; d: f2; e: f8")
570
+
571
+ t = np.dtype(t)
572
+ tmgr = mgr.astype(t)
573
+ assert tmgr.iget(0).dtype.type == t
574
+ assert tmgr.iget(1).dtype.type == t
575
+ assert tmgr.iget(2).dtype.type == t
576
+
577
+ # mixed
578
+ mgr = create_mgr("a,b: object; c: bool; d: datetime; e: f4; f: f2; g: f8")
579
+
580
+ t = np.dtype(t)
581
+ tmgr = mgr.astype(t, errors="ignore")
582
+ assert tmgr.iget(2).dtype.type == t
583
+ assert tmgr.iget(4).dtype.type == t
584
+ assert tmgr.iget(5).dtype.type == t
585
+ assert tmgr.iget(6).dtype.type == t
586
+
587
+ assert tmgr.iget(0).dtype.type == np.object_
588
+ assert tmgr.iget(1).dtype.type == np.object_
589
+ if t != np.int64:
590
+ assert tmgr.iget(3).dtype.type == np.datetime64
591
+ else:
592
+ assert tmgr.iget(3).dtype.type == t
593
+
594
+ def test_convert(self, using_infer_string):
595
+ def _compare(old_mgr, new_mgr):
596
+ """compare the blocks, numeric compare ==, object don't"""
597
+ old_blocks = set(old_mgr.blocks)
598
+ new_blocks = set(new_mgr.blocks)
599
+ assert len(old_blocks) == len(new_blocks)
600
+
601
+ # compare non-numeric
602
+ for b in old_blocks:
603
+ found = False
604
+ for nb in new_blocks:
605
+ if (b.values == nb.values).all():
606
+ found = True
607
+ break
608
+ assert found
609
+
610
+ for b in new_blocks:
611
+ found = False
612
+ for ob in old_blocks:
613
+ if (b.values == ob.values).all():
614
+ found = True
615
+ break
616
+ assert found
617
+
618
+ # noops
619
+ mgr = create_mgr("f: i8; g: f8")
620
+ new_mgr = mgr.convert(copy=True)
621
+ _compare(mgr, new_mgr)
622
+
623
+ # convert
624
+ mgr = create_mgr("a,b,foo: object; f: i8; g: f8")
625
+ mgr.iset(0, np.array(["1"] * N, dtype=np.object_))
626
+ mgr.iset(1, np.array(["2."] * N, dtype=np.object_))
627
+ mgr.iset(2, np.array(["foo."] * N, dtype=np.object_))
628
+ new_mgr = mgr.convert(copy=True)
629
+ dtype = "string[pyarrow_numpy]" if using_infer_string else np.object_
630
+ assert new_mgr.iget(0).dtype == dtype
631
+ assert new_mgr.iget(1).dtype == dtype
632
+ assert new_mgr.iget(2).dtype == dtype
633
+ assert new_mgr.iget(3).dtype == np.int64
634
+ assert new_mgr.iget(4).dtype == np.float64
635
+
636
+ mgr = create_mgr(
637
+ "a,b,foo: object; f: i4; bool: bool; dt: datetime; i: i8; g: f8; h: f2"
638
+ )
639
+ mgr.iset(0, np.array(["1"] * N, dtype=np.object_))
640
+ mgr.iset(1, np.array(["2."] * N, dtype=np.object_))
641
+ mgr.iset(2, np.array(["foo."] * N, dtype=np.object_))
642
+ new_mgr = mgr.convert(copy=True)
643
+ assert new_mgr.iget(0).dtype == dtype
644
+ assert new_mgr.iget(1).dtype == dtype
645
+ assert new_mgr.iget(2).dtype == dtype
646
+ assert new_mgr.iget(3).dtype == np.int32
647
+ assert new_mgr.iget(4).dtype == np.bool_
648
+ assert new_mgr.iget(5).dtype.type, np.datetime64
649
+ assert new_mgr.iget(6).dtype == np.int64
650
+ assert new_mgr.iget(7).dtype == np.float64
651
+ assert new_mgr.iget(8).dtype == np.float16
652
+
653
+ def test_interleave(self):
654
+ # self
655
+ for dtype in ["f8", "i8", "object", "bool", "complex", "M8[ns]", "m8[ns]"]:
656
+ mgr = create_mgr(f"a: {dtype}")
657
+ assert mgr.as_array().dtype == dtype
658
+ mgr = create_mgr(f"a: {dtype}; b: {dtype}")
659
+ assert mgr.as_array().dtype == dtype
660
+
661
+ @pytest.mark.parametrize(
662
+ "mgr_string, dtype",
663
+ [
664
+ ("a: category", "i8"),
665
+ ("a: category; b: category", "i8"),
666
+ ("a: category; b: category2", "object"),
667
+ ("a: category2", "object"),
668
+ ("a: category2; b: category2", "object"),
669
+ ("a: f8", "f8"),
670
+ ("a: f8; b: i8", "f8"),
671
+ ("a: f4; b: i8", "f8"),
672
+ ("a: f4; b: i8; d: object", "object"),
673
+ ("a: bool; b: i8", "object"),
674
+ ("a: complex", "complex"),
675
+ ("a: f8; b: category", "object"),
676
+ ("a: M8[ns]; b: category", "object"),
677
+ ("a: M8[ns]; b: bool", "object"),
678
+ ("a: M8[ns]; b: i8", "object"),
679
+ ("a: m8[ns]; b: bool", "object"),
680
+ ("a: m8[ns]; b: i8", "object"),
681
+ ("a: M8[ns]; b: m8[ns]", "object"),
682
+ ],
683
+ )
684
+ def test_interleave_dtype(self, mgr_string, dtype):
685
+ # will be converted according the actual dtype of the underlying
686
+ mgr = create_mgr("a: category")
687
+ assert mgr.as_array().dtype == "i8"
688
+ mgr = create_mgr("a: category; b: category2")
689
+ assert mgr.as_array().dtype == "object"
690
+ mgr = create_mgr("a: category2")
691
+ assert mgr.as_array().dtype == "object"
692
+
693
+ # combinations
694
+ mgr = create_mgr("a: f8")
695
+ assert mgr.as_array().dtype == "f8"
696
+ mgr = create_mgr("a: f8; b: i8")
697
+ assert mgr.as_array().dtype == "f8"
698
+ mgr = create_mgr("a: f4; b: i8")
699
+ assert mgr.as_array().dtype == "f8"
700
+ mgr = create_mgr("a: f4; b: i8; d: object")
701
+ assert mgr.as_array().dtype == "object"
702
+ mgr = create_mgr("a: bool; b: i8")
703
+ assert mgr.as_array().dtype == "object"
704
+ mgr = create_mgr("a: complex")
705
+ assert mgr.as_array().dtype == "complex"
706
+ mgr = create_mgr("a: f8; b: category")
707
+ assert mgr.as_array().dtype == "f8"
708
+ mgr = create_mgr("a: M8[ns]; b: category")
709
+ assert mgr.as_array().dtype == "object"
710
+ mgr = create_mgr("a: M8[ns]; b: bool")
711
+ assert mgr.as_array().dtype == "object"
712
+ mgr = create_mgr("a: M8[ns]; b: i8")
713
+ assert mgr.as_array().dtype == "object"
714
+ mgr = create_mgr("a: m8[ns]; b: bool")
715
+ assert mgr.as_array().dtype == "object"
716
+ mgr = create_mgr("a: m8[ns]; b: i8")
717
+ assert mgr.as_array().dtype == "object"
718
+ mgr = create_mgr("a: M8[ns]; b: m8[ns]")
719
+ assert mgr.as_array().dtype == "object"
720
+
721
+ def test_consolidate_ordering_issues(self, mgr):
722
+ mgr.iset(mgr.items.get_loc("f"), np.random.default_rng(2).standard_normal(N))
723
+ mgr.iset(mgr.items.get_loc("d"), np.random.default_rng(2).standard_normal(N))
724
+ mgr.iset(mgr.items.get_loc("b"), np.random.default_rng(2).standard_normal(N))
725
+ mgr.iset(mgr.items.get_loc("g"), np.random.default_rng(2).standard_normal(N))
726
+ mgr.iset(mgr.items.get_loc("h"), np.random.default_rng(2).standard_normal(N))
727
+
728
+ # we have datetime/tz blocks in mgr
729
+ cons = mgr.consolidate()
730
+ assert cons.nblocks == 4
731
+ cons = mgr.consolidate().get_numeric_data()
732
+ assert cons.nblocks == 1
733
+ assert isinstance(cons.blocks[0].mgr_locs, BlockPlacement)
734
+ tm.assert_numpy_array_equal(
735
+ cons.blocks[0].mgr_locs.as_array, np.arange(len(cons.items), dtype=np.intp)
736
+ )
737
+
738
+ def test_reindex_items(self):
739
+ # mgr is not consolidated, f8 & f8-2 blocks
740
+ mgr = create_mgr("a: f8; b: i8; c: f8; d: i8; e: f8; f: bool; g: f8-2")
741
+
742
+ reindexed = mgr.reindex_axis(["g", "c", "a", "d"], axis=0)
743
+ # reindex_axis does not consolidate_inplace, as that risks failing to
744
+ # invalidate _item_cache
745
+ assert not reindexed.is_consolidated()
746
+
747
+ tm.assert_index_equal(reindexed.items, Index(["g", "c", "a", "d"]))
748
+ tm.assert_almost_equal(
749
+ mgr.iget(6).internal_values(), reindexed.iget(0).internal_values()
750
+ )
751
+ tm.assert_almost_equal(
752
+ mgr.iget(2).internal_values(), reindexed.iget(1).internal_values()
753
+ )
754
+ tm.assert_almost_equal(
755
+ mgr.iget(0).internal_values(), reindexed.iget(2).internal_values()
756
+ )
757
+ tm.assert_almost_equal(
758
+ mgr.iget(3).internal_values(), reindexed.iget(3).internal_values()
759
+ )
760
+
761
+ def test_get_numeric_data(self, using_copy_on_write):
762
+ mgr = create_mgr(
763
+ "int: int; float: float; complex: complex;"
764
+ "str: object; bool: bool; obj: object; dt: datetime",
765
+ item_shape=(3,),
766
+ )
767
+ mgr.iset(5, np.array([1, 2, 3], dtype=np.object_))
768
+
769
+ numeric = mgr.get_numeric_data()
770
+ tm.assert_index_equal(numeric.items, Index(["int", "float", "complex", "bool"]))
771
+ tm.assert_almost_equal(
772
+ mgr.iget(mgr.items.get_loc("float")).internal_values(),
773
+ numeric.iget(numeric.items.get_loc("float")).internal_values(),
774
+ )
775
+
776
+ # Check sharing
777
+ numeric.iset(
778
+ numeric.items.get_loc("float"),
779
+ np.array([100.0, 200.0, 300.0]),
780
+ inplace=True,
781
+ )
782
+ if using_copy_on_write:
783
+ tm.assert_almost_equal(
784
+ mgr.iget(mgr.items.get_loc("float")).internal_values(),
785
+ np.array([1.0, 1.0, 1.0]),
786
+ )
787
+ else:
788
+ tm.assert_almost_equal(
789
+ mgr.iget(mgr.items.get_loc("float")).internal_values(),
790
+ np.array([100.0, 200.0, 300.0]),
791
+ )
792
+
793
+ def test_get_bool_data(self, using_copy_on_write):
794
+ mgr = create_mgr(
795
+ "int: int; float: float; complex: complex;"
796
+ "str: object; bool: bool; obj: object; dt: datetime",
797
+ item_shape=(3,),
798
+ )
799
+ mgr.iset(6, np.array([True, False, True], dtype=np.object_))
800
+
801
+ bools = mgr.get_bool_data()
802
+ tm.assert_index_equal(bools.items, Index(["bool"]))
803
+ tm.assert_almost_equal(
804
+ mgr.iget(mgr.items.get_loc("bool")).internal_values(),
805
+ bools.iget(bools.items.get_loc("bool")).internal_values(),
806
+ )
807
+
808
+ bools.iset(0, np.array([True, False, True]), inplace=True)
809
+ if using_copy_on_write:
810
+ tm.assert_numpy_array_equal(
811
+ mgr.iget(mgr.items.get_loc("bool")).internal_values(),
812
+ np.array([True, True, True]),
813
+ )
814
+ else:
815
+ tm.assert_numpy_array_equal(
816
+ mgr.iget(mgr.items.get_loc("bool")).internal_values(),
817
+ np.array([True, False, True]),
818
+ )
819
+
820
+ def test_unicode_repr_doesnt_raise(self):
821
+ repr(create_mgr("b,\u05d0: object"))
822
+
823
+ @pytest.mark.parametrize(
824
+ "mgr_string", ["a,b,c: i8-1; d,e,f: i8-2", "a,a,a: i8-1; b,b,b: i8-2"]
825
+ )
826
+ def test_equals(self, mgr_string):
827
+ # unique items
828
+ bm1 = create_mgr(mgr_string)
829
+ bm2 = BlockManager(bm1.blocks[::-1], bm1.axes)
830
+ assert bm1.equals(bm2)
831
+
832
+ @pytest.mark.parametrize(
833
+ "mgr_string",
834
+ [
835
+ "a:i8;b:f8", # basic case
836
+ "a:i8;b:f8;c:c8;d:b", # many types
837
+ "a:i8;e:dt;f:td;g:string", # more types
838
+ "a:i8;b:category;c:category2", # categories
839
+ "c:sparse;d:sparse_na;b:f8", # sparse
840
+ ],
841
+ )
842
+ def test_equals_block_order_different_dtypes(self, mgr_string):
843
+ # GH 9330
844
+ bm = create_mgr(mgr_string)
845
+ block_perms = itertools.permutations(bm.blocks)
846
+ for bm_perm in block_perms:
847
+ bm_this = BlockManager(tuple(bm_perm), bm.axes)
848
+ assert bm.equals(bm_this)
849
+ assert bm_this.equals(bm)
850
+
851
+ def test_single_mgr_ctor(self):
852
+ mgr = create_single_mgr("f8", num_rows=5)
853
+ assert mgr.external_values().tolist() == [0.0, 1.0, 2.0, 3.0, 4.0]
854
+
855
+ @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
856
+ def test_validate_bool_args(self, value):
857
+ bm1 = create_mgr("a,b,c: i8-1; d,e,f: i8-2")
858
+
859
+ msg = (
860
+ 'For argument "inplace" expected type bool, '
861
+ f"received type {type(value).__name__}."
862
+ )
863
+ with pytest.raises(ValueError, match=msg):
864
+ bm1.replace_list([1], [2], inplace=value)
865
+
866
+ def test_iset_split_block(self):
867
+ bm = create_mgr("a,b,c: i8; d: f8")
868
+ bm._iset_split_block(0, np.array([0]))
869
+ tm.assert_numpy_array_equal(
870
+ bm.blklocs, np.array([0, 0, 1, 0], dtype="int64" if IS64 else "int32")
871
+ )
872
+ # First indexer currently does not have a block associated with it in case
873
+ tm.assert_numpy_array_equal(
874
+ bm.blknos, np.array([0, 0, 0, 1], dtype="int64" if IS64 else "int32")
875
+ )
876
+ assert len(bm.blocks) == 2
877
+
878
+ def test_iset_split_block_values(self):
879
+ bm = create_mgr("a,b,c: i8; d: f8")
880
+ bm._iset_split_block(0, np.array([0]), np.array([list(range(10))]))
881
+ tm.assert_numpy_array_equal(
882
+ bm.blklocs, np.array([0, 0, 1, 0], dtype="int64" if IS64 else "int32")
883
+ )
884
+ # First indexer currently does not have a block associated with it in case
885
+ tm.assert_numpy_array_equal(
886
+ bm.blknos, np.array([0, 2, 2, 1], dtype="int64" if IS64 else "int32")
887
+ )
888
+ assert len(bm.blocks) == 3
889
+
890
+
891
+ def _as_array(mgr):
892
+ if mgr.ndim == 1:
893
+ return mgr.external_values()
894
+ return mgr.as_array().T
895
+
896
+
897
+ class TestIndexing:
898
+ # Nosetests-style data-driven tests.
899
+ #
900
+ # This test applies different indexing routines to block managers and
901
+ # compares the outcome to the result of same operations on np.ndarray.
902
+ #
903
+ # NOTE: sparse (SparseBlock with fill_value != np.nan) fail a lot of tests
904
+ # and are disabled.
905
+
906
+ MANAGERS = [
907
+ create_single_mgr("f8", N),
908
+ create_single_mgr("i8", N),
909
+ # 2-dim
910
+ create_mgr("a,b,c,d,e,f: f8", item_shape=(N,)),
911
+ create_mgr("a,b,c,d,e,f: i8", item_shape=(N,)),
912
+ create_mgr("a,b: f8; c,d: i8; e,f: string", item_shape=(N,)),
913
+ create_mgr("a,b: f8; c,d: i8; e,f: f8", item_shape=(N,)),
914
+ ]
915
+
916
+ @pytest.mark.parametrize("mgr", MANAGERS)
917
+ def test_get_slice(self, mgr):
918
+ def assert_slice_ok(mgr, axis, slobj):
919
+ mat = _as_array(mgr)
920
+
921
+ # we maybe using an ndarray to test slicing and
922
+ # might not be the full length of the axis
923
+ if isinstance(slobj, np.ndarray):
924
+ ax = mgr.axes[axis]
925
+ if len(ax) and len(slobj) and len(slobj) != len(ax):
926
+ slobj = np.concatenate(
927
+ [slobj, np.zeros(len(ax) - len(slobj), dtype=bool)]
928
+ )
929
+
930
+ if isinstance(slobj, slice):
931
+ sliced = mgr.get_slice(slobj, axis=axis)
932
+ elif (
933
+ mgr.ndim == 1
934
+ and axis == 0
935
+ and isinstance(slobj, np.ndarray)
936
+ and slobj.dtype == bool
937
+ ):
938
+ sliced = mgr.get_rows_with_mask(slobj)
939
+ else:
940
+ # BlockManager doesn't support non-slice, SingleBlockManager
941
+ # doesn't support axis > 0
942
+ raise TypeError(slobj)
943
+
944
+ mat_slobj = (slice(None),) * axis + (slobj,)
945
+ tm.assert_numpy_array_equal(
946
+ mat[mat_slobj], _as_array(sliced), check_dtype=False
947
+ )
948
+ tm.assert_index_equal(mgr.axes[axis][slobj], sliced.axes[axis])
949
+
950
+ assert mgr.ndim <= 2, mgr.ndim
951
+ for ax in range(mgr.ndim):
952
+ # slice
953
+ assert_slice_ok(mgr, ax, slice(None))
954
+ assert_slice_ok(mgr, ax, slice(3))
955
+ assert_slice_ok(mgr, ax, slice(100))
956
+ assert_slice_ok(mgr, ax, slice(1, 4))
957
+ assert_slice_ok(mgr, ax, slice(3, 0, -2))
958
+
959
+ if mgr.ndim < 2:
960
+ # 2D only support slice objects
961
+
962
+ # boolean mask
963
+ assert_slice_ok(mgr, ax, np.ones(mgr.shape[ax], dtype=np.bool_))
964
+ assert_slice_ok(mgr, ax, np.zeros(mgr.shape[ax], dtype=np.bool_))
965
+
966
+ if mgr.shape[ax] >= 3:
967
+ assert_slice_ok(mgr, ax, np.arange(mgr.shape[ax]) % 3 == 0)
968
+ assert_slice_ok(
969
+ mgr, ax, np.array([True, True, False], dtype=np.bool_)
970
+ )
971
+
972
+ @pytest.mark.parametrize("mgr", MANAGERS)
973
+ def test_take(self, mgr):
974
+ def assert_take_ok(mgr, axis, indexer):
975
+ mat = _as_array(mgr)
976
+ taken = mgr.take(indexer, axis)
977
+ tm.assert_numpy_array_equal(
978
+ np.take(mat, indexer, axis), _as_array(taken), check_dtype=False
979
+ )
980
+ tm.assert_index_equal(mgr.axes[axis].take(indexer), taken.axes[axis])
981
+
982
+ for ax in range(mgr.ndim):
983
+ # take/fancy indexer
984
+ assert_take_ok(mgr, ax, indexer=np.array([], dtype=np.intp))
985
+ assert_take_ok(mgr, ax, indexer=np.array([0, 0, 0], dtype=np.intp))
986
+ assert_take_ok(
987
+ mgr, ax, indexer=np.array(list(range(mgr.shape[ax])), dtype=np.intp)
988
+ )
989
+
990
+ if mgr.shape[ax] >= 3:
991
+ assert_take_ok(mgr, ax, indexer=np.array([0, 1, 2], dtype=np.intp))
992
+ assert_take_ok(mgr, ax, indexer=np.array([-1, -2, -3], dtype=np.intp))
993
+
994
+ @pytest.mark.parametrize("mgr", MANAGERS)
995
+ @pytest.mark.parametrize("fill_value", [None, np.nan, 100.0])
996
+ def test_reindex_axis(self, fill_value, mgr):
997
+ def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value):
998
+ mat = _as_array(mgr)
999
+ indexer = mgr.axes[axis].get_indexer_for(new_labels)
1000
+
1001
+ reindexed = mgr.reindex_axis(new_labels, axis, fill_value=fill_value)
1002
+ tm.assert_numpy_array_equal(
1003
+ algos.take_nd(mat, indexer, axis, fill_value=fill_value),
1004
+ _as_array(reindexed),
1005
+ check_dtype=False,
1006
+ )
1007
+ tm.assert_index_equal(reindexed.axes[axis], new_labels)
1008
+
1009
+ for ax in range(mgr.ndim):
1010
+ assert_reindex_axis_is_ok(mgr, ax, Index([]), fill_value)
1011
+ assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax], fill_value)
1012
+ assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][[0, 0, 0]], fill_value)
1013
+ assert_reindex_axis_is_ok(mgr, ax, Index(["foo", "bar", "baz"]), fill_value)
1014
+ assert_reindex_axis_is_ok(
1015
+ mgr, ax, Index(["foo", mgr.axes[ax][0], "baz"]), fill_value
1016
+ )
1017
+
1018
+ if mgr.shape[ax] >= 3:
1019
+ assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][:-3], fill_value)
1020
+ assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][-3::-1], fill_value)
1021
+ assert_reindex_axis_is_ok(
1022
+ mgr, ax, mgr.axes[ax][[0, 1, 2, 0, 1, 2]], fill_value
1023
+ )
1024
+
1025
+ @pytest.mark.parametrize("mgr", MANAGERS)
1026
+ @pytest.mark.parametrize("fill_value", [None, np.nan, 100.0])
1027
+ def test_reindex_indexer(self, fill_value, mgr):
1028
+ def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value):
1029
+ mat = _as_array(mgr)
1030
+ reindexed_mat = algos.take_nd(mat, indexer, axis, fill_value=fill_value)
1031
+ reindexed = mgr.reindex_indexer(
1032
+ new_labels, indexer, axis, fill_value=fill_value
1033
+ )
1034
+ tm.assert_numpy_array_equal(
1035
+ reindexed_mat, _as_array(reindexed), check_dtype=False
1036
+ )
1037
+ tm.assert_index_equal(reindexed.axes[axis], new_labels)
1038
+
1039
+ for ax in range(mgr.ndim):
1040
+ assert_reindex_indexer_is_ok(
1041
+ mgr, ax, Index([]), np.array([], dtype=np.intp), fill_value
1042
+ )
1043
+ assert_reindex_indexer_is_ok(
1044
+ mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax]), fill_value
1045
+ )
1046
+ assert_reindex_indexer_is_ok(
1047
+ mgr,
1048
+ ax,
1049
+ Index(["foo"] * mgr.shape[ax]),
1050
+ np.arange(mgr.shape[ax]),
1051
+ fill_value,
1052
+ )
1053
+ assert_reindex_indexer_is_ok(
1054
+ mgr, ax, mgr.axes[ax][::-1], np.arange(mgr.shape[ax]), fill_value
1055
+ )
1056
+ assert_reindex_indexer_is_ok(
1057
+ mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax])[::-1], fill_value
1058
+ )
1059
+ assert_reindex_indexer_is_ok(
1060
+ mgr, ax, Index(["foo", "bar", "baz"]), np.array([0, 0, 0]), fill_value
1061
+ )
1062
+ assert_reindex_indexer_is_ok(
1063
+ mgr, ax, Index(["foo", "bar", "baz"]), np.array([-1, 0, -1]), fill_value
1064
+ )
1065
+ assert_reindex_indexer_is_ok(
1066
+ mgr,
1067
+ ax,
1068
+ Index(["foo", mgr.axes[ax][0], "baz"]),
1069
+ np.array([-1, -1, -1]),
1070
+ fill_value,
1071
+ )
1072
+
1073
+ if mgr.shape[ax] >= 3:
1074
+ assert_reindex_indexer_is_ok(
1075
+ mgr,
1076
+ ax,
1077
+ Index(["foo", "bar", "baz"]),
1078
+ np.array([0, 1, 2]),
1079
+ fill_value,
1080
+ )
1081
+
1082
+
1083
+ class TestBlockPlacement:
1084
+ @pytest.mark.parametrize(
1085
+ "slc, expected",
1086
+ [
1087
+ (slice(0, 4), 4),
1088
+ (slice(0, 4, 2), 2),
1089
+ (slice(0, 3, 2), 2),
1090
+ (slice(0, 1, 2), 1),
1091
+ (slice(1, 0, -1), 1),
1092
+ ],
1093
+ )
1094
+ def test_slice_len(self, slc, expected):
1095
+ assert len(BlockPlacement(slc)) == expected
1096
+
1097
+ @pytest.mark.parametrize("slc", [slice(1, 1, 0), slice(1, 2, 0)])
1098
+ def test_zero_step_raises(self, slc):
1099
+ msg = "slice step cannot be zero"
1100
+ with pytest.raises(ValueError, match=msg):
1101
+ BlockPlacement(slc)
1102
+
1103
+ def test_slice_canonize_negative_stop(self):
1104
+ # GH#37524 negative stop is OK with negative step and positive start
1105
+ slc = slice(3, -1, -2)
1106
+
1107
+ bp = BlockPlacement(slc)
1108
+ assert bp.indexer == slice(3, None, -2)
1109
+
1110
+ @pytest.mark.parametrize(
1111
+ "slc",
1112
+ [
1113
+ slice(None, None),
1114
+ slice(10, None),
1115
+ slice(None, None, -1),
1116
+ slice(None, 10, -1),
1117
+ # These are "unbounded" because negative index will
1118
+ # change depending on container shape.
1119
+ slice(-1, None),
1120
+ slice(None, -1),
1121
+ slice(-1, -1),
1122
+ slice(-1, None, -1),
1123
+ slice(None, -1, -1),
1124
+ slice(-1, -1, -1),
1125
+ ],
1126
+ )
1127
+ def test_unbounded_slice_raises(self, slc):
1128
+ msg = "unbounded slice"
1129
+ with pytest.raises(ValueError, match=msg):
1130
+ BlockPlacement(slc)
1131
+
1132
+ @pytest.mark.parametrize(
1133
+ "slc",
1134
+ [
1135
+ slice(0, 0),
1136
+ slice(100, 0),
1137
+ slice(100, 100),
1138
+ slice(100, 100, -1),
1139
+ slice(0, 100, -1),
1140
+ ],
1141
+ )
1142
+ def test_not_slice_like_slices(self, slc):
1143
+ assert not BlockPlacement(slc).is_slice_like
1144
+
1145
+ @pytest.mark.parametrize(
1146
+ "arr, slc",
1147
+ [
1148
+ ([0], slice(0, 1, 1)),
1149
+ ([100], slice(100, 101, 1)),
1150
+ ([0, 1, 2], slice(0, 3, 1)),
1151
+ ([0, 5, 10], slice(0, 15, 5)),
1152
+ ([0, 100], slice(0, 200, 100)),
1153
+ ([2, 1], slice(2, 0, -1)),
1154
+ ],
1155
+ )
1156
+ def test_array_to_slice_conversion(self, arr, slc):
1157
+ assert BlockPlacement(arr).as_slice == slc
1158
+
1159
+ @pytest.mark.parametrize(
1160
+ "arr",
1161
+ [
1162
+ [],
1163
+ [-1],
1164
+ [-1, -2, -3],
1165
+ [-10],
1166
+ [-1],
1167
+ [-1, 0, 1, 2],
1168
+ [-2, 0, 2, 4],
1169
+ [1, 0, -1],
1170
+ [1, 1, 1],
1171
+ ],
1172
+ )
1173
+ def test_not_slice_like_arrays(self, arr):
1174
+ assert not BlockPlacement(arr).is_slice_like
1175
+
1176
+ @pytest.mark.parametrize(
1177
+ "slc, expected",
1178
+ [(slice(0, 3), [0, 1, 2]), (slice(0, 0), []), (slice(3, 0), [])],
1179
+ )
1180
+ def test_slice_iter(self, slc, expected):
1181
+ assert list(BlockPlacement(slc)) == expected
1182
+
1183
+ @pytest.mark.parametrize(
1184
+ "slc, arr",
1185
+ [
1186
+ (slice(0, 3), [0, 1, 2]),
1187
+ (slice(0, 0), []),
1188
+ (slice(3, 0), []),
1189
+ (slice(3, 0, -1), [3, 2, 1]),
1190
+ ],
1191
+ )
1192
+ def test_slice_to_array_conversion(self, slc, arr):
1193
+ tm.assert_numpy_array_equal(
1194
+ BlockPlacement(slc).as_array, np.asarray(arr, dtype=np.intp)
1195
+ )
1196
+
1197
+ def test_blockplacement_add(self):
1198
+ bpl = BlockPlacement(slice(0, 5))
1199
+ assert bpl.add(1).as_slice == slice(1, 6, 1)
1200
+ assert bpl.add(np.arange(5)).as_slice == slice(0, 10, 2)
1201
+ assert list(bpl.add(np.arange(5, 0, -1))) == [5, 5, 5, 5, 5]
1202
+
1203
+ @pytest.mark.parametrize(
1204
+ "val, inc, expected",
1205
+ [
1206
+ (slice(0, 0), 0, []),
1207
+ (slice(1, 4), 0, [1, 2, 3]),
1208
+ (slice(3, 0, -1), 0, [3, 2, 1]),
1209
+ ([1, 2, 4], 0, [1, 2, 4]),
1210
+ (slice(0, 0), 10, []),
1211
+ (slice(1, 4), 10, [11, 12, 13]),
1212
+ (slice(3, 0, -1), 10, [13, 12, 11]),
1213
+ ([1, 2, 4], 10, [11, 12, 14]),
1214
+ (slice(0, 0), -1, []),
1215
+ (slice(1, 4), -1, [0, 1, 2]),
1216
+ ([1, 2, 4], -1, [0, 1, 3]),
1217
+ ],
1218
+ )
1219
+ def test_blockplacement_add_int(self, val, inc, expected):
1220
+ assert list(BlockPlacement(val).add(inc)) == expected
1221
+
1222
+ @pytest.mark.parametrize("val", [slice(1, 4), [1, 2, 4]])
1223
+ def test_blockplacement_add_int_raises(self, val):
1224
+ msg = "iadd causes length change"
1225
+ with pytest.raises(ValueError, match=msg):
1226
+ BlockPlacement(val).add(-10)
1227
+
1228
+
1229
+ class TestCanHoldElement:
1230
+ @pytest.fixture(
1231
+ params=[
1232
+ lambda x: x,
1233
+ lambda x: x.to_series(),
1234
+ lambda x: x._data,
1235
+ lambda x: list(x),
1236
+ lambda x: x.astype(object),
1237
+ lambda x: np.asarray(x),
1238
+ lambda x: x[0],
1239
+ lambda x: x[:0],
1240
+ ]
1241
+ )
1242
+ def element(self, request):
1243
+ """
1244
+ Functions that take an Index and return an element that should have
1245
+ blk._can_hold_element(element) for a Block with this index's dtype.
1246
+ """
1247
+ return request.param
1248
+
1249
+ def test_datetime_block_can_hold_element(self):
1250
+ block = create_block("datetime", [0])
1251
+
1252
+ assert block._can_hold_element([])
1253
+
1254
+ # We will check that block._can_hold_element iff arr.__setitem__ works
1255
+ arr = pd.array(block.values.ravel())
1256
+
1257
+ # coerce None
1258
+ assert block._can_hold_element(None)
1259
+ arr[0] = None
1260
+ assert arr[0] is pd.NaT
1261
+
1262
+ # coerce different types of datetime objects
1263
+ vals = [np.datetime64("2010-10-10"), datetime(2010, 10, 10)]
1264
+ for val in vals:
1265
+ assert block._can_hold_element(val)
1266
+ arr[0] = val
1267
+
1268
+ val = date(2010, 10, 10)
1269
+ assert not block._can_hold_element(val)
1270
+
1271
+ msg = (
1272
+ "value should be a 'Timestamp', 'NaT', "
1273
+ "or array of those. Got 'date' instead."
1274
+ )
1275
+ with pytest.raises(TypeError, match=msg):
1276
+ arr[0] = val
1277
+
1278
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
1279
+ def test_interval_can_hold_element_emptylist(self, dtype, element):
1280
+ arr = np.array([1, 3, 4], dtype=dtype)
1281
+ ii = IntervalIndex.from_breaks(arr)
1282
+ blk = new_block(ii._data, BlockPlacement([1]), ndim=2)
1283
+
1284
+ assert blk._can_hold_element([])
1285
+ # TODO: check this holds for all blocks
1286
+
1287
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
1288
+ def test_interval_can_hold_element(self, dtype, element):
1289
+ arr = np.array([1, 3, 4, 9], dtype=dtype)
1290
+ ii = IntervalIndex.from_breaks(arr)
1291
+ blk = new_block(ii._data, BlockPlacement([1]), ndim=2)
1292
+
1293
+ elem = element(ii)
1294
+ self.check_series_setitem(elem, ii, True)
1295
+ assert blk._can_hold_element(elem)
1296
+
1297
+ # Careful: to get the expected Series-inplace behavior we need
1298
+ # `elem` to not have the same length as `arr`
1299
+ ii2 = IntervalIndex.from_breaks(arr[:-1], closed="neither")
1300
+ elem = element(ii2)
1301
+ with tm.assert_produces_warning(FutureWarning):
1302
+ self.check_series_setitem(elem, ii, False)
1303
+ assert not blk._can_hold_element(elem)
1304
+
1305
+ ii3 = IntervalIndex.from_breaks([Timestamp(1), Timestamp(3), Timestamp(4)])
1306
+ elem = element(ii3)
1307
+ with tm.assert_produces_warning(FutureWarning):
1308
+ self.check_series_setitem(elem, ii, False)
1309
+ assert not blk._can_hold_element(elem)
1310
+
1311
+ ii4 = IntervalIndex.from_breaks([Timedelta(1), Timedelta(3), Timedelta(4)])
1312
+ elem = element(ii4)
1313
+ with tm.assert_produces_warning(FutureWarning):
1314
+ self.check_series_setitem(elem, ii, False)
1315
+ assert not blk._can_hold_element(elem)
1316
+
1317
+ def test_period_can_hold_element_emptylist(self):
1318
+ pi = period_range("2016", periods=3, freq="Y")
1319
+ blk = new_block(pi._data.reshape(1, 3), BlockPlacement([1]), ndim=2)
1320
+
1321
+ assert blk._can_hold_element([])
1322
+
1323
+ def test_period_can_hold_element(self, element):
1324
+ pi = period_range("2016", periods=3, freq="Y")
1325
+
1326
+ elem = element(pi)
1327
+ self.check_series_setitem(elem, pi, True)
1328
+
1329
+ # Careful: to get the expected Series-inplace behavior we need
1330
+ # `elem` to not have the same length as `arr`
1331
+ pi2 = pi.asfreq("D")[:-1]
1332
+ elem = element(pi2)
1333
+ with tm.assert_produces_warning(FutureWarning):
1334
+ self.check_series_setitem(elem, pi, False)
1335
+
1336
+ dti = pi.to_timestamp("s")[:-1]
1337
+ elem = element(dti)
1338
+ with tm.assert_produces_warning(FutureWarning):
1339
+ self.check_series_setitem(elem, pi, False)
1340
+
1341
+ def check_can_hold_element(self, obj, elem, inplace: bool):
1342
+ blk = obj._mgr.blocks[0]
1343
+ if inplace:
1344
+ assert blk._can_hold_element(elem)
1345
+ else:
1346
+ assert not blk._can_hold_element(elem)
1347
+
1348
+ def check_series_setitem(self, elem, index: Index, inplace: bool):
1349
+ arr = index._data.copy()
1350
+ ser = Series(arr, copy=False)
1351
+
1352
+ self.check_can_hold_element(ser, elem, inplace)
1353
+
1354
+ if is_scalar(elem):
1355
+ ser[0] = elem
1356
+ else:
1357
+ ser[: len(elem)] = elem
1358
+
1359
+ if inplace:
1360
+ assert ser.array is arr # i.e. setting was done inplace
1361
+ else:
1362
+ assert ser.dtype == object
1363
+
1364
+
1365
+ class TestShouldStore:
1366
+ def test_should_store_categorical(self):
1367
+ cat = Categorical(["A", "B", "C"])
1368
+ df = DataFrame(cat)
1369
+ blk = df._mgr.blocks[0]
1370
+
1371
+ # matching dtype
1372
+ assert blk.should_store(cat)
1373
+ assert blk.should_store(cat[:-1])
1374
+
1375
+ # different dtype
1376
+ assert not blk.should_store(cat.as_ordered())
1377
+
1378
+ # ndarray instead of Categorical
1379
+ assert not blk.should_store(np.asarray(cat))
1380
+
1381
+
1382
+ def test_validate_ndim():
1383
+ values = np.array([1.0, 2.0])
1384
+ placement = BlockPlacement(slice(2))
1385
+ msg = r"Wrong number of dimensions. values.ndim != ndim \[1 != 2\]"
1386
+
1387
+ with pytest.raises(ValueError, match=msg):
1388
+ make_block(values, placement, ndim=2)
1389
+
1390
+
1391
+ def test_block_shape():
1392
+ idx = Index([0, 1, 2, 3, 4])
1393
+ a = Series([1, 2, 3]).reindex(idx)
1394
+ b = Series(Categorical([1, 2, 3])).reindex(idx)
1395
+
1396
+ assert a._mgr.blocks[0].mgr_locs.indexer == b._mgr.blocks[0].mgr_locs.indexer
1397
+
1398
+
1399
+ def test_make_block_no_pandas_array(block_maker):
1400
+ # https://github.com/pandas-dev/pandas/pull/24866
1401
+ arr = pd.arrays.NumpyExtensionArray(np.array([1, 2]))
1402
+
1403
+ # NumpyExtensionArray, no dtype
1404
+ result = block_maker(arr, BlockPlacement(slice(len(arr))), ndim=arr.ndim)
1405
+ assert result.dtype.kind in ["i", "u"]
1406
+
1407
+ if block_maker is make_block:
1408
+ # new_block requires caller to unwrap NumpyExtensionArray
1409
+ assert result.is_extension is False
1410
+
1411
+ # NumpyExtensionArray, NumpyEADtype
1412
+ result = block_maker(arr, slice(len(arr)), dtype=arr.dtype, ndim=arr.ndim)
1413
+ assert result.dtype.kind in ["i", "u"]
1414
+ assert result.is_extension is False
1415
+
1416
+ # new_block no longer taked dtype keyword
1417
+ # ndarray, NumpyEADtype
1418
+ result = block_maker(
1419
+ arr.to_numpy(), slice(len(arr)), dtype=arr.dtype, ndim=arr.ndim
1420
+ )
1421
+ assert result.dtype.kind in ["i", "u"]
1422
+ assert result.is_extension is False
venv/lib/python3.10/site-packages/pandas/tests/internals/test_managers.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Testing interaction between the different managers (BlockManager, ArrayManager)
3
+ """
4
+ import os
5
+ import subprocess
6
+ import sys
7
+
8
+ import pytest
9
+
10
+ from pandas.core.dtypes.missing import array_equivalent
11
+
12
+ import pandas as pd
13
+ import pandas._testing as tm
14
+ from pandas.core.internals import (
15
+ ArrayManager,
16
+ BlockManager,
17
+ SingleArrayManager,
18
+ SingleBlockManager,
19
+ )
20
+
21
+
22
+ def test_dataframe_creation():
23
+ msg = "data_manager option is deprecated"
24
+ with tm.assert_produces_warning(FutureWarning, match=msg):
25
+ with pd.option_context("mode.data_manager", "block"):
26
+ df_block = pd.DataFrame(
27
+ {"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]}
28
+ )
29
+ assert isinstance(df_block._mgr, BlockManager)
30
+
31
+ with tm.assert_produces_warning(FutureWarning, match=msg):
32
+ with pd.option_context("mode.data_manager", "array"):
33
+ df_array = pd.DataFrame(
34
+ {"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]}
35
+ )
36
+ assert isinstance(df_array._mgr, ArrayManager)
37
+
38
+ # also ensure both are seen as equal
39
+ tm.assert_frame_equal(df_block, df_array)
40
+
41
+ # conversion from one manager to the other
42
+ result = df_block._as_manager("block")
43
+ assert isinstance(result._mgr, BlockManager)
44
+ result = df_block._as_manager("array")
45
+ assert isinstance(result._mgr, ArrayManager)
46
+ tm.assert_frame_equal(result, df_block)
47
+ assert all(
48
+ array_equivalent(left, right)
49
+ for left, right in zip(result._mgr.arrays, df_array._mgr.arrays)
50
+ )
51
+
52
+ result = df_array._as_manager("array")
53
+ assert isinstance(result._mgr, ArrayManager)
54
+ result = df_array._as_manager("block")
55
+ assert isinstance(result._mgr, BlockManager)
56
+ tm.assert_frame_equal(result, df_array)
57
+ assert len(result._mgr.blocks) == 2
58
+
59
+
60
+ def test_series_creation():
61
+ msg = "data_manager option is deprecated"
62
+ with tm.assert_produces_warning(FutureWarning, match=msg):
63
+ with pd.option_context("mode.data_manager", "block"):
64
+ s_block = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"])
65
+ assert isinstance(s_block._mgr, SingleBlockManager)
66
+
67
+ with tm.assert_produces_warning(FutureWarning, match=msg):
68
+ with pd.option_context("mode.data_manager", "array"):
69
+ s_array = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"])
70
+ assert isinstance(s_array._mgr, SingleArrayManager)
71
+
72
+ # also ensure both are seen as equal
73
+ tm.assert_series_equal(s_block, s_array)
74
+
75
+ # conversion from one manager to the other
76
+ result = s_block._as_manager("block")
77
+ assert isinstance(result._mgr, SingleBlockManager)
78
+ result = s_block._as_manager("array")
79
+ assert isinstance(result._mgr, SingleArrayManager)
80
+ tm.assert_series_equal(result, s_block)
81
+
82
+ result = s_array._as_manager("array")
83
+ assert isinstance(result._mgr, SingleArrayManager)
84
+ result = s_array._as_manager("block")
85
+ assert isinstance(result._mgr, SingleBlockManager)
86
+ tm.assert_series_equal(result, s_array)
87
+
88
+
89
+ @pytest.mark.single_cpu
90
+ @pytest.mark.parametrize("manager", ["block", "array"])
91
+ def test_array_manager_depr_env_var(manager):
92
+ # GH#55043
93
+ test_env = os.environ.copy()
94
+ test_env["PANDAS_DATA_MANAGER"] = manager
95
+ response = subprocess.run(
96
+ [sys.executable, "-c", "import pandas"],
97
+ capture_output=True,
98
+ env=test_env,
99
+ check=True,
100
+ )
101
+ msg = "FutureWarning: The env variable PANDAS_DATA_MANAGER is set"
102
+ stderr_msg = response.stderr.decode("utf-8")
103
+ assert msg in stderr_msg, stderr_msg
venv/lib/python3.10/site-packages/pandas/tests/series/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_api.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_arithmetic.cpython-310.pyc ADDED
Binary file (30.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (78.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_cumulative.cpython-310.pyc ADDED
Binary file (4.45 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_formats.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_iteration.cpython-310.pyc ADDED
Binary file (1.64 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_logical_ops.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_missing.cpython-310.pyc ADDED
Binary file (3.71 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_npfuncs.cpython-310.pyc ADDED
Binary file (1.75 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_reductions.cpython-310.pyc ADDED
Binary file (6.81 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_subclass.cpython-310.pyc ADDED
Binary file (3.57 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_ufunc.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_unary.cpython-310.pyc ADDED
Binary file (1.95 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/__pycache__/test_validate.cpython-310.pyc ADDED
Binary file (860 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (197 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__pycache__/test_cat_accessor.cpython-310.pyc ADDED
Binary file (8.63 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__pycache__/test_list_accessor.cpython-310.pyc ADDED
Binary file (3.82 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/series/accessors/__pycache__/test_sparse_accessor.cpython-310.pyc ADDED
Binary file (790 Bytes). View file