diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index fa9c424351b00..3ac3852f17074 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -239,6 +239,7 @@ Indexing - Bug in updating values of :class:`pandas.Series` using boolean index, created by using :meth:`pandas.DataFrame.pop` (:issue:`42530`) - Bug in :meth:`Index.get_indexer_non_unique` when index contains multiple ``np.nan`` (:issue:`35392`) - Bug in :meth:`DataFrame.query` did not handle the degree sign in a backticked column name, such as \`Temp(°C)\`, used in an expression to query a dataframe (:issue:`42826`) +- Bug in :meth:`DataFrame.drop` where the error message did not show missing labels with commas when raising ``KeyError`` (:issue:`42881`) - Missing diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 87c50e94deb34..bf03835611aa9 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -6247,7 +6247,7 @@ def drop(self, labels, errors: str_t = "raise") -> Index: mask = indexer == -1 if mask.any(): if errors != "ignore": - raise KeyError(f"{labels[mask]} not found in axis") + raise KeyError(f"{list(labels[mask])} not found in axis") indexer = indexer[~mask] return self.delete(indexer) diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index fa658d87c3ca0..1e2ce38a2fefd 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -130,6 +130,10 @@ def test_drop(self): with pytest.raises(KeyError, match=r"\['C'\] not found in axis"): simple.drop(["A", "C"], axis=1) + # GH 42881 + with pytest.raises(KeyError, match=r"\['C', 'D', 'F'\] not found in axis"): + simple.drop(["C", "D", "F"], axis=1) + # errors = 'ignore' tm.assert_frame_equal(simple.drop(5, errors="ignore"), simple) tm.assert_frame_equal(