From 097b0d252c02a0f48b84c4e09f662e048e2958e9 Mon Sep 17 00:00:00 2001 From: Kenta Murata Date: Thu, 23 May 2024 14:30:43 +0900 Subject: [PATCH] Add test case for creation from records --- pandas/tests/frame/test_constructors.py | 44 +++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 1572c65dec9741..cd09763f1306c2 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -8,6 +8,7 @@ from collections.abc import ( Iterator, Mapping, + Sequence, ) from dataclasses import make_dataclass from datetime import ( @@ -94,6 +95,19 @@ def __len__(self): return self._dict.__len__() +class ListWrapper(Sequence): + _list: list + + def __init__(self, lst: list) -> None: + self._list = lst + + def __getitem__(self, i): + return self._list[i] + + def __len__(self): + return self._list.__len__() + + class TestDataFrameConstructors: def test_constructor_from_ndarray_with_str_dtype(self): # If we don't ravel/reshape around ensure_str_array, we end up @@ -2931,6 +2945,36 @@ def test_from_dict_with_mapping(self): tm.assert_series_equal(df["A"], Series(idx, name="A")) tm.assert_series_equal(df["B"], Series(dr, name="B")) + def test_from_mappiog_list(self): + idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo") + dr = date_range("20130110", periods=3) + data = DataFrame({"A": idx, "B": dr}) + mapping_list = [ + DictWrapper(record) for record in data.to_dict(orient="records") + ] + + # construction + df = DataFrame(mapping_list) + assert df["A"].dtype, "M8[ns, US/Eastern" + assert df["A"].name == "A" + tm.assert_series_equal(df["A"], Series(idx, name="A")) + tm.assert_series_equal(df["B"], Series(dr, name="B")) + + def test_from_mappiog_sequence(self): + idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo") + dr = date_range("20130110", periods=3) + data = DataFrame({"A": idx, "B": dr}) + mapping_list = ListWrapper( + [DictWrapper(record) for record in data.to_dict(orient="records")] + ) + + # construction + df = DataFrame(mapping_list) + assert df["A"].dtype, "M8[ns, US/Eastern" + assert df["A"].name == "A" + tm.assert_series_equal(df["A"], Series(idx, name="A")) + tm.assert_series_equal(df["B"], Series(dr, name="B")) + def test_from_index(self): # from index idx2 = date_range("20130101", periods=3, tz="US/Eastern", name="foo")