diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 7cf88a642f511..f5dd5666b6ca5 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1333,6 +1333,7 @@ Metadata Other ^^^^^ - Bug in :meth:`Series.searchsorted` inconsistent behavior when accepting :class:`DataFrame` as parameter ``value`` (:issue:`49620`) +- Bug in :func:`array` failing to raise on :class:`DataFrame` inputs (:issue:`51167`) - .. ***DO NOT USE THIS SECTION*** diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 5593826218fec..69ba7e0bb0848 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -52,6 +52,7 @@ ) from pandas.core.dtypes.dtypes import PandasDtype from pandas.core.dtypes.generic import ( + ABCDataFrame, ABCExtensionArray, ABCIndex, ABCPandasArray, @@ -308,6 +309,8 @@ def array( if lib.is_scalar(data): msg = f"Cannot pass scalar '{data}' to 'pandas.array'." raise ValueError(msg) + elif isinstance(data, ABCDataFrame): + raise TypeError("Cannot pass DataFrame to 'pandas.array'") if dtype is None and isinstance(data, (ABCSeries, ABCIndex, ExtensionArray)): # Note: we exclude np.ndarray here, will do type inference on it diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index 2288ac408d99e..59e5c6fa2dda3 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -343,6 +343,14 @@ def test_scalar_raises(): pd.array(1) +def test_dataframe_raises(): + # GH#51167 don't accidentally cast to StringArray by doing inference on columns + df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + msg = "Cannot pass DataFrame to 'pandas.array'" + with pytest.raises(TypeError, match=msg): + pd.array(df) + + def test_bounds_check(): # GH21796 with pytest.raises(