Skip to content

Commit ab19909

Browse files
committed
Update from_records to preserve columns on empty input and added test
1 parent 882fa9c commit ab19909

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2231,7 +2231,7 @@ def maybe_reorder(
22312231

22322232
if is_iterator(data):
22332233
if nrows == 0:
2234-
return cls()
2234+
return cls(columns=columns)
22352235

22362236
try:
22372237
first_row = next(data)

pandas/tests/frame/test_constructors.py

+7
Original file line numberDiff line numberDiff line change
@@ -2779,6 +2779,13 @@ def test_construction_nan_value_timedelta64_dtype(self):
27792779
["NaT", "0 days 00:00:00.000000001"], dtype="timedelta64[ns]"
27802780
)
27812781
tm.assert_frame_equal(result, expected)
2782+
2783+
def test_from_records_empty_iterator_with_preserve_columns(self):
2784+
2785+
rows = []
2786+
df = pd.DataFrame.from_records(iter(rows), columns=["col_1", "Col_2"], nrows=0)
2787+
assert list(df.columns) == ["col_1", "Col_2"]
2788+
assert len(df) == 0
27822789

27832790

27842791
class TestDataFrameConstructorIndexInference:

0 commit comments

Comments
 (0)