Skip to content

Commit 0366ddb

Browse files
yuanx749kpvenkat47
andauthored
BUG: Preserve column names in DataFrame.from_records when nrows=0 (#62085)
Co-authored-by: Venkat <[email protected]> Co-authored-by: kpvenkat47 <[email protected]>
1 parent 979e743 commit 0366ddb

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,7 @@ I/O
837837
- 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`)
838838
- Bug in :meth:`.io.common.is_fsspec_url` not recognizing chained fsspec URLs (:issue:`48978`)
839839
- Bug in :meth:`DataFrame._repr_html_` which ignored the ``"display.float_format"`` option (:issue:`59876`)
840+
- Bug in :meth:`DataFrame.from_records` ignoring ``columns`` and ``index`` parameters when ``data`` is an empty iterator and ``nrows=0``. (:issue:`61140`)
840841
- Bug in :meth:`DataFrame.from_records` where ``columns`` parameter with numpy structured array was not reordering and filtering out the columns (:issue:`59717`)
841842
- Bug in :meth:`DataFrame.to_dict` raises unnecessary ``UserWarning`` when columns are not unique and ``orient='tight'``. (:issue:`58281`)
842843
- Bug in :meth:`DataFrame.to_excel` when writing empty :class:`DataFrame` with :class:`MultiIndex` on both axes (:issue:`57696`)

pandas/core/frame.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2234,7 +2234,7 @@ def maybe_reorder(
22342234

22352235
if is_iterator(data):
22362236
if nrows == 0:
2237-
return cls()
2237+
return cls(index=index, columns=columns)
22382238

22392239
try:
22402240
first_row = next(data)

pandas/tests/frame/constructors/test_from_records.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,3 +492,12 @@ def test_from_records_structured_array(self):
492492
expected_result = DataFrame(modified_data)
493493

494494
tm.assert_frame_equal(actual_result, expected_result)
495+
496+
def test_from_records_empty_iterator_with_preserve_columns(self):
497+
# GH#61140
498+
rows = []
499+
result = DataFrame.from_records(
500+
iter(rows), index=[0, 1], columns=["col_1", "Col_2"], nrows=0
501+
)
502+
expected = DataFrame([], index=[0, 1], columns=["col_1", "Col_2"])
503+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)