diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 834477f2aa46a..5a05d43ec2d23 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -801,6 +801,7 @@ I/O - Bug in :meth:`.DataFrame.to_json` when ``"index"`` was a value in the :attr:`DataFrame.column` and :attr:`Index.name` was ``None``. Now, this will fail with a ``ValueError`` (:issue:`58925`) - Bug in :meth:`.io.common.is_fsspec_url` not recognizing chained fsspec URLs (:issue:`48978`) - Bug in :meth:`DataFrame._repr_html_` which ignored the ``"display.float_format"`` option (:issue:`59876`) +- Bug in :meth:`DataFrame.from_records` ignoring ``columns`` parameter when ``data`` is an iterator and ``nrows=0``. (:issue:`61140`) - Bug in :meth:`DataFrame.from_records` where ``columns`` parameter with numpy structured array was not reordering and filtering out the columns (:issue:`59717`) - Bug in :meth:`DataFrame.to_dict` raises unnecessary ``UserWarning`` when columns are not unique and ``orient='tight'``. (:issue:`58281`) - Bug in :meth:`DataFrame.to_excel` when writing empty :class:`DataFrame` with :class:`MultiIndex` on both axes (:issue:`57696`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f14cb74f7cddf..be4bfcd987db4 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2234,7 +2234,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..bc57680059a9a 100644 --- a/pandas/tests/frame/constructors/test_from_records.py +++ b/pandas/tests/frame/constructors/test_from_records.py @@ -492,3 +492,10 @@ 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)