Skip to content

Commit 266b9c0

Browse files
BUG: fix Series.where(cond) when cond is empty (#34595)
1 parent 2c052f7 commit 266b9c0

File tree

3 files changed

+18
-9
lines changed

3 files changed

+18
-9
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,7 @@ Reshaping
10131013
- Ensure only named functions can be used in :func:`eval()` (:issue:`32460`)
10141014
- Bug in :func:`Dataframe.aggregate` and :func:`Series.aggregate` was causing recursive loop in some cases (:issue:`34224`)
10151015
- Fixed bug in :func:`melt` where melting MultiIndex columns with ``col_level`` > 0 would raise a ``KeyError`` on ``id_vars`` (:issue:`34129`)
1016+
- Bug in :meth:`Series.where` with an empty Series and empty ``cond`` having non-bool dtype (:issue:`34592`)
10161017

10171018
Sparse
10181019
^^^^^^

pandas/core/generic.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -8831,16 +8831,17 @@ def _where(
88318831

88328832
msg = "Boolean array expected for the condition, not {dtype}"
88338833

8834-
if not isinstance(cond, ABCDataFrame):
8835-
# This is a single-dimensional object.
8836-
if not is_bool_dtype(cond):
8837-
raise ValueError(msg.format(dtype=cond.dtype))
8838-
elif not cond.empty:
8839-
for dt in cond.dtypes:
8840-
if not is_bool_dtype(dt):
8841-
raise ValueError(msg.format(dtype=dt))
8834+
if not cond.empty:
8835+
if not isinstance(cond, ABCDataFrame):
8836+
# This is a single-dimensional object.
8837+
if not is_bool_dtype(cond):
8838+
raise ValueError(msg.format(dtype=cond.dtype))
8839+
else:
8840+
for dt in cond.dtypes:
8841+
if not is_bool_dtype(dt):
8842+
raise ValueError(msg.format(dtype=dt))
88428843
else:
8843-
# GH#21947 we have an empty DataFrame, could be object-dtype
8844+
# GH#21947 we have an empty DataFrame/Series, could be object-dtype
88448845
cond = cond.astype(bool)
88458846

88468847
cond = -cond if inplace else cond

pandas/tests/series/indexing/test_where.py

+7
Original file line numberDiff line numberDiff line change
@@ -443,3 +443,10 @@ def test_where_sparse():
443443
result = ser.where(ser >= 2, 0)
444444
expected = pd.Series(pd.arrays.SparseArray([0, 2]))
445445
tm.assert_series_equal(result, expected)
446+
447+
448+
def test_where_empty_series_and_empty_cond_having_non_bool_dtypes():
449+
# https://github.com/pandas-dev/pandas/issues/34592
450+
ser = Series([], dtype=float)
451+
result = ser.where([])
452+
tm.assert_series_equal(result, ser)

0 commit comments

Comments
 (0)