applied-ai-018 commited on
Commit
49fc484
·
verified ·
1 Parent(s): 7d19378

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/14.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
  2. ckpts/universal/global_step80/zero/26.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
  3. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/__init__.cpython-310.pyc +0 -0
  4. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/common.cpython-310.pyc +0 -0
  5. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/conftest.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_alter_axes.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_api.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_arrow_interface.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_block_internals.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_constructors.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_cumulative.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_iteration.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_logical_ops.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_nonunique_indexes.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_npfuncs.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_query_eval.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_reductions.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_repr.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_stack_unstack.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_subclass.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_ufunc.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_unary.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_validate.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/__init__.py +0 -0
  26. venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/__pycache__/__init__.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/__pycache__/test_from_dict.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/__pycache__/test_from_records.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/test_from_dict.py +228 -0
  30. venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/test_from_records.py +505 -0
  31. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__init__.py +0 -0
  32. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/__init__.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_coercion.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_delitem.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_get.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_get_value.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_getitem.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_indexing.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_insert.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_mask.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_set_value.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_setitem.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_take.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_where.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_xs.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_coercion.py +199 -0
  47. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_delitem.py +60 -0
  48. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_get.py +27 -0
  49. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_get_value.py +22 -0
  50. venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_getitem.py +472 -0
ckpts/universal/global_step80/zero/14.mlp.dense_h_to_4h_swiglu.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c6913781bec7a7e712ba47cf9820c97bfe145bbdabf736adb519d48b5dddb8c
3
+ size 33555533
ckpts/universal/global_step80/zero/26.mlp.dense_4h_to_h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20708760c2b7a78217316cb1903d48f4d1a8112ae64463a94f49106d01f952ad
3
+ size 33555612
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/common.cpython-310.pyc ADDED
Binary file (2.34 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (3.49 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_alter_axes.cpython-310.pyc ADDED
Binary file (1.23 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_api.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_arithmetic.cpython-310.pyc ADDED
Binary file (58.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_arrow_interface.cpython-310.pyc ADDED
Binary file (1.43 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_block_internals.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (115 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_cumulative.cpython-310.pyc ADDED
Binary file (2.44 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_iteration.cpython-310.pyc ADDED
Binary file (6.06 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_logical_ops.cpython-310.pyc ADDED
Binary file (6.14 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_nonunique_indexes.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_npfuncs.cpython-310.pyc ADDED
Binary file (2.76 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_query_eval.cpython-310.pyc ADDED
Binary file (48.7 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_reductions.cpython-310.pyc ADDED
Binary file (56.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_repr.cpython-310.pyc ADDED
Binary file (17.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_stack_unstack.cpython-310.pyc ADDED
Binary file (68.2 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_subclass.cpython-310.pyc ADDED
Binary file (24 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_ufunc.cpython-310.pyc ADDED
Binary file (8.59 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_unary.cpython-310.pyc ADDED
Binary file (5.42 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/__pycache__/test_validate.cpython-310.pyc ADDED
Binary file (1.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/__pycache__/test_from_dict.cpython-310.pyc ADDED
Binary file (6.87 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/__pycache__/test_from_records.cpython-310.pyc ADDED
Binary file (17.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/test_from_dict.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas._config import using_pyarrow_string_dtype
7
+
8
+ from pandas import (
9
+ DataFrame,
10
+ Index,
11
+ MultiIndex,
12
+ RangeIndex,
13
+ Series,
14
+ )
15
+ import pandas._testing as tm
16
+
17
+
18
+ class TestFromDict:
19
+ # Note: these tests are specific to the from_dict method, not for
20
+ # passing dictionaries to DataFrame.__init__
21
+
22
+ def test_constructor_list_of_odicts(self):
23
+ data = [
24
+ OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]),
25
+ OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]),
26
+ OrderedDict([["a", 1.5], ["d", 6]]),
27
+ OrderedDict(),
28
+ OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]),
29
+ OrderedDict([["b", 3], ["c", 4], ["d", 6]]),
30
+ ]
31
+
32
+ result = DataFrame(data)
33
+ expected = DataFrame.from_dict(
34
+ dict(zip(range(len(data)), data)), orient="index"
35
+ )
36
+ tm.assert_frame_equal(result, expected.reindex(result.index))
37
+
38
+ def test_constructor_single_row(self):
39
+ data = [OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]])]
40
+
41
+ result = DataFrame(data)
42
+ expected = DataFrame.from_dict(dict(zip([0], data)), orient="index").reindex(
43
+ result.index
44
+ )
45
+ tm.assert_frame_equal(result, expected)
46
+
47
+ @pytest.mark.skipif(
48
+ using_pyarrow_string_dtype(), reason="columns inferring logic broken"
49
+ )
50
+ def test_constructor_list_of_series(self):
51
+ data = [
52
+ OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]),
53
+ OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]),
54
+ ]
55
+ sdict = OrderedDict(zip(["x", "y"], data))
56
+ idx = Index(["a", "b", "c"])
57
+
58
+ # all named
59
+ data2 = [
60
+ Series([1.5, 3, 4], idx, dtype="O", name="x"),
61
+ Series([1.5, 3, 6], idx, name="y"),
62
+ ]
63
+ result = DataFrame(data2)
64
+ expected = DataFrame.from_dict(sdict, orient="index")
65
+ tm.assert_frame_equal(result, expected)
66
+
67
+ # some unnamed
68
+ data2 = [
69
+ Series([1.5, 3, 4], idx, dtype="O", name="x"),
70
+ Series([1.5, 3, 6], idx),
71
+ ]
72
+ result = DataFrame(data2)
73
+
74
+ sdict = OrderedDict(zip(["x", "Unnamed 0"], data))
75
+ expected = DataFrame.from_dict(sdict, orient="index")
76
+ tm.assert_frame_equal(result, expected)
77
+
78
+ # none named
79
+ data = [
80
+ OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]),
81
+ OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]),
82
+ OrderedDict([["a", 1.5], ["d", 6]]),
83
+ OrderedDict(),
84
+ OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]),
85
+ OrderedDict([["b", 3], ["c", 4], ["d", 6]]),
86
+ ]
87
+ data = [Series(d) for d in data]
88
+
89
+ result = DataFrame(data)
90
+ sdict = OrderedDict(zip(range(len(data)), data))
91
+ expected = DataFrame.from_dict(sdict, orient="index")
92
+ tm.assert_frame_equal(result, expected.reindex(result.index))
93
+
94
+ result2 = DataFrame(data, index=np.arange(6, dtype=np.int64))
95
+ tm.assert_frame_equal(result, result2)
96
+
97
+ result = DataFrame([Series(dtype=object)])
98
+ expected = DataFrame(index=[0])
99
+ tm.assert_frame_equal(result, expected)
100
+
101
+ data = [
102
+ OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]),
103
+ OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]),
104
+ ]
105
+ sdict = OrderedDict(zip(range(len(data)), data))
106
+
107
+ idx = Index(["a", "b", "c"])
108
+ data2 = [Series([1.5, 3, 4], idx, dtype="O"), Series([1.5, 3, 6], idx)]
109
+ result = DataFrame(data2)
110
+ expected = DataFrame.from_dict(sdict, orient="index")
111
+ tm.assert_frame_equal(result, expected)
112
+
113
+ def test_constructor_orient(self, float_string_frame):
114
+ data_dict = float_string_frame.T._series
115
+ recons = DataFrame.from_dict(data_dict, orient="index")
116
+ expected = float_string_frame.reindex(index=recons.index)
117
+ tm.assert_frame_equal(recons, expected)
118
+
119
+ # dict of sequence
120
+ a = {"hi": [32, 3, 3], "there": [3, 5, 3]}
121
+ rs = DataFrame.from_dict(a, orient="index")
122
+ xp = DataFrame.from_dict(a).T.reindex(list(a.keys()))
123
+ tm.assert_frame_equal(rs, xp)
124
+
125
+ def test_constructor_from_ordered_dict(self):
126
+ # GH#8425
127
+ a = OrderedDict(
128
+ [
129
+ ("one", OrderedDict([("col_a", "foo1"), ("col_b", "bar1")])),
130
+ ("two", OrderedDict([("col_a", "foo2"), ("col_b", "bar2")])),
131
+ ("three", OrderedDict([("col_a", "foo3"), ("col_b", "bar3")])),
132
+ ]
133
+ )
134
+ expected = DataFrame.from_dict(a, orient="columns").T
135
+ result = DataFrame.from_dict(a, orient="index")
136
+ tm.assert_frame_equal(result, expected)
137
+
138
+ def test_from_dict_columns_parameter(self):
139
+ # GH#18529
140
+ # Test new columns parameter for from_dict that was added to make
141
+ # from_items(..., orient='index', columns=[...]) easier to replicate
142
+ result = DataFrame.from_dict(
143
+ OrderedDict([("A", [1, 2]), ("B", [4, 5])]),
144
+ orient="index",
145
+ columns=["one", "two"],
146
+ )
147
+ expected = DataFrame([[1, 2], [4, 5]], index=["A", "B"], columns=["one", "two"])
148
+ tm.assert_frame_equal(result, expected)
149
+
150
+ msg = "cannot use columns parameter with orient='columns'"
151
+ with pytest.raises(ValueError, match=msg):
152
+ DataFrame.from_dict(
153
+ {"A": [1, 2], "B": [4, 5]},
154
+ orient="columns",
155
+ columns=["one", "two"],
156
+ )
157
+ with pytest.raises(ValueError, match=msg):
158
+ DataFrame.from_dict({"A": [1, 2], "B": [4, 5]}, columns=["one", "two"])
159
+
160
+ @pytest.mark.parametrize(
161
+ "data_dict, orient, expected",
162
+ [
163
+ ({}, "index", RangeIndex(0)),
164
+ (
165
+ [{("a",): 1}, {("a",): 2}],
166
+ "columns",
167
+ Index([("a",)], tupleize_cols=False),
168
+ ),
169
+ (
170
+ [OrderedDict([(("a",), 1), (("b",), 2)])],
171
+ "columns",
172
+ Index([("a",), ("b",)], tupleize_cols=False),
173
+ ),
174
+ ([{("a", "b"): 1}], "columns", Index([("a", "b")], tupleize_cols=False)),
175
+ ],
176
+ )
177
+ def test_constructor_from_dict_tuples(self, data_dict, orient, expected):
178
+ # GH#16769
179
+ df = DataFrame.from_dict(data_dict, orient)
180
+ result = df.columns
181
+ tm.assert_index_equal(result, expected)
182
+
183
+ def test_frame_dict_constructor_empty_series(self):
184
+ s1 = Series(
185
+ [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (2, 2), (2, 4)])
186
+ )
187
+ s2 = Series(
188
+ [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)])
189
+ )
190
+ s3 = Series(dtype=object)
191
+
192
+ # it works!
193
+ DataFrame({"foo": s1, "bar": s2, "baz": s3})
194
+ DataFrame.from_dict({"foo": s1, "baz": s3, "bar": s2})
195
+
196
+ def test_from_dict_scalars_requires_index(self):
197
+ msg = "If using all scalar values, you must pass an index"
198
+ with pytest.raises(ValueError, match=msg):
199
+ DataFrame.from_dict(OrderedDict([("b", 8), ("a", 5), ("a", 6)]))
200
+
201
+ def test_from_dict_orient_invalid(self):
202
+ msg = (
203
+ "Expected 'index', 'columns' or 'tight' for orient parameter. "
204
+ "Got 'abc' instead"
205
+ )
206
+ with pytest.raises(ValueError, match=msg):
207
+ DataFrame.from_dict({"foo": 1, "baz": 3, "bar": 2}, orient="abc")
208
+
209
+ def test_from_dict_order_with_single_column(self):
210
+ data = {
211
+ "alpha": {
212
+ "value2": 123,
213
+ "value1": 532,
214
+ "animal": 222,
215
+ "plant": False,
216
+ "name": "test",
217
+ }
218
+ }
219
+ result = DataFrame.from_dict(
220
+ data,
221
+ orient="columns",
222
+ )
223
+ expected = DataFrame(
224
+ [[123], [532], [222], [False], ["test"]],
225
+ index=["value2", "value1", "animal", "plant", "name"],
226
+ columns=["alpha"],
227
+ )
228
+ tm.assert_frame_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/frame/constructors/test_from_records.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterator
2
+ from datetime import datetime
3
+ from decimal import Decimal
4
+
5
+ import numpy as np
6
+ import pytest
7
+ import pytz
8
+
9
+ from pandas._config import using_pyarrow_string_dtype
10
+
11
+ from pandas.compat import is_platform_little_endian
12
+
13
+ from pandas import (
14
+ CategoricalIndex,
15
+ DataFrame,
16
+ Index,
17
+ Interval,
18
+ RangeIndex,
19
+ Series,
20
+ date_range,
21
+ )
22
+ import pandas._testing as tm
23
+
24
+
25
+ class TestFromRecords:
26
+ def test_from_records_dt64tz_frame(self):
27
+ # GH#51162 don't lose tz when calling from_records with DataFrame input
28
+ dti = date_range("2016-01-01", periods=10, tz="US/Pacific")
29
+ df = DataFrame({i: dti for i in range(4)})
30
+ with tm.assert_produces_warning(FutureWarning):
31
+ res = DataFrame.from_records(df)
32
+ tm.assert_frame_equal(res, df)
33
+
34
+ def test_from_records_with_datetimes(self):
35
+ # this may fail on certain platforms because of a numpy issue
36
+ # related GH#6140
37
+ if not is_platform_little_endian():
38
+ pytest.skip("known failure of test on non-little endian")
39
+
40
+ # construction with a null in a recarray
41
+ # GH#6140
42
+ expected = DataFrame({"EXPIRY": [datetime(2005, 3, 1, 0, 0), None]})
43
+
44
+ arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])]
45
+ dtypes = [("EXPIRY", "<M8[ns]")]
46
+
47
+ recarray = np.rec.fromarrays(arrdata, dtype=dtypes)
48
+
49
+ result = DataFrame.from_records(recarray)
50
+ tm.assert_frame_equal(result, expected)
51
+
52
+ # coercion should work too
53
+ arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])]
54
+ dtypes = [("EXPIRY", "<M8[m]")]
55
+ recarray = np.rec.fromarrays(arrdata, dtype=dtypes)
56
+ result = DataFrame.from_records(recarray)
57
+ # we get the closest supported unit, "s"
58
+ expected["EXPIRY"] = expected["EXPIRY"].astype("M8[s]")
59
+ tm.assert_frame_equal(result, expected)
60
+
61
+ @pytest.mark.skipif(
62
+ using_pyarrow_string_dtype(), reason="dtype checking logic doesn't work"
63
+ )
64
+ def test_from_records_sequencelike(self):
65
+ df = DataFrame(
66
+ {
67
+ "A": np.array(
68
+ np.random.default_rng(2).standard_normal(6), dtype=np.float64
69
+ ),
70
+ "A1": np.array(
71
+ np.random.default_rng(2).standard_normal(6), dtype=np.float64
72
+ ),
73
+ "B": np.array(np.arange(6), dtype=np.int64),
74
+ "C": ["foo"] * 6,
75
+ "D": np.array([True, False] * 3, dtype=bool),
76
+ "E": np.array(
77
+ np.random.default_rng(2).standard_normal(6), dtype=np.float32
78
+ ),
79
+ "E1": np.array(
80
+ np.random.default_rng(2).standard_normal(6), dtype=np.float32
81
+ ),
82
+ "F": np.array(np.arange(6), dtype=np.int32),
83
+ }
84
+ )
85
+
86
+ # this is actually tricky to create the recordlike arrays and
87
+ # have the dtypes be intact
88
+ blocks = df._to_dict_of_blocks()
89
+ tuples = []
90
+ columns = []
91
+ dtypes = []
92
+ for dtype, b in blocks.items():
93
+ columns.extend(b.columns)
94
+ dtypes.extend([(c, np.dtype(dtype).descr[0][1]) for c in b.columns])
95
+ for i in range(len(df.index)):
96
+ tup = []
97
+ for _, b in blocks.items():
98
+ tup.extend(b.iloc[i].values)
99
+ tuples.append(tuple(tup))
100
+
101
+ recarray = np.array(tuples, dtype=dtypes).view(np.rec.recarray)
102
+ recarray2 = df.to_records()
103
+ lists = [list(x) for x in tuples]
104
+
105
+ # tuples (lose the dtype info)
106
+ result = DataFrame.from_records(tuples, columns=columns).reindex(
107
+ columns=df.columns
108
+ )
109
+
110
+ # created recarray and with to_records recarray (have dtype info)
111
+ result2 = DataFrame.from_records(recarray, columns=columns).reindex(
112
+ columns=df.columns
113
+ )
114
+ result3 = DataFrame.from_records(recarray2, columns=columns).reindex(
115
+ columns=df.columns
116
+ )
117
+
118
+ # list of tuples (no dtype info)
119
+ result4 = DataFrame.from_records(lists, columns=columns).reindex(
120
+ columns=df.columns
121
+ )
122
+
123
+ tm.assert_frame_equal(result, df, check_dtype=False)
124
+ tm.assert_frame_equal(result2, df)
125
+ tm.assert_frame_equal(result3, df)
126
+ tm.assert_frame_equal(result4, df, check_dtype=False)
127
+
128
+ # tuples is in the order of the columns
129
+ result = DataFrame.from_records(tuples)
130
+ tm.assert_index_equal(result.columns, RangeIndex(8))
131
+
132
+ # test exclude parameter & we are casting the results here (as we don't
133
+ # have dtype info to recover)
134
+ columns_to_test = [columns.index("C"), columns.index("E1")]
135
+
136
+ exclude = list(set(range(8)) - set(columns_to_test))
137
+ result = DataFrame.from_records(tuples, exclude=exclude)
138
+ result.columns = [columns[i] for i in sorted(columns_to_test)]
139
+ tm.assert_series_equal(result["C"], df["C"])
140
+ tm.assert_series_equal(result["E1"], df["E1"])
141
+
142
+ def test_from_records_sequencelike_empty(self):
143
+ # empty case
144
+ result = DataFrame.from_records([], columns=["foo", "bar", "baz"])
145
+ assert len(result) == 0
146
+ tm.assert_index_equal(result.columns, Index(["foo", "bar", "baz"]))
147
+
148
+ result = DataFrame.from_records([])
149
+ assert len(result) == 0
150
+ assert len(result.columns) == 0
151
+
152
+ def test_from_records_dictlike(self):
153
+ # test the dict methods
154
+ df = DataFrame(
155
+ {
156
+ "A": np.array(
157
+ np.random.default_rng(2).standard_normal(6), dtype=np.float64
158
+ ),
159
+ "A1": np.array(
160
+ np.random.default_rng(2).standard_normal(6), dtype=np.float64
161
+ ),
162
+ "B": np.array(np.arange(6), dtype=np.int64),
163
+ "C": ["foo"] * 6,
164
+ "D": np.array([True, False] * 3, dtype=bool),
165
+ "E": np.array(
166
+ np.random.default_rng(2).standard_normal(6), dtype=np.float32
167
+ ),
168
+ "E1": np.array(
169
+ np.random.default_rng(2).standard_normal(6), dtype=np.float32
170
+ ),
171
+ "F": np.array(np.arange(6), dtype=np.int32),
172
+ }
173
+ )
174
+
175
+ # columns is in a different order here than the actual items iterated
176
+ # from the dict
177
+ blocks = df._to_dict_of_blocks()
178
+ columns = []
179
+ for b in blocks.values():
180
+ columns.extend(b.columns)
181
+
182
+ asdict = dict(df.items())
183
+ asdict2 = {x: y.values for x, y in df.items()}
184
+
185
+ # dict of series & dict of ndarrays (have dtype info)
186
+ results = []
187
+ results.append(DataFrame.from_records(asdict).reindex(columns=df.columns))
188
+ results.append(
189
+ DataFrame.from_records(asdict, columns=columns).reindex(columns=df.columns)
190
+ )
191
+ results.append(
192
+ DataFrame.from_records(asdict2, columns=columns).reindex(columns=df.columns)
193
+ )
194
+
195
+ for r in results:
196
+ tm.assert_frame_equal(r, df)
197
+
198
+ def test_from_records_with_index_data(self):
199
+ df = DataFrame(
200
+ np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"]
201
+ )
202
+
203
+ data = np.random.default_rng(2).standard_normal(10)
204
+ with tm.assert_produces_warning(FutureWarning):
205
+ df1 = DataFrame.from_records(df, index=data)
206
+ tm.assert_index_equal(df1.index, Index(data))
207
+
208
+ def test_from_records_bad_index_column(self):
209
+ df = DataFrame(
210
+ np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"]
211
+ )
212
+
213
+ # should pass
214
+ with tm.assert_produces_warning(FutureWarning):
215
+ df1 = DataFrame.from_records(df, index=["C"])
216
+ tm.assert_index_equal(df1.index, Index(df.C))
217
+
218
+ with tm.assert_produces_warning(FutureWarning):
219
+ df1 = DataFrame.from_records(df, index="C")
220
+ tm.assert_index_equal(df1.index, Index(df.C))
221
+
222
+ # should fail
223
+ msg = "|".join(
224
+ [
225
+ r"'None of \[2\] are in the columns'",
226
+ ]
227
+ )
228
+ with pytest.raises(KeyError, match=msg):
229
+ with tm.assert_produces_warning(FutureWarning):
230
+ DataFrame.from_records(df, index=[2])
231
+ with pytest.raises(KeyError, match=msg):
232
+ with tm.assert_produces_warning(FutureWarning):
233
+ DataFrame.from_records(df, index=2)
234
+
235
+ def test_from_records_non_tuple(self):
236
+ class Record:
237
+ def __init__(self, *args) -> None:
238
+ self.args = args
239
+
240
+ def __getitem__(self, i):
241
+ return self.args[i]
242
+
243
+ def __iter__(self) -> Iterator:
244
+ return iter(self.args)
245
+
246
+ recs = [Record(1, 2, 3), Record(4, 5, 6), Record(7, 8, 9)]
247
+ tups = [tuple(rec) for rec in recs]
248
+
249
+ result = DataFrame.from_records(recs)
250
+ expected = DataFrame.from_records(tups)
251
+ tm.assert_frame_equal(result, expected)
252
+
253
+ def test_from_records_len0_with_columns(self):
254
+ # GH#2633
255
+ result = DataFrame.from_records([], index="foo", columns=["foo", "bar"])
256
+ expected = Index(["bar"])
257
+
258
+ assert len(result) == 0
259
+ assert result.index.name == "foo"
260
+ tm.assert_index_equal(result.columns, expected)
261
+
262
+ def test_from_records_series_list_dict(self):
263
+ # GH#27358
264
+ expected = DataFrame([[{"a": 1, "b": 2}, {"a": 3, "b": 4}]]).T
265
+ data = Series([[{"a": 1, "b": 2}], [{"a": 3, "b": 4}]])
266
+ result = DataFrame.from_records(data)
267
+ tm.assert_frame_equal(result, expected)
268
+
269
+ def test_from_records_series_categorical_index(self):
270
+ # GH#32805
271
+ index = CategoricalIndex(
272
+ [Interval(-20, -10), Interval(-10, 0), Interval(0, 10)]
273
+ )
274
+ series_of_dicts = Series([{"a": 1}, {"a": 2}, {"b": 3}], index=index)
275
+ frame = DataFrame.from_records(series_of_dicts, index=index)
276
+ expected = DataFrame(
277
+ {"a": [1, 2, np.nan], "b": [np.nan, np.nan, 3]}, index=index
278
+ )
279
+ tm.assert_frame_equal(frame, expected)
280
+
281
+ def test_frame_from_records_utc(self):
282
+ rec = {"datum": 1.5, "begin_time": datetime(2006, 4, 27, tzinfo=pytz.utc)}
283
+
284
+ # it works
285
+ DataFrame.from_records([rec], index="begin_time")
286
+
287
+ def test_from_records_to_records(self):
288
+ # from numpy documentation
289
+ arr = np.zeros((2,), dtype=("i4,f4,S10"))
290
+ arr[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")]
291
+
292
+ DataFrame.from_records(arr)
293
+
294
+ index = Index(np.arange(len(arr))[::-1])
295
+ indexed_frame = DataFrame.from_records(arr, index=index)
296
+ tm.assert_index_equal(indexed_frame.index, index)
297
+
298
+ # without names, it should go to last ditch
299
+ arr2 = np.zeros((2, 3))
300
+ tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2))
301
+
302
+ # wrong length
303
+ msg = "|".join(
304
+ [
305
+ r"Length of values \(2\) does not match length of index \(1\)",
306
+ ]
307
+ )
308
+ with pytest.raises(ValueError, match=msg):
309
+ DataFrame.from_records(arr, index=index[:-1])
310
+
311
+ indexed_frame = DataFrame.from_records(arr, index="f1")
312
+
313
+ # what to do?
314
+ records = indexed_frame.to_records()
315
+ assert len(records.dtype.names) == 3
316
+
317
+ records = indexed_frame.to_records(index=False)
318
+ assert len(records.dtype.names) == 2
319
+ assert "index" not in records.dtype.names
320
+
321
+ def test_from_records_nones(self):
322
+ tuples = [(1, 2, None, 3), (1, 2, None, 3), (None, 2, 5, 3)]
323
+
324
+ df = DataFrame.from_records(tuples, columns=["a", "b", "c", "d"])
325
+ assert np.isnan(df["c"][0])
326
+
327
+ def test_from_records_iterator(self):
328
+ arr = np.array(
329
+ [(1.0, 1.0, 2, 2), (3.0, 3.0, 4, 4), (5.0, 5.0, 6, 6), (7.0, 7.0, 8, 8)],
330
+ dtype=[
331
+ ("x", np.float64),
332
+ ("u", np.float32),
333
+ ("y", np.int64),
334
+ ("z", np.int32),
335
+ ],
336
+ )
337
+ df = DataFrame.from_records(iter(arr), nrows=2)
338
+ xp = DataFrame(
339
+ {
340
+ "x": np.array([1.0, 3.0], dtype=np.float64),
341
+ "u": np.array([1.0, 3.0], dtype=np.float32),
342
+ "y": np.array([2, 4], dtype=np.int64),
343
+ "z": np.array([2, 4], dtype=np.int32),
344
+ }
345
+ )
346
+ tm.assert_frame_equal(df.reindex_like(xp), xp)
347
+
348
+ # no dtypes specified here, so just compare with the default
349
+ arr = [(1.0, 2), (3.0, 4), (5.0, 6), (7.0, 8)]
350
+ df = DataFrame.from_records(iter(arr), columns=["x", "y"], nrows=2)
351
+ tm.assert_frame_equal(df, xp.reindex(columns=["x", "y"]), check_dtype=False)
352
+
353
+ def test_from_records_tuples_generator(self):
354
+ def tuple_generator(length):
355
+ for i in range(length):
356
+ letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
357
+ yield (i, letters[i % len(letters)], i / length)
358
+
359
+ columns_names = ["Integer", "String", "Float"]
360
+ columns = [
361
+ [i[j] for i in tuple_generator(10)] for j in range(len(columns_names))
362
+ ]
363
+ data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]}
364
+ expected = DataFrame(data, columns=columns_names)
365
+
366
+ generator = tuple_generator(10)
367
+ result = DataFrame.from_records(generator, columns=columns_names)
368
+ tm.assert_frame_equal(result, expected)
369
+
370
+ def test_from_records_lists_generator(self):
371
+ def list_generator(length):
372
+ for i in range(length):
373
+ letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
374
+ yield [i, letters[i % len(letters)], i / length]
375
+
376
+ columns_names = ["Integer", "String", "Float"]
377
+ columns = [
378
+ [i[j] for i in list_generator(10)] for j in range(len(columns_names))
379
+ ]
380
+ data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]}
381
+ expected = DataFrame(data, columns=columns_names)
382
+
383
+ generator = list_generator(10)
384
+ result = DataFrame.from_records(generator, columns=columns_names)
385
+ tm.assert_frame_equal(result, expected)
386
+
387
+ def test_from_records_columns_not_modified(self):
388
+ tuples = [(1, 2, 3), (1, 2, 3), (2, 5, 3)]
389
+
390
+ columns = ["a", "b", "c"]
391
+ original_columns = list(columns)
392
+
393
+ DataFrame.from_records(tuples, columns=columns, index="a")
394
+
395
+ assert columns == original_columns
396
+
397
+ def test_from_records_decimal(self):
398
+ tuples = [(Decimal("1.5"),), (Decimal("2.5"),), (None,)]
399
+
400
+ df = DataFrame.from_records(tuples, columns=["a"])
401
+ assert df["a"].dtype == object
402
+
403
+ df = DataFrame.from_records(tuples, columns=["a"], coerce_float=True)
404
+ assert df["a"].dtype == np.float64
405
+ assert np.isnan(df["a"].values[-1])
406
+
407
+ def test_from_records_duplicates(self):
408
+ result = DataFrame.from_records([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"])
409
+
410
+ expected = DataFrame([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"])
411
+
412
+ tm.assert_frame_equal(result, expected)
413
+
414
+ def test_from_records_set_index_name(self):
415
+ def create_dict(order_id):
416
+ return {
417
+ "order_id": order_id,
418
+ "quantity": np.random.default_rng(2).integers(1, 10),
419
+ "price": np.random.default_rng(2).integers(1, 10),
420
+ }
421
+
422
+ documents = [create_dict(i) for i in range(10)]
423
+ # demo missing data
424
+ documents.append({"order_id": 10, "quantity": 5})
425
+
426
+ result = DataFrame.from_records(documents, index="order_id")
427
+ assert result.index.name == "order_id"
428
+
429
+ # MultiIndex
430
+ result = DataFrame.from_records(documents, index=["order_id", "quantity"])
431
+ assert result.index.names == ("order_id", "quantity")
432
+
433
+ def test_from_records_misc_brokenness(self):
434
+ # GH#2179
435
+
436
+ data = {1: ["foo"], 2: ["bar"]}
437
+
438
+ result = DataFrame.from_records(data, columns=["a", "b"])
439
+ exp = DataFrame(data, columns=["a", "b"])
440
+ tm.assert_frame_equal(result, exp)
441
+
442
+ # overlap in index/index_names
443
+
444
+ data = {"a": [1, 2, 3], "b": [4, 5, 6]}
445
+
446
+ result = DataFrame.from_records(data, index=["a", "b", "c"])
447
+ exp = DataFrame(data, index=["a", "b", "c"])
448
+ tm.assert_frame_equal(result, exp)
449
+
450
+ def test_from_records_misc_brokenness2(self):
451
+ # GH#2623
452
+ rows = []
453
+ rows.append([datetime(2010, 1, 1), 1])
454
+ rows.append([datetime(2010, 1, 2), "hi"]) # test col upconverts to obj
455
+ result = DataFrame.from_records(rows, columns=["date", "test"])
456
+ expected = DataFrame(
457
+ {"date": [row[0] for row in rows], "test": [row[1] for row in rows]}
458
+ )
459
+ tm.assert_frame_equal(result, expected)
460
+ assert result.dtypes["test"] == np.dtype(object)
461
+
462
+ def test_from_records_misc_brokenness3(self):
463
+ rows = []
464
+ rows.append([datetime(2010, 1, 1), 1])
465
+ rows.append([datetime(2010, 1, 2), 1])
466
+ result = DataFrame.from_records(rows, columns=["date", "test"])
467
+ expected = DataFrame(
468
+ {"date": [row[0] for row in rows], "test": [row[1] for row in rows]}
469
+ )
470
+ tm.assert_frame_equal(result, expected)
471
+
472
+ def test_from_records_empty(self):
473
+ # GH#3562
474
+ result = DataFrame.from_records([], columns=["a", "b", "c"])
475
+ expected = DataFrame(columns=["a", "b", "c"])
476
+ tm.assert_frame_equal(result, expected)
477
+
478
+ result = DataFrame.from_records([], columns=["a", "b", "b"])
479
+ expected = DataFrame(columns=["a", "b", "b"])
480
+ tm.assert_frame_equal(result, expected)
481
+
482
+ def test_from_records_empty_with_nonempty_fields_gh3682(self):
483
+ a = np.array([(1, 2)], dtype=[("id", np.int64), ("value", np.int64)])
484
+ df = DataFrame.from_records(a, index="id")
485
+
486
+ ex_index = Index([1], name="id")
487
+ expected = DataFrame({"value": [2]}, index=ex_index, columns=["value"])
488
+ tm.assert_frame_equal(df, expected)
489
+
490
+ b = a[:0]
491
+ df2 = DataFrame.from_records(b, index="id")
492
+ tm.assert_frame_equal(df2, df.iloc[:0])
493
+
494
+ def test_from_records_empty2(self):
495
+ # GH#42456
496
+ dtype = [("prop", int)]
497
+ shape = (0, len(dtype))
498
+ arr = np.empty(shape, dtype=dtype)
499
+
500
+ result = DataFrame.from_records(arr)
501
+ expected = DataFrame({"prop": np.array([], dtype=int)})
502
+ tm.assert_frame_equal(result, expected)
503
+
504
+ alt = DataFrame(arr)
505
+ tm.assert_frame_equal(alt, expected)
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (195 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_coercion.cpython-310.pyc ADDED
Binary file (5.23 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_delitem.cpython-310.pyc ADDED
Binary file (2.15 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_get.cpython-310.pyc ADDED
Binary file (1 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_get_value.cpython-310.pyc ADDED
Binary file (1.15 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_getitem.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (58.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_insert.cpython-310.pyc ADDED
Binary file (4.37 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_mask.cpython-310.pyc ADDED
Binary file (5.46 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_set_value.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_setitem.cpython-310.pyc ADDED
Binary file (48.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_take.cpython-310.pyc ADDED
Binary file (2.86 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_where.cpython-310.pyc ADDED
Binary file (30.6 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/__pycache__/test_xs.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_coercion.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for values coercion in setitem-like operations on DataFrame.
3
+
4
+ For the most part, these should be multi-column DataFrames, otherwise
5
+ we would share the tests with Series.
6
+ """
7
+ import numpy as np
8
+ import pytest
9
+
10
+ import pandas as pd
11
+ from pandas import (
12
+ DataFrame,
13
+ MultiIndex,
14
+ NaT,
15
+ Series,
16
+ Timestamp,
17
+ date_range,
18
+ )
19
+ import pandas._testing as tm
20
+
21
+
22
+ class TestDataFrameSetitemCoercion:
23
+ @pytest.mark.parametrize("consolidate", [True, False])
24
+ def test_loc_setitem_multiindex_columns(self, consolidate):
25
+ # GH#18415 Setting values in a single column preserves dtype,
26
+ # while setting them in multiple columns did unwanted cast.
27
+
28
+ # Note that A here has 2 blocks, below we do the same thing
29
+ # with a consolidated frame.
30
+ A = DataFrame(np.zeros((6, 5), dtype=np.float32))
31
+ A = pd.concat([A, A], axis=1, keys=[1, 2])
32
+ if consolidate:
33
+ A = A._consolidate()
34
+
35
+ A.loc[2:3, (1, slice(2, 3))] = np.ones((2, 2), dtype=np.float32)
36
+ assert (A.dtypes == np.float32).all()
37
+
38
+ A.loc[0:5, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
39
+
40
+ assert (A.dtypes == np.float32).all()
41
+
42
+ A.loc[:, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
43
+ assert (A.dtypes == np.float32).all()
44
+
45
+ # TODO: i think this isn't about MultiIndex and could be done with iloc?
46
+
47
+
48
+ def test_37477():
49
+ # fixed by GH#45121
50
+ orig = DataFrame({"A": [1, 2, 3], "B": [3, 4, 5]})
51
+ expected = DataFrame({"A": [1, 2, 3], "B": [3, 1.2, 5]})
52
+
53
+ df = orig.copy()
54
+ with tm.assert_produces_warning(
55
+ FutureWarning, match="Setting an item of incompatible dtype"
56
+ ):
57
+ df.at[1, "B"] = 1.2
58
+ tm.assert_frame_equal(df, expected)
59
+
60
+ df = orig.copy()
61
+ with tm.assert_produces_warning(
62
+ FutureWarning, match="Setting an item of incompatible dtype"
63
+ ):
64
+ df.loc[1, "B"] = 1.2
65
+ tm.assert_frame_equal(df, expected)
66
+
67
+ df = orig.copy()
68
+ with tm.assert_produces_warning(
69
+ FutureWarning, match="Setting an item of incompatible dtype"
70
+ ):
71
+ df.iat[1, 1] = 1.2
72
+ tm.assert_frame_equal(df, expected)
73
+
74
+ df = orig.copy()
75
+ with tm.assert_produces_warning(
76
+ FutureWarning, match="Setting an item of incompatible dtype"
77
+ ):
78
+ df.iloc[1, 1] = 1.2
79
+ tm.assert_frame_equal(df, expected)
80
+
81
+
82
+ def test_6942(indexer_al):
83
+ # check that the .at __setitem__ after setting "Live" actually sets the data
84
+ start = Timestamp("2014-04-01")
85
+ t1 = Timestamp("2014-04-23 12:42:38.883082")
86
+ t2 = Timestamp("2014-04-24 01:33:30.040039")
87
+
88
+ dti = date_range(start, periods=1)
89
+ orig = DataFrame(index=dti, columns=["timenow", "Live"])
90
+
91
+ df = orig.copy()
92
+ indexer_al(df)[start, "timenow"] = t1
93
+
94
+ df["Live"] = True
95
+
96
+ df.at[start, "timenow"] = t2
97
+ assert df.iloc[0, 0] == t2
98
+
99
+
100
+ def test_26395(indexer_al):
101
+ # .at case fixed by GH#45121 (best guess)
102
+ df = DataFrame(index=["A", "B", "C"])
103
+ df["D"] = 0
104
+
105
+ indexer_al(df)["C", "D"] = 2
106
+ expected = DataFrame({"D": [0, 0, 2]}, index=["A", "B", "C"], dtype=np.int64)
107
+ tm.assert_frame_equal(df, expected)
108
+
109
+ with tm.assert_produces_warning(
110
+ FutureWarning, match="Setting an item of incompatible dtype"
111
+ ):
112
+ indexer_al(df)["C", "D"] = 44.5
113
+ expected = DataFrame({"D": [0, 0, 44.5]}, index=["A", "B", "C"], dtype=np.float64)
114
+ tm.assert_frame_equal(df, expected)
115
+
116
+ with tm.assert_produces_warning(
117
+ FutureWarning, match="Setting an item of incompatible dtype"
118
+ ):
119
+ indexer_al(df)["C", "D"] = "hello"
120
+ expected = DataFrame({"D": [0, 0, "hello"]}, index=["A", "B", "C"], dtype=object)
121
+ tm.assert_frame_equal(df, expected)
122
+
123
+
124
+ @pytest.mark.xfail(reason="unwanted upcast")
125
+ def test_15231():
126
+ df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
127
+ df.loc[2] = Series({"a": 5, "b": 6})
128
+ assert (df.dtypes == np.int64).all()
129
+
130
+ df.loc[3] = Series({"a": 7})
131
+
132
+ # df["a"] doesn't have any NaNs, should not have been cast
133
+ exp_dtypes = Series([np.int64, np.float64], dtype=object, index=["a", "b"])
134
+ tm.assert_series_equal(df.dtypes, exp_dtypes)
135
+
136
+
137
+ def test_iloc_setitem_unnecesssary_float_upcasting():
138
+ # GH#12255
139
+ df = DataFrame(
140
+ {
141
+ 0: np.array([1, 3], dtype=np.float32),
142
+ 1: np.array([2, 4], dtype=np.float32),
143
+ 2: ["a", "b"],
144
+ }
145
+ )
146
+ orig = df.copy()
147
+
148
+ values = df[0].values.reshape(2, 1)
149
+ df.iloc[:, 0:1] = values
150
+
151
+ tm.assert_frame_equal(df, orig)
152
+
153
+
154
+ @pytest.mark.xfail(reason="unwanted casting to dt64")
155
+ def test_12499():
156
+ # TODO: OP in GH#12499 used np.datetim64("NaT") instead of pd.NaT,
157
+ # which has consequences for the expected df["two"] (though i think at
158
+ # the time it might not have because of a separate bug). See if it makes
159
+ # a difference which one we use here.
160
+ ts = Timestamp("2016-03-01 03:13:22.98986", tz="UTC")
161
+
162
+ data = [{"one": 0, "two": ts}]
163
+ orig = DataFrame(data)
164
+ df = orig.copy()
165
+ df.loc[1] = [np.nan, NaT]
166
+
167
+ expected = DataFrame(
168
+ {"one": [0, np.nan], "two": Series([ts, NaT], dtype="datetime64[ns, UTC]")}
169
+ )
170
+ tm.assert_frame_equal(df, expected)
171
+
172
+ data = [{"one": 0, "two": ts}]
173
+ df = orig.copy()
174
+ df.loc[1, :] = [np.nan, NaT]
175
+ tm.assert_frame_equal(df, expected)
176
+
177
+
178
+ def test_20476():
179
+ mi = MultiIndex.from_product([["A", "B"], ["a", "b", "c"]])
180
+ df = DataFrame(-1, index=range(3), columns=mi)
181
+ filler = DataFrame([[1, 2, 3.0]] * 3, index=range(3), columns=["a", "b", "c"])
182
+ df["A"] = filler
183
+
184
+ expected = DataFrame(
185
+ {
186
+ 0: [1, 1, 1],
187
+ 1: [2, 2, 2],
188
+ 2: [3.0, 3.0, 3.0],
189
+ 3: [-1, -1, -1],
190
+ 4: [-1, -1, -1],
191
+ 5: [-1, -1, -1],
192
+ }
193
+ )
194
+ expected.columns = mi
195
+ exp_dtypes = Series(
196
+ [np.dtype(np.int64)] * 2 + [np.dtype(np.float64)] + [np.dtype(np.int64)] * 3,
197
+ index=mi,
198
+ )
199
+ tm.assert_series_equal(df.dtypes, exp_dtypes)
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_delitem.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ DataFrame,
8
+ MultiIndex,
9
+ )
10
+
11
+
12
+ class TestDataFrameDelItem:
13
+ def test_delitem(self, float_frame):
14
+ del float_frame["A"]
15
+ assert "A" not in float_frame
16
+
17
+ def test_delitem_multiindex(self):
18
+ midx = MultiIndex.from_product([["A", "B"], [1, 2]])
19
+ df = DataFrame(np.random.default_rng(2).standard_normal((4, 4)), columns=midx)
20
+ assert len(df.columns) == 4
21
+ assert ("A",) in df.columns
22
+ assert "A" in df.columns
23
+
24
+ result = df["A"]
25
+ assert isinstance(result, DataFrame)
26
+ del df["A"]
27
+
28
+ assert len(df.columns) == 2
29
+
30
+ # A still in the levels, BUT get a KeyError if trying
31
+ # to delete
32
+ assert ("A",) not in df.columns
33
+ with pytest.raises(KeyError, match=re.escape("('A',)")):
34
+ del df[("A",)]
35
+
36
+ # behavior of dropped/deleted MultiIndex levels changed from
37
+ # GH 2770 to GH 19027: MultiIndex no longer '.__contains__'
38
+ # levels which are dropped/deleted
39
+ assert "A" not in df.columns
40
+ with pytest.raises(KeyError, match=re.escape("('A',)")):
41
+ del df["A"]
42
+
43
+ def test_delitem_corner(self, float_frame):
44
+ f = float_frame.copy()
45
+ del f["D"]
46
+ assert len(f.columns) == 3
47
+ with pytest.raises(KeyError, match=r"^'D'$"):
48
+ del f["D"]
49
+ del f["B"]
50
+ assert len(f.columns) == 2
51
+
52
+ def test_delitem_col_still_multiindex(self):
53
+ arrays = [["a", "b", "c", "top"], ["", "", "", "OD"], ["", "", "", "wx"]]
54
+
55
+ tuples = sorted(zip(*arrays))
56
+ index = MultiIndex.from_tuples(tuples)
57
+
58
+ df = DataFrame(np.random.default_rng(2).standard_normal((3, 4)), columns=index)
59
+ del df[("a", "", "")]
60
+ assert isinstance(df.columns, MultiIndex)
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_get.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import DataFrame
4
+ import pandas._testing as tm
5
+
6
+
7
+ class TestGet:
8
+ def test_get(self, float_frame):
9
+ b = float_frame.get("B")
10
+ tm.assert_series_equal(b, float_frame["B"])
11
+
12
+ assert float_frame.get("foo") is None
13
+ tm.assert_series_equal(
14
+ float_frame.get("foo", float_frame["B"]), float_frame["B"]
15
+ )
16
+
17
+ @pytest.mark.parametrize(
18
+ "df",
19
+ [
20
+ DataFrame(),
21
+ DataFrame(columns=list("AB")),
22
+ DataFrame(columns=list("AB"), index=range(3)),
23
+ ],
24
+ )
25
+ def test_get_none(self, df):
26
+ # see gh-5652
27
+ assert df.get(None) is None
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_get_value.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import (
4
+ DataFrame,
5
+ MultiIndex,
6
+ )
7
+
8
+
9
+ class TestGetValue:
10
+ def test_get_set_value_no_partial_indexing(self):
11
+ # partial w/ MultiIndex raise exception
12
+ index = MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)])
13
+ df = DataFrame(index=index, columns=range(4))
14
+ with pytest.raises(KeyError, match=r"^0$"):
15
+ df._get_value(0, 1)
16
+
17
+ def test_get_value(self, float_frame):
18
+ for idx in float_frame.index:
19
+ for col in float_frame.columns:
20
+ result = float_frame._get_value(idx, col)
21
+ expected = float_frame[col][idx]
22
+ assert result == expected
venv/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_getitem.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ Categorical,
8
+ CategoricalDtype,
9
+ CategoricalIndex,
10
+ DataFrame,
11
+ DateOffset,
12
+ DatetimeIndex,
13
+ Index,
14
+ MultiIndex,
15
+ Series,
16
+ Timestamp,
17
+ concat,
18
+ date_range,
19
+ get_dummies,
20
+ period_range,
21
+ )
22
+ import pandas._testing as tm
23
+ from pandas.core.arrays import SparseArray
24
+
25
+
26
+ class TestGetitem:
27
+ def test_getitem_unused_level_raises(self):
28
+ # GH#20410
29
+ mi = MultiIndex(
30
+ levels=[["a_lot", "onlyone", "notevenone"], [1970, ""]],
31
+ codes=[[1, 0], [1, 0]],
32
+ )
33
+ df = DataFrame(-1, index=range(3), columns=mi)
34
+
35
+ with pytest.raises(KeyError, match="notevenone"):
36
+ df["notevenone"]
37
+
38
+ def test_getitem_periodindex(self):
39
+ rng = period_range("1/1/2000", periods=5)
40
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)), columns=rng)
41
+
42
+ ts = df[rng[0]]
43
+ tm.assert_series_equal(ts, df.iloc[:, 0])
44
+
45
+ ts = df["1/1/2000"]
46
+ tm.assert_series_equal(ts, df.iloc[:, 0])
47
+
48
+ def test_getitem_list_of_labels_categoricalindex_cols(self):
49
+ # GH#16115
50
+ cats = Categorical([Timestamp("12-31-1999"), Timestamp("12-31-2000")])
51
+
52
+ expected = DataFrame([[1, 0], [0, 1]], dtype="bool", index=[0, 1], columns=cats)
53
+ dummies = get_dummies(cats)
54
+ result = dummies[list(dummies.columns)]
55
+ tm.assert_frame_equal(result, expected)
56
+
57
+ def test_getitem_sparse_column_return_type_and_dtype(self):
58
+ # https://github.com/pandas-dev/pandas/issues/23559
59
+ data = SparseArray([0, 1])
60
+ df = DataFrame({"A": data})
61
+ expected = Series(data, name="A")
62
+ result = df["A"]
63
+ tm.assert_series_equal(result, expected)
64
+
65
+ # Also check iloc and loc while we're here
66
+ result = df.iloc[:, 0]
67
+ tm.assert_series_equal(result, expected)
68
+
69
+ result = df.loc[:, "A"]
70
+ tm.assert_series_equal(result, expected)
71
+
72
+ def test_getitem_string_columns(self):
73
+ # GH#46185
74
+ df = DataFrame([[1, 2]], columns=Index(["A", "B"], dtype="string"))
75
+ result = df.A
76
+ expected = df["A"]
77
+ tm.assert_series_equal(result, expected)
78
+
79
+
80
+ class TestGetitemListLike:
81
+ def test_getitem_list_missing_key(self):
82
+ # GH#13822, incorrect error string with non-unique columns when missing
83
+ # column is accessed
84
+ df = DataFrame({"x": [1.0], "y": [2.0], "z": [3.0]})
85
+ df.columns = ["x", "x", "z"]
86
+
87
+ # Check that we get the correct value in the KeyError
88
+ with pytest.raises(KeyError, match=r"\['y'\] not in index"):
89
+ df[["x", "y", "z"]]
90
+
91
+ def test_getitem_list_duplicates(self):
92
+ # GH#1943
93
+ df = DataFrame(
94
+ np.random.default_rng(2).standard_normal((4, 4)), columns=list("AABC")
95
+ )
96
+ df.columns.name = "foo"
97
+
98
+ result = df[["B", "C"]]
99
+ assert result.columns.name == "foo"
100
+
101
+ expected = df.iloc[:, 2:]
102
+ tm.assert_frame_equal(result, expected)
103
+
104
+ def test_getitem_dupe_cols(self):
105
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
106
+ msg = "\"None of [Index(['baf'], dtype="
107
+ with pytest.raises(KeyError, match=re.escape(msg)):
108
+ df[["baf"]]
109
+
110
+ @pytest.mark.parametrize(
111
+ "idx_type",
112
+ [
113
+ list,
114
+ iter,
115
+ Index,
116
+ set,
117
+ lambda keys: dict(zip(keys, range(len(keys)))),
118
+ lambda keys: dict(zip(keys, range(len(keys)))).keys(),
119
+ ],
120
+ ids=["list", "iter", "Index", "set", "dict", "dict_keys"],
121
+ )
122
+ @pytest.mark.parametrize("levels", [1, 2])
123
+ def test_getitem_listlike(self, idx_type, levels, float_frame):
124
+ # GH#21294
125
+
126
+ if levels == 1:
127
+ frame, missing = float_frame, "food"
128
+ else:
129
+ # MultiIndex columns
130
+ frame = DataFrame(
131
+ np.random.default_rng(2).standard_normal((8, 3)),
132
+ columns=Index(
133
+ [("foo", "bar"), ("baz", "qux"), ("peek", "aboo")],
134
+ name=("sth", "sth2"),
135
+ ),
136
+ )
137
+ missing = ("good", "food")
138
+
139
+ keys = [frame.columns[1], frame.columns[0]]
140
+ idx = idx_type(keys)
141
+ idx_check = list(idx_type(keys))
142
+
143
+ if isinstance(idx, (set, dict)):
144
+ with pytest.raises(TypeError, match="as an indexer is not supported"):
145
+ frame[idx]
146
+
147
+ return
148
+ else:
149
+ result = frame[idx]
150
+
151
+ expected = frame.loc[:, idx_check]
152
+ expected.columns.names = frame.columns.names
153
+
154
+ tm.assert_frame_equal(result, expected)
155
+
156
+ idx = idx_type(keys + [missing])
157
+ with pytest.raises(KeyError, match="not in index"):
158
+ frame[idx]
159
+
160
+ def test_getitem_iloc_generator(self):
161
+ # GH#39614
162
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
163
+ indexer = (x for x in [1, 2])
164
+ result = df.iloc[indexer]
165
+ expected = DataFrame({"a": [2, 3], "b": [5, 6]}, index=[1, 2])
166
+ tm.assert_frame_equal(result, expected)
167
+
168
+ def test_getitem_iloc_two_dimensional_generator(self):
169
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
170
+ indexer = (x for x in [1, 2])
171
+ result = df.iloc[indexer, 1]
172
+ expected = Series([5, 6], name="b", index=[1, 2])
173
+ tm.assert_series_equal(result, expected)
174
+
175
+ def test_getitem_iloc_dateoffset_days(self):
176
+ # GH 46671
177
+ df = DataFrame(
178
+ list(range(10)),
179
+ index=date_range("01-01-2022", periods=10, freq=DateOffset(days=1)),
180
+ )
181
+ result = df.loc["2022-01-01":"2022-01-03"]
182
+ expected = DataFrame(
183
+ [0, 1, 2],
184
+ index=DatetimeIndex(
185
+ ["2022-01-01", "2022-01-02", "2022-01-03"],
186
+ dtype="datetime64[ns]",
187
+ freq=DateOffset(days=1),
188
+ ),
189
+ )
190
+ tm.assert_frame_equal(result, expected)
191
+
192
+ df = DataFrame(
193
+ list(range(10)),
194
+ index=date_range(
195
+ "01-01-2022", periods=10, freq=DateOffset(days=1, hours=2)
196
+ ),
197
+ )
198
+ result = df.loc["2022-01-01":"2022-01-03"]
199
+ expected = DataFrame(
200
+ [0, 1, 2],
201
+ index=DatetimeIndex(
202
+ ["2022-01-01 00:00:00", "2022-01-02 02:00:00", "2022-01-03 04:00:00"],
203
+ dtype="datetime64[ns]",
204
+ freq=DateOffset(days=1, hours=2),
205
+ ),
206
+ )
207
+ tm.assert_frame_equal(result, expected)
208
+
209
+ df = DataFrame(
210
+ list(range(10)),
211
+ index=date_range("01-01-2022", periods=10, freq=DateOffset(minutes=3)),
212
+ )
213
+ result = df.loc["2022-01-01":"2022-01-03"]
214
+ tm.assert_frame_equal(result, df)
215
+
216
+
217
+ class TestGetitemCallable:
218
+ def test_getitem_callable(self, float_frame):
219
+ # GH#12533
220
+ result = float_frame[lambda x: "A"]
221
+ expected = float_frame.loc[:, "A"]
222
+ tm.assert_series_equal(result, expected)
223
+
224
+ result = float_frame[lambda x: ["A", "B"]]
225
+ expected = float_frame.loc[:, ["A", "B"]]
226
+ tm.assert_frame_equal(result, float_frame.loc[:, ["A", "B"]])
227
+
228
+ df = float_frame[:3]
229
+ result = df[lambda x: [True, False, True]]
230
+ expected = float_frame.iloc[[0, 2], :]
231
+ tm.assert_frame_equal(result, expected)
232
+
233
+ def test_loc_multiindex_columns_one_level(self):
234
+ # GH#29749
235
+ df = DataFrame([[1, 2]], columns=[["a", "b"]])
236
+ expected = DataFrame([1], columns=[["a"]])
237
+
238
+ result = df["a"]
239
+ tm.assert_frame_equal(result, expected)
240
+
241
+ result = df.loc[:, "a"]
242
+ tm.assert_frame_equal(result, expected)
243
+
244
+
245
+ class TestGetitemBooleanMask:
246
+ def test_getitem_bool_mask_categorical_index(self):
247
+ df3 = DataFrame(
248
+ {
249
+ "A": np.arange(6, dtype="int64"),
250
+ },
251
+ index=CategoricalIndex(
252
+ [1, 1, 2, 1, 3, 2],
253
+ dtype=CategoricalDtype([3, 2, 1], ordered=True),
254
+ name="B",
255
+ ),
256
+ )
257
+ df4 = DataFrame(
258
+ {
259
+ "A": np.arange(6, dtype="int64"),
260
+ },
261
+ index=CategoricalIndex(
262
+ [1, 1, 2, 1, 3, 2],
263
+ dtype=CategoricalDtype([3, 2, 1], ordered=False),
264
+ name="B",
265
+ ),
266
+ )
267
+
268
+ result = df3[df3.index == "a"]
269
+ expected = df3.iloc[[]]
270
+ tm.assert_frame_equal(result, expected)
271
+
272
+ result = df4[df4.index == "a"]
273
+ expected = df4.iloc[[]]
274
+ tm.assert_frame_equal(result, expected)
275
+
276
+ result = df3[df3.index == 1]
277
+ expected = df3.iloc[[0, 1, 3]]
278
+ tm.assert_frame_equal(result, expected)
279
+
280
+ result = df4[df4.index == 1]
281
+ expected = df4.iloc[[0, 1, 3]]
282
+ tm.assert_frame_equal(result, expected)
283
+
284
+ # since we have an ordered categorical
285
+
286
+ # CategoricalIndex([1, 1, 2, 1, 3, 2],
287
+ # categories=[3, 2, 1],
288
+ # ordered=True,
289
+ # name='B')
290
+ result = df3[df3.index < 2]
291
+ expected = df3.iloc[[4]]
292
+ tm.assert_frame_equal(result, expected)
293
+
294
+ result = df3[df3.index > 1]
295
+ expected = df3.iloc[[]]
296
+ tm.assert_frame_equal(result, expected)
297
+
298
+ # unordered
299
+ # cannot be compared
300
+
301
+ # CategoricalIndex([1, 1, 2, 1, 3, 2],
302
+ # categories=[3, 2, 1],
303
+ # ordered=False,
304
+ # name='B')
305
+ msg = "Unordered Categoricals can only compare equality or not"
306
+ with pytest.raises(TypeError, match=msg):
307
+ df4[df4.index < 2]
308
+ with pytest.raises(TypeError, match=msg):
309
+ df4[df4.index > 1]
310
+
311
+ @pytest.mark.parametrize(
312
+ "data1,data2,expected_data",
313
+ (
314
+ (
315
+ [[1, 2], [3, 4]],
316
+ [[0.5, 6], [7, 8]],
317
+ [[np.nan, 3.0], [np.nan, 4.0], [np.nan, 7.0], [6.0, 8.0]],
318
+ ),
319
+ (
320
+ [[1, 2], [3, 4]],
321
+ [[5, 6], [7, 8]],
322
+ [[np.nan, 3.0], [np.nan, 4.0], [5, 7], [6, 8]],
323
+ ),
324
+ ),
325
+ )
326
+ def test_getitem_bool_mask_duplicate_columns_mixed_dtypes(
327
+ self,
328
+ data1,
329
+ data2,
330
+ expected_data,
331
+ ):
332
+ # GH#31954
333
+
334
+ df1 = DataFrame(np.array(data1))
335
+ df2 = DataFrame(np.array(data2))
336
+ df = concat([df1, df2], axis=1)
337
+
338
+ result = df[df > 2]
339
+
340
+ exdict = {i: np.array(col) for i, col in enumerate(expected_data)}
341
+ expected = DataFrame(exdict).rename(columns={2: 0, 3: 1})
342
+ tm.assert_frame_equal(result, expected)
343
+
344
+ @pytest.fixture
345
+ def df_dup_cols(self):
346
+ dups = ["A", "A", "C", "D"]
347
+ df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64")
348
+ return df
349
+
350
+ def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self, df_dup_cols):
351
+ # `df.A > 6` is a DataFrame with a different shape from df
352
+
353
+ # boolean with the duplicate raises
354
+ df = df_dup_cols
355
+ msg = "cannot reindex on an axis with duplicate labels"
356
+ with pytest.raises(ValueError, match=msg):
357
+ df[df.A > 6]
358
+
359
+ def test_getitem_boolean_series_with_duplicate_columns(self, df_dup_cols):
360
+ # boolean indexing
361
+ # GH#4879
362
+ df = DataFrame(
363
+ np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64"
364
+ )
365
+ expected = df[df.C > 6]
366
+ expected.columns = df_dup_cols.columns
367
+
368
+ df = df_dup_cols
369
+ result = df[df.C > 6]
370
+
371
+ tm.assert_frame_equal(result, expected)
372
+
373
+ def test_getitem_boolean_frame_with_duplicate_columns(self, df_dup_cols):
374
+ # where
375
+ df = DataFrame(
376
+ np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64"
377
+ )
378
+ # `df > 6` is a DataFrame with the same shape+alignment as df
379
+ expected = df[df > 6]
380
+ expected.columns = df_dup_cols.columns
381
+
382
+ df = df_dup_cols
383
+ result = df[df > 6]
384
+
385
+ tm.assert_frame_equal(result, expected)
386
+
387
+ def test_getitem_empty_frame_with_boolean(self):
388
+ # Test for issue GH#11859
389
+
390
+ df = DataFrame()
391
+ df2 = df[df > 0]
392
+ tm.assert_frame_equal(df, df2)
393
+
394
+ def test_getitem_returns_view_when_column_is_unique_in_df(
395
+ self, using_copy_on_write, warn_copy_on_write
396
+ ):
397
+ # GH#45316
398
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
399
+ df_orig = df.copy()
400
+ view = df["b"]
401
+ with tm.assert_cow_warning(warn_copy_on_write):
402
+ view.loc[:] = 100
403
+ if using_copy_on_write:
404
+ expected = df_orig
405
+ else:
406
+ expected = DataFrame([[1, 2, 100], [4, 5, 100]], columns=["a", "a", "b"])
407
+ tm.assert_frame_equal(df, expected)
408
+
409
+ def test_getitem_frozenset_unique_in_column(self):
410
+ # GH#41062
411
+ df = DataFrame([[1, 2, 3, 4]], columns=[frozenset(["KEY"]), "B", "C", "C"])
412
+ result = df[frozenset(["KEY"])]
413
+ expected = Series([1], name=frozenset(["KEY"]))
414
+ tm.assert_series_equal(result, expected)
415
+
416
+
417
+ class TestGetitemSlice:
418
+ def test_getitem_slice_float64(self, frame_or_series):
419
+ values = np.arange(10.0, 50.0, 2)
420
+ index = Index(values)
421
+
422
+ start, end = values[[5, 15]]
423
+
424
+ data = np.random.default_rng(2).standard_normal((20, 3))
425
+ if frame_or_series is not DataFrame:
426
+ data = data[:, 0]
427
+
428
+ obj = frame_or_series(data, index=index)
429
+
430
+ result = obj[start:end]
431
+ expected = obj.iloc[5:16]
432
+ tm.assert_equal(result, expected)
433
+
434
+ result = obj.loc[start:end]
435
+ tm.assert_equal(result, expected)
436
+
437
+ def test_getitem_datetime_slice(self):
438
+ # GH#43223
439
+ df = DataFrame(
440
+ {"a": 0},
441
+ index=DatetimeIndex(
442
+ [
443
+ "11.01.2011 22:00",
444
+ "11.01.2011 23:00",
445
+ "12.01.2011 00:00",
446
+ "2011-01-13 00:00",
447
+ ]
448
+ ),
449
+ )
450
+ with pytest.raises(
451
+ KeyError, match="Value based partial slicing on non-monotonic"
452
+ ):
453
+ df["2011-01-01":"2011-11-01"]
454
+
455
+ def test_getitem_slice_same_dim_only_one_axis(self):
456
+ # GH#54622
457
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 8)))
458
+ result = df.iloc[(slice(None, None, 2),)]
459
+ assert result.shape == (5, 8)
460
+ expected = df.iloc[slice(None, None, 2), slice(None)]
461
+ tm.assert_frame_equal(result, expected)
462
+
463
+
464
+ class TestGetitemDeprecatedIndexers:
465
+ @pytest.mark.parametrize("key", [{"a", "b"}, {"a": "a"}])
466
+ def test_getitem_dict_and_set_deprecated(self, key):
467
+ # GH#42825 enforced in 2.0
468
+ df = DataFrame(
469
+ [[1, 2], [3, 4]], columns=MultiIndex.from_tuples([("a", 1), ("b", 2)])
470
+ )
471
+ with pytest.raises(TypeError, match="as an indexer is not supported"):
472
+ df[key]