From 42a105aca1f5c017c973b3a0fa6c9f4a0d039491 Mon Sep 17 00:00:00 2001 From: Simon Hawkins Date: Fri, 5 Jun 2020 11:11:54 +0100 Subject: [PATCH] BUG: fix Series.where(cond) when cond is empty --- doc/source/whatsnew/v1.1.0.rst | 1 + pandas/core/generic.py | 19 ++++++++++--------- pandas/tests/series/indexing/test_where.py | 7 +++++++ 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index b4e29291bb12d..be4f6a3a3098f 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1003,6 +1003,7 @@ Reshaping - Bug in :func:`cut` raised an error when non-unique labels (:issue:`33141`) - Ensure only named functions can be used in :func:`eval()` (:issue:`32460`) - Fixed bug in :func:`melt` where melting MultiIndex columns with ``col_level`` > 0 would raise a ``KeyError`` on ``id_vars`` (:issue:`34129`) +- Bug in :meth:`Series.where` with an empty Series and empty ``cond`` having non-bool dtype (:issue:`34592`) Sparse ^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 197696f8ed4fe..b642ed436444c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8826,16 +8826,17 @@ def _where( msg = "Boolean array expected for the condition, not {dtype}" - if not isinstance(cond, ABCDataFrame): - # This is a single-dimensional object. - if not is_bool_dtype(cond): - raise ValueError(msg.format(dtype=cond.dtype)) - elif not cond.empty: - for dt in cond.dtypes: - if not is_bool_dtype(dt): - raise ValueError(msg.format(dtype=dt)) + if not cond.empty: + if not isinstance(cond, ABCDataFrame): + # This is a single-dimensional object. + if not is_bool_dtype(cond): + raise ValueError(msg.format(dtype=cond.dtype)) + else: + for dt in cond.dtypes: + if not is_bool_dtype(dt): + raise ValueError(msg.format(dtype=dt)) else: - # GH#21947 we have an empty DataFrame, could be object-dtype + # GH#21947 we have an empty DataFrame/Series, could be object-dtype cond = cond.astype(bool) cond = -cond if inplace else cond diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index 6765d9f9d8266..8daea84492871 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -443,3 +443,10 @@ def test_where_sparse(): result = ser.where(ser >= 2, 0) expected = pd.Series(pd.arrays.SparseArray([0, 2])) tm.assert_series_equal(result, expected) + + +def test_where_empty_series_and_empty_cond_having_non_bool_dtypes(): + # https://github.com/pandas-dev/pandas/issues/34592 + ser = Series([], dtype=float) + result = ser.where([]) + tm.assert_series_equal(result, ser)