zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
from collections import abc
import email
from email.parser import Parser
 
import numpy as np
import pytest
 
from pandas import (
    CategoricalDtype,
    DataFrame,
    MultiIndex,
    Series,
    Timestamp,
    date_range,
)
import pandas._testing as tm
 
 
class TestDataFrameToRecords:
    def test_to_records_timeseries(self):
        index = date_range("1/1/2000", periods=10)
        df = DataFrame(np.random.randn(10, 3), index=index, columns=["a", "b", "c"])
 
        result = df.to_records()
        assert result["index"].dtype == "M8[ns]"
 
        result = df.to_records(index=False)
 
    def test_to_records_dt64(self):
        df = DataFrame(
            [["one", "two", "three"], ["four", "five", "six"]],
            index=date_range("2012-01-01", "2012-01-02"),
        )
 
        expected = df.index.values[0]
        result = df.to_records()["index"][0]
        assert expected == result
 
    def test_to_records_dt64tz_column(self):
        # GH#32535 dont less tz in to_records
        df = DataFrame({"A": date_range("2012-01-01", "2012-01-02", tz="US/Eastern")})
 
        result = df.to_records()
 
        assert result.dtype["A"] == object
        val = result[0][1]
        assert isinstance(val, Timestamp)
        assert val == df.loc[0, "A"]
 
    def test_to_records_with_multindex(self):
        # GH#3189
        index = [
            ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
            ["one", "two", "one", "two", "one", "two", "one", "two"],
        ]
        data = np.zeros((8, 4))
        df = DataFrame(data, index=index)
        r = df.to_records(index=True)["level_0"]
        assert "bar" in r
        assert "one" not in r
 
    def test_to_records_with_Mapping_type(self):
        abc.Mapping.register(email.message.Message)
 
        headers = Parser().parsestr(
            "From: <user@example.com>\n"
            "To: <someone_else@example.com>\n"
            "Subject: Test message\n"
            "\n"
            "Body would go here\n"
        )
 
        frame = DataFrame.from_records([headers])
        all(x in frame for x in ["Type", "Subject", "From"])
 
    def test_to_records_floats(self):
        df = DataFrame(np.random.rand(10, 10))
        df.to_records()
 
    def test_to_records_index_name(self):
        df = DataFrame(np.random.randn(3, 3))
        df.index.name = "X"
        rs = df.to_records()
        assert "X" in rs.dtype.fields
 
        df = DataFrame(np.random.randn(3, 3))
        rs = df.to_records()
        assert "index" in rs.dtype.fields
 
        df.index = MultiIndex.from_tuples([("a", "x"), ("a", "y"), ("b", "z")])
        df.index.names = ["A", None]
        result = df.to_records()
        expected = np.rec.fromarrays(
            [np.array(["a", "a", "b"]), np.array(["x", "y", "z"])]
            + [np.asarray(df.iloc[:, i]) for i in range(3)],
            dtype={
                "names": ["A", "level_1", "0", "1", "2"],
                "formats": [
                    "O",
                    "O",
                    f"{tm.ENDIAN}f8",
                    f"{tm.ENDIAN}f8",
                    f"{tm.ENDIAN}f8",
                ],
            },
        )
        tm.assert_numpy_array_equal(result, expected)
 
    def test_to_records_with_unicode_index(self):
        # GH#13172
        # unicode_literals conflict with to_records
        result = DataFrame([{"a": "x", "b": "y"}]).set_index("a").to_records()
        expected = np.rec.array([("x", "y")], dtype=[("a", "O"), ("b", "O")])
        tm.assert_almost_equal(result, expected)
 
    def test_to_records_index_dtype(self):
        # GH 47263: consistent data types for Index and MultiIndex
        df = DataFrame(
            {
                1: date_range("2022-01-01", periods=2),
                2: date_range("2022-01-01", periods=2),
                3: date_range("2022-01-01", periods=2),
            }
        )
 
        expected = np.rec.array(
            [
                ("2022-01-01", "2022-01-01", "2022-01-01"),
                ("2022-01-02", "2022-01-02", "2022-01-02"),
            ],
            dtype=[
                ("1", f"{tm.ENDIAN}M8[ns]"),
                ("2", f"{tm.ENDIAN}M8[ns]"),
                ("3", f"{tm.ENDIAN}M8[ns]"),
            ],
        )
 
        result = df.to_records(index=False)
        tm.assert_almost_equal(result, expected)
 
        result = df.set_index(1).to_records(index=True)
        tm.assert_almost_equal(result, expected)
 
        result = df.set_index([1, 2]).to_records(index=True)
        tm.assert_almost_equal(result, expected)
 
    def test_to_records_with_unicode_column_names(self):
        # xref issue: https://github.com/numpy/numpy/issues/2407
        # Issue GH#11879. to_records used to raise an exception when used
        # with column names containing non-ascii characters in Python 2
        result = DataFrame(data={"accented_name_é": [1.0]}).to_records()
 
        # Note that numpy allows for unicode field names but dtypes need
        # to be specified using dictionary instead of list of tuples.
        expected = np.rec.array(
            [(0, 1.0)],
            dtype={"names": ["index", "accented_name_é"], "formats": ["=i8", "=f8"]},
        )
        tm.assert_almost_equal(result, expected)
 
    def test_to_records_with_categorical(self):
        # GH#8626
 
        # dict creation
        df = DataFrame({"A": list("abc")}, dtype="category")
        expected = Series(list("abc"), dtype="category", name="A")
        tm.assert_series_equal(df["A"], expected)
 
        # list-like creation
        df = DataFrame(list("abc"), dtype="category")
        expected = Series(list("abc"), dtype="category", name=0)
        tm.assert_series_equal(df[0], expected)
 
        # to record array
        # this coerces
        result = df.to_records()
        expected = np.rec.array(
            [(0, "a"), (1, "b"), (2, "c")], dtype=[("index", "=i8"), ("0", "O")]
        )
        tm.assert_almost_equal(result, expected)
 
    @pytest.mark.parametrize(
        "kwargs,expected",
        [
            # No dtypes --> default to array dtypes.
            (
                {},
                np.rec.array(
                    [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}i8"),
                        ("A", f"{tm.ENDIAN}i8"),
                        ("B", f"{tm.ENDIAN}f8"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Should have no effect in this case.
            (
                {"index": True},
                np.rec.array(
                    [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}i8"),
                        ("A", f"{tm.ENDIAN}i8"),
                        ("B", f"{tm.ENDIAN}f8"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Column dtype applied across the board. Index unaffected.
            (
                {"column_dtypes": f"{tm.ENDIAN}U4"},
                np.rec.array(
                    [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}i8"),
                        ("A", f"{tm.ENDIAN}U4"),
                        ("B", f"{tm.ENDIAN}U4"),
                        ("C", f"{tm.ENDIAN}U4"),
                    ],
                ),
            ),
            # Index dtype applied across the board. Columns unaffected.
            (
                {"index_dtypes": f"{tm.ENDIAN}U1"},
                np.rec.array(
                    [("0", 1, 0.2, "a"), ("1", 2, 1.5, "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}U1"),
                        ("A", f"{tm.ENDIAN}i8"),
                        ("B", f"{tm.ENDIAN}f8"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Pass in a type instance.
            (
                {"column_dtypes": str},
                np.rec.array(
                    [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}i8"),
                        ("A", f"{tm.ENDIAN}U"),
                        ("B", f"{tm.ENDIAN}U"),
                        ("C", f"{tm.ENDIAN}U"),
                    ],
                ),
            ),
            # Pass in a dtype instance.
            (
                {"column_dtypes": np.dtype("unicode")},
                np.rec.array(
                    [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}i8"),
                        ("A", f"{tm.ENDIAN}U"),
                        ("B", f"{tm.ENDIAN}U"),
                        ("C", f"{tm.ENDIAN}U"),
                    ],
                ),
            ),
            # Pass in a dictionary (name-only).
            (
                {
                    "column_dtypes": {
                        "A": np.int8,
                        "B": np.float32,
                        "C": f"{tm.ENDIAN}U2",
                    }
                },
                np.rec.array(
                    [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}i8"),
                        ("A", "i1"),
                        ("B", f"{tm.ENDIAN}f4"),
                        ("C", f"{tm.ENDIAN}U2"),
                    ],
                ),
            ),
            # Pass in a dictionary (indices-only).
            (
                {"index_dtypes": {0: "int16"}},
                np.rec.array(
                    [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],
                    dtype=[
                        ("index", "i2"),
                        ("A", f"{tm.ENDIAN}i8"),
                        ("B", f"{tm.ENDIAN}f8"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Ignore index mappings if index is not True.
            (
                {"index": False, "index_dtypes": f"{tm.ENDIAN}U2"},
                np.rec.array(
                    [(1, 0.2, "a"), (2, 1.5, "bc")],
                    dtype=[
                        ("A", f"{tm.ENDIAN}i8"),
                        ("B", f"{tm.ENDIAN}f8"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Non-existent names / indices in mapping should not error.
            (
                {"index_dtypes": {0: "int16", "not-there": "float32"}},
                np.rec.array(
                    [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],
                    dtype=[
                        ("index", "i2"),
                        ("A", f"{tm.ENDIAN}i8"),
                        ("B", f"{tm.ENDIAN}f8"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Names / indices not in mapping default to array dtype.
            (
                {"column_dtypes": {"A": np.int8, "B": np.float32}},
                np.rec.array(
                    [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}i8"),
                        ("A", "i1"),
                        ("B", f"{tm.ENDIAN}f4"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Names / indices not in dtype mapping default to array dtype.
            (
                {"column_dtypes": {"A": np.dtype("int8"), "B": np.dtype("float32")}},
                np.rec.array(
                    [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}i8"),
                        ("A", "i1"),
                        ("B", f"{tm.ENDIAN}f4"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Mixture of everything.
            (
                {
                    "column_dtypes": {"A": np.int8, "B": np.float32},
                    "index_dtypes": f"{tm.ENDIAN}U2",
                },
                np.rec.array(
                    [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
                    dtype=[
                        ("index", f"{tm.ENDIAN}U2"),
                        ("A", "i1"),
                        ("B", f"{tm.ENDIAN}f4"),
                        ("C", "O"),
                    ],
                ),
            ),
            # Invalid dype values.
            (
                {"index": False, "column_dtypes": []},
                (ValueError, "Invalid dtype \\[\\] specified for column A"),
            ),
            (
                {"index": False, "column_dtypes": {"A": "int32", "B": 5}},
                (ValueError, "Invalid dtype 5 specified for column B"),
            ),
            # Numpy can't handle EA types, so check error is raised
            (
                {
                    "index": False,
                    "column_dtypes": {"A": "int32", "B": CategoricalDtype(["a", "b"])},
                },
                (ValueError, "Invalid dtype category specified for column B"),
            ),
            # Check that bad types raise
            (
                {"index": False, "column_dtypes": {"A": "int32", "B": "foo"}},
                (TypeError, "data type [\"']foo[\"'] not understood"),
            ),
        ],
    )
    def test_to_records_dtype(self, kwargs, expected):
        # see GH#18146
        df = DataFrame({"A": [1, 2], "B": [0.2, 1.5], "C": ["a", "bc"]})
 
        if not isinstance(expected, np.recarray):
            with pytest.raises(expected[0], match=expected[1]):
                df.to_records(**kwargs)
        else:
            result = df.to_records(**kwargs)
            tm.assert_almost_equal(result, expected)
 
    @pytest.mark.parametrize(
        "df,kwargs,expected",
        [
            # MultiIndex in the index.
            (
                DataFrame(
                    [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("abc")
                ).set_index(["a", "b"]),
                {"column_dtypes": "float64", "index_dtypes": {0: "int32", 1: "int8"}},
                np.rec.array(
                    [(1, 2, 3.0), (4, 5, 6.0), (7, 8, 9.0)],
                    dtype=[
                        ("a", f"{tm.ENDIAN}i4"),
                        ("b", "i1"),
                        ("c", f"{tm.ENDIAN}f8"),
                    ],
                ),
            ),
            # MultiIndex in the columns.
            (
                DataFrame(
                    [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
                    columns=MultiIndex.from_tuples(
                        [("a", "d"), ("b", "e"), ("c", "f")]
                    ),
                ),
                {
                    "column_dtypes": {0: f"{tm.ENDIAN}U1", 2: "float32"},
                    "index_dtypes": "float32",
                },
                np.rec.array(
                    [(0.0, "1", 2, 3.0), (1.0, "4", 5, 6.0), (2.0, "7", 8, 9.0)],
                    dtype=[
                        ("index", f"{tm.ENDIAN}f4"),
                        ("('a', 'd')", f"{tm.ENDIAN}U1"),
                        ("('b', 'e')", f"{tm.ENDIAN}i8"),
                        ("('c', 'f')", f"{tm.ENDIAN}f4"),
                    ],
                ),
            ),
            # MultiIndex in both the columns and index.
            (
                DataFrame(
                    [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
                    columns=MultiIndex.from_tuples(
                        [("a", "d"), ("b", "e"), ("c", "f")], names=list("ab")
                    ),
                    index=MultiIndex.from_tuples(
                        [("d", -4), ("d", -5), ("f", -6)], names=list("cd")
                    ),
                ),
                {
                    "column_dtypes": "float64",
                    "index_dtypes": {0: f"{tm.ENDIAN}U2", 1: "int8"},
                },
                np.rec.array(
                    [
                        ("d", -4, 1.0, 2.0, 3.0),
                        ("d", -5, 4.0, 5.0, 6.0),
                        ("f", -6, 7, 8, 9.0),
                    ],
                    dtype=[
                        ("c", f"{tm.ENDIAN}U2"),
                        ("d", "i1"),
                        ("('a', 'd')", f"{tm.ENDIAN}f8"),
                        ("('b', 'e')", f"{tm.ENDIAN}f8"),
                        ("('c', 'f')", f"{tm.ENDIAN}f8"),
                    ],
                ),
            ),
        ],
    )
    def test_to_records_dtype_mi(self, df, kwargs, expected):
        # see GH#18146
        result = df.to_records(**kwargs)
        tm.assert_almost_equal(result, expected)
 
    def test_to_records_dict_like(self):
        # see GH#18146
        class DictLike:
            def __init__(self, **kwargs) -> None:
                self.d = kwargs.copy()
 
            def __getitem__(self, key):
                return self.d.__getitem__(key)
 
            def __contains__(self, key) -> bool:
                return key in self.d
 
            def keys(self):
                return self.d.keys()
 
        df = DataFrame({"A": [1, 2], "B": [0.2, 1.5], "C": ["a", "bc"]})
 
        dtype_mappings = {
            "column_dtypes": DictLike(**{"A": np.int8, "B": np.float32}),
            "index_dtypes": f"{tm.ENDIAN}U2",
        }
 
        result = df.to_records(**dtype_mappings)
        expected = np.rec.array(
            [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
            dtype=[
                ("index", f"{tm.ENDIAN}U2"),
                ("A", "i1"),
                ("B", f"{tm.ENDIAN}f4"),
                ("C", "O"),
            ],
        )
        tm.assert_almost_equal(result, expected)
 
    @pytest.mark.parametrize("tz", ["UTC", "GMT", "US/Eastern"])
    def test_to_records_datetimeindex_with_tz(self, tz):
        # GH#13937
        dr = date_range("2016-01-01", periods=10, freq="S", tz=tz)
 
        df = DataFrame({"datetime": dr}, index=dr)
 
        expected = df.to_records()
        result = df.tz_convert("UTC").to_records()
 
        # both converted to UTC, so they are equal
        tm.assert_numpy_array_equal(result, expected)