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/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py index 1d4a2c0075e3e..57bd7a3c877ea 100644 --- a/pandas/tests/frame/constructors/test_from_records.py +++ b/pandas/tests/frame/constructors/test_from_records.py @@ -492,3 +492,11 @@ def test_from_records_structured_array(self): expected_result = DataFrame(modified_data) tm.assert_frame_equal(actual_result, expected_result) + + + def test_from_records_empty_iterator_with_preserve_columns(self): + # GH#61140 + rows = [] + result = DataFrame.from_records(iter(rows), columns=["col_1", "Col_2"], nrows=0) + expected = DataFrame([],columns=["col_1", "Col_2"]) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 037a2ae294bb2..18f0d4a864c04 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2779,7 +2779,7 @@ def test_construction_nan_value_timedelta64_dtype(self): ["NaT", "0 days 00:00:00.000000001"], dtype="timedelta64[ns]" ) tm.assert_frame_equal(result, expected) - + class TestDataFrameConstructorIndexInference: def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self):