Skip to content

BUG: dataframe construction with dict of recarrays should raise #49405

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
-

.. ---------------------------------------------------------------------------
Expand Down
7 changes: 7 additions & 0 deletions pandas/core/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down