diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index aff30d113438e..8e506cd9b8cbe 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -35,6 +35,7 @@ Other enhancements - Let :meth:`DataFrame.to_feather` accept a non-default :class:`Index` and non-string column names (:issue:`51787`) - :class:`api.extensions.ExtensionArray` now has a :meth:`~api.extensions.ExtensionArray.map` method (:issue:`51809`) - Improve error message when having incompatible columns using :meth:`DataFrame.merge` (:issue:`51861`) +- Improved error message when creating a DataFrame with empty data (0 rows), no index and an incorrect number of columns. (:issue:`52084`) .. --------------------------------------------------------------------------- .. _whatsnew_210.notable_bug_fixes: diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index b114b8a1aa7aa..e660abafcd567 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -382,7 +382,7 @@ def _check_values_indices_shape_match( if values.shape[1] != len(columns) or values.shape[0] != len(index): # Could let this raise in Block constructor, but we get a more # helpful exception message this way. - if values.shape[0] == 0: + if values.shape[0] == 0 < len(index): raise ValueError("Empty data passed with indices specified.") passed = values.shape diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index db7e97d672b4d..cb61a68200411 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -656,7 +656,7 @@ def test_constructor_error_msgs(self): msg = "Empty data passed with indices specified." # passing an empty array with columns specified. with pytest.raises(ValueError, match=msg): - DataFrame(np.empty(0), columns=list("abc")) + DataFrame(np.empty(0), index=[1]) msg = "Mixing dicts with non-Series may lead to ambiguous ordering." # mix dict and array, wrong size @@ -2635,7 +2635,7 @@ def test_from_dict_with_missing_copy_false(self): def test_construction_empty_array_multi_column_raises(self): # GH#46822 - msg = "Empty data passed with indices specified." + msg = r"Shape of passed values is \(0, 1\), indices imply \(0, 2\)" with pytest.raises(ValueError, match=msg): DataFrame(data=np.array([]), columns=["a", "b"])