diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 55bfb044fb31d..d01aac8780531 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -776,7 +776,7 @@ Conversion Strings ^^^^^^^ - Bug in :meth:`str.startswith` and :meth:`str.endswith` when using other series as parameter _pat_. Now raises ``TypeError`` (:issue:`3485`) -- +- Bug in :meth:`DataFrame.from_records` raises a ``KeyError`` if passed a string field label and an empty iterable (:issue:`47285`) Interval ^^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 4376c784bc847..b3f44bd10e158 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2291,6 +2291,16 @@ def maybe_reorder( arr_columns = ensure_index(arr_columns) if columns is None: columns = arr_columns + + if len(arrays) == 0: + if index is not None: + if isinstance(index, str) or not hasattr(index, "__iter__"): + if index not in columns: + # error: Incompatible types in assignment + # type "List[Any]"; expected "Optional[Index]" + result_index = [index] # type: ignore[assignment] + index = None + else: arrays, arr_columns, result_index = maybe_reorder( arrays, arr_columns, columns, index diff --git a/pandas/tests/io/formats/test_info.py b/pandas/tests/io/formats/test_info.py index 54b5e699cd034..6e53b6999fe47 100644 --- a/pandas/tests/io/formats/test_info.py +++ b/pandas/tests/io/formats/test_info.py @@ -491,3 +491,22 @@ def test_info_int_columns(): """ ) assert result == expected + + +def test_info_from_rec(): + # GH47285 + df = DataFrame.from_records([], index="foo") + buf = StringIO() + df.info(buf=buf) + + +def test_info_from_rec_with_itr(): + # GH47285 + itr = [ + {"col_1": 3, "col_2": "a"}, + {"col_1": 2, "col_2": "b"}, + {"col_1": 1, "col_2": "c"}, + {"col_1": 0, "col_2": "d"}, + ] + with pytest.raises(KeyError, match="^'col_14'$"): + DataFrame.from_records(itr, index="col_14")