Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG GH16983 fix df.where with extension dtypes #24169

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.24.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,7 @@ Indexing
- Bug in :func:`Index.union` and :func:`Index.intersection` where name of the ``Index`` of the result was not computed correctly for certain cases (:issue:`9943`, :issue:`9862`)
- Bug in :class:`Index` slicing with boolean :class:`Index` may raise ``TypeError`` (:issue:`22533`)
- Bug in ``PeriodArray.__setitem__`` when accepting slice and list-like value (:issue:`23978`)
- Bug in :func:`DataFrame.where` where a ``ValueError`` would raise when a column had an extension dtype (:issue:`16983`)

Missing
^^^^^^^
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,8 @@ def func(cond, values, other):
return values

values, other = self._try_coerce_args(values, other)
if isinstance(values, ExtensionArray):
values = values.get_values().reshape(-1, 1) # GH 16983
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just FYI, we want to avoid get_values since that converts the ExtensionArray to an ndarray.


try:
return self._try_coerce_result(expressions.where(
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/frame/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3089,6 +3089,15 @@ def test_where_tz_values(self, tz_naive_fixture):
result = df1.where(mask, df2)
assert_frame_equal(exp, result)

def test_where_extension_dtypes_with_na(self):
from pandas.core.sparse.api import SparseDataFrame
sdf = DataFrame(SparseDataFrame([1, None]))
cdf = DataFrame([1, None]).astype('category')
df = DataFrame([1, None])

assert_frame_equal(df.where(df.isna()), sdf.where(sdf.isna()))
assert_frame_equal(df.where(df.isna()), cdf.where(cdf.isna()))

def test_mask(self):
df = DataFrame(np.random.randn(5, 3))
cond = df > 0
Expand Down