Skip to content

Commit b2823a0

Browse files
committed
BUG: Properly handle lists for .mask
Closes pandas-devgh-21891.
1 parent 272bbdc commit b2823a0

File tree

4 files changed

+23
-1
lines changed

4 files changed

+23
-1
lines changed

doc/source/whatsnew/v0.24.0.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ For situations where you need an ``ndarray`` of ``Interval`` objects, use
155155
:meth:`numpy.asarray` or ``idx.astype(object)``.
156156

157157
.. ipython:: python
158-
158+
159159
np.asarray(idx)
160160
idx.values.astype(object)
161161

@@ -482,6 +482,7 @@ Reshaping
482482
- Bug in :func:`pandas.concat` when joining resampled DataFrames with timezone aware index (:issue:`13783`)
483483
- Bug in :meth:`Series.combine_first` with ``datetime64[ns, tz]`` dtype which would return tz-naive result (:issue:`21469`)
484484
- Bug in :meth:`Series.where` and :meth:`DataFrame.where` with ``datetime64[ns, tz]`` dtype (:issue:`21546`)
485+
- Bug in :meth:`Series.mask` and :meth:`DataFrame.mask` with ``list`` conditionals (:issue:`21891`)
485486
-
486487
-
487488

pandas/core/generic.py

+4
Original file line numberDiff line numberDiff line change
@@ -7941,6 +7941,10 @@ def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None,
79417941
inplace = validate_bool_kwarg(inplace, 'inplace')
79427942
cond = com._apply_if_callable(cond, self)
79437943

7944+
# see gh-21891
7945+
if not hasattr(cond, "__invert__"):
7946+
cond = np.array(cond)
7947+
79447948
return self.where(~cond, other=other, inplace=inplace, axis=axis,
79457949
level=level, try_cast=try_cast,
79467950
errors=errors)

pandas/tests/frame/test_indexing.py

+8
Original file line numberDiff line numberDiff line change
@@ -3010,6 +3010,14 @@ def test_mask_callable(self):
30103010
tm.assert_frame_equal(result,
30113011
(df + 2).mask((df + 2) > 8, (df + 2) + 10))
30123012

3013+
def test_mask_list(self):
3014+
# see gh-21891
3015+
df = DataFrame([1, 2])
3016+
res = df.mask([[True], [False]])
3017+
3018+
exp = DataFrame([np.nan, 2])
3019+
tm.assert_frame_equal(res, exp)
3020+
30133021
def test_head_tail(self):
30143022
assert_frame_equal(self.frame.head(), self.frame[:5])
30153023
assert_frame_equal(self.frame.tail(), self.frame[-5:])

pandas/tests/series/indexing/test_boolean.py

+9
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,15 @@ def test_where_dt_tz_values(tz_naive_fixture):
582582
assert_series_equal(exp, result)
583583

584584

585+
def test_where_list():
586+
# see gh-21891
587+
s = Series([1, 2])
588+
res = s.mask([True, False])
589+
590+
exp = Series([np.nan, 2])
591+
tm.assert_series_equal(res, exp)
592+
593+
585594
def test_mask():
586595
# compare with tested results in test_where
587596
s = Series(np.random.randn(5))

0 commit comments

Comments
 (0)