diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index a0076118a28a7..01a0c35117ea3 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -160,7 +160,7 @@ For situations where you need an ``ndarray`` of ``Interval`` objects, use :meth:`numpy.asarray` or ``idx.astype(object)``. .. ipython:: python - + np.asarray(idx) idx.values.astype(object) @@ -487,6 +487,7 @@ Reshaping - Bug in :func:`pandas.concat` when joining resampled DataFrames with timezone aware index (:issue:`13783`) - Bug in :meth:`Series.combine_first` with ``datetime64[ns, tz]`` dtype which would return tz-naive result (:issue:`21469`) - Bug in :meth:`Series.where` and :meth:`DataFrame.where` with ``datetime64[ns, tz]`` dtype (:issue:`21546`) +- Bug in :meth:`Series.mask` and :meth:`DataFrame.mask` with ``list`` conditionals (:issue:`21891`) - - diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7305da4f56506..b682f5e65f876 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7941,6 +7941,10 @@ def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None, inplace = validate_bool_kwarg(inplace, 'inplace') cond = com._apply_if_callable(cond, self) + # see gh-21891 + if not hasattr(cond, "__invert__"): + cond = np.array(cond) + return self.where(~cond, other=other, inplace=inplace, axis=axis, level=level, try_cast=try_cast, errors=errors) diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 9ca2b7e3c8a6a..2eed6b47df9e3 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -2966,6 +2966,13 @@ def test_mask(self): assert_frame_equal(rs, df.mask(df <= 0, other)) assert_frame_equal(rs, df.mask(~cond, other)) + # see gh-21891 + df = DataFrame([1, 2]) + res = df.mask([[True], [False]]) + + exp = DataFrame([np.nan, 2]) + tm.assert_frame_equal(res, exp) + def test_mask_inplace(self): # GH8801 df = DataFrame(np.random.randn(5, 3)) diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py index bd54d5f57d12d..e2a9b3586648d 100644 --- a/pandas/tests/series/indexing/test_boolean.py +++ b/pandas/tests/series/indexing/test_boolean.py @@ -617,6 +617,13 @@ def test_mask(): expected = Series([1, 2, np.nan, np.nan]) assert_series_equal(result, expected) + # see gh-21891 + s = Series([1, 2]) + res = s.mask([True, False]) + + exp = Series([np.nan, 2]) + tm.assert_series_equal(res, exp) + def test_mask_inplace(): s = Series(np.random.randn(5))