From ab19909ffae8eaf1cda81c9a177e9ba3b2ee18d8 Mon Sep 17 00:00:00 2001 From: kpvenkat47 Date: Wed, 19 Mar 2025 22:33:41 +0530 Subject: [PATCH] Update from_records to preserve columns on empty input and added test --- pandas/core/frame.py | 2 +- pandas/tests/frame/test_constructors.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8f65277f660f7..7ee8992e1c39d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2231,7 +2231,7 @@ def maybe_reorder( if is_iterator(data): if nrows == 0: - return cls() + return cls(columns=columns) try: first_row = next(data) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 037a2ae294bb2..c4abb0545fcf0 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2779,6 +2779,13 @@ def test_construction_nan_value_timedelta64_dtype(self): ["NaT", "0 days 00:00:00.000000001"], dtype="timedelta64[ns]" ) tm.assert_frame_equal(result, expected) + + def test_from_records_empty_iterator_with_preserve_columns(self): + + rows = [] + df = pd.DataFrame.from_records(iter(rows), columns=["col_1", "Col_2"], nrows=0) + assert list(df.columns) == ["col_1", "Col_2"] + assert len(df) == 0 class TestDataFrameConstructorIndexInference: