diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index cd0714838a3f1..2e188ec5a9af5 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -184,7 +184,7 @@ Groupby/resample/rolling Reshaping ^^^^^^^^^ -- +- Bug in :meth:`DataFrame.drop` when passing empty :class:`DatetimeIndex` or ``list`` (:issue:`27994`) - Sparse diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 1a5b36b07e93c..93bad6fa94277 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3916,6 +3916,9 @@ def drop( for axis, labels in axes.items(): if labels is not None: + # Check for empty Index, GH 27994 + if is_list_like(labels) and not len(labels): + continue obj = obj._drop_axis(labels, axis, level=level, errors=errors) if inplace: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2dbd592fc6787..9022fa9ee69e7 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4720,6 +4720,10 @@ def get_indexer_non_unique(self, target): return pself.get_indexer_non_unique(ptarget) if self.is_all_dates: + # If `target` doesn't consist of dates, `target.asi8` will return + # None, which will raise TypeError. GH 27994 + if not target.is_all_dates: + raise KeyError("{} not found in axis".format(target.to_numpy())) tgt_values = target.asi8 else: tgt_values = target._ndarray_values diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 1ef10ea5857d0..901cdfbe1a032 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -117,6 +117,32 @@ def test_drop(self): df.drop(labels=df[df.b > 0].index, inplace=True) assert_frame_equal(df, expected) + def test_drop_empty_index(self): + # GH 27994 + df = pd.DataFrame( + {"a": [0, 1]}, + index=[pd.Timestamp("2019-01-01"), pd.Timestamp("2019-01-01")], + ) + result_empty_list = df.drop([]) + assert_frame_equal(result_empty_list, df) + + result_empty_array = df.drop(np.array([])) + assert_frame_equal(result_empty_array, df) + + result_empty_index = df.drop(df[:0]) + assert_frame_equal(result_empty_index, df) + + @pytest.mark.parametrize("labels", ["a", ["a"]]) + def test_drop_empty_index_str(self, labels): + # Passing str to DataFrame.drop() for dataframe with DatetimeIndex + # should raise KeyError, GH 27994 + df = pd.DataFrame( + {"a": [0, 1]}, + index=[pd.Timestamp("2019-01-01"), pd.Timestamp("2019-01-01")], + ) + with pytest.raises(KeyError, match="not found in axis"): + df.drop(labels) + def test_drop_multiindex_not_lexsorted(self): # GH 11640