diff --git a/doc/source/whatsnew/v1.5.2.rst b/doc/source/whatsnew/v1.5.2.rst index aaf00804262bb..4cf5fcd85884a 100644 --- a/doc/source/whatsnew/v1.5.2.rst +++ b/doc/source/whatsnew/v1.5.2.rst @@ -21,7 +21,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -- +- Bug in :meth:`DataFrame` construction when constructing from a dict where one of the dict values is a numpy recarray should fail, but didn't (:issue:`49388`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 4ceafa6d4462e..d9e61bd8fc921 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -534,6 +534,13 @@ def sanitize_array( if dtype is None: dtype = data.dtype data = lib.item_from_zerodim(data) + elif isinstance(data, np.ndarray) and len(data.dtype): + # GH#13296 we are dealing with a compound dtype, which + # should be treated as 2D + raise ValueError( + "Cannot construct a 1-dim array for a DataFrame from an ndarray with " + f"compound dtype {repr(data.dtype)}." + ) elif isinstance(data, range): # GH#16804 data = range_to_ndarray(data) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 5a83c4997b33c..fe0587009ad48 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -797,6 +797,17 @@ def test_constructor_dict_of_generators(self): expected = DataFrame({"a": [0, 1, 2], "b": [2, 1, 0]}) tm.assert_frame_equal(result, expected) + def test_constructor_dict_of_rec_raises(self): + # GH 49388 + c = np.array([2] * 20, dtype="f8") + rec_arr = np.rec.fromarrays([c], names=["c"]) + msg = ( + "Cannot construct a array for a DataFrame from an ndarray with " + r"compound dtype " + ) + with pytest.raises(ValueError, match=msg): + DataFrame({"a": rec_arr}) + def test_constructor_dict_multiindex(self): d = { ("a", "a"): {("i", "i"): 0, ("i", "j"): 1, ("j", "i"): 2},