Skip to content

Commit e764efa

Browse files
committed
BUG: Fix cast_pointwise_result with all-NA values
1 parent e503c13 commit e764efa

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -941,6 +941,7 @@ Numeric
941941

942942
Conversion
943943
^^^^^^^^^^
944+
- Bug in :meth:`BaseMaskedArray._cast_pointwise_result` with all-NA values results returned ``object`` dtype instead of preserving the original dtype (:issue:`62344`)
944945
- Bug in :meth:`DataFrame.astype` not casting ``values`` for Arrow-based dictionary dtype correctly (:issue:`58479`)
945946
- Bug in :meth:`DataFrame.update` bool dtype being converted to object (:issue:`55509`)
946947
- Bug in :meth:`Series.astype` might modify read-only array inplace when casting to a string dtype (:issue:`57212`)

pandas/core/arrays/masked.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,8 @@ def _from_sequence(cls, scalars, *, dtype=None, copy: bool = False) -> Self:
149149
return cls(values, mask)
150150

151151
def _cast_pointwise_result(self, values) -> ArrayLike:
152+
if isna(values).all():
153+
return type(self)._from_sequence(values, dtype=self.dtype)
152154
values = np.asarray(values, dtype=object)
153155
result = lib.maybe_convert_objects(values, convert_to_nullable_dtype=True)
154156
lkind = self.dtype.kind

pandas/tests/extension/test_masked.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,3 +360,21 @@ def check_accumulate(self, ser: pd.Series, op_name: str, skipna: bool):
360360
)
361361
)
362362
tm.assert_series_equal(result, expected)
363+
364+
365+
@pytest.mark.parametrize(
366+
"arr, values",
367+
[
368+
(pd.array([True, False]), [pd.NA, pd.NA]),
369+
(pd.array([1, 2]), [pd.NA, pd.NA]),
370+
],
371+
)
372+
def test_cast_pointwise_result_all_na_respects_dtype(arr, values):
373+
"""
374+
GH#62344
375+
Ensure that _cast_pointwise_result respects the original dtype
376+
even when the result consists entirely of NA values.
377+
"""
378+
result = arr._cast_pointwise_result(values)
379+
assert result.dtype == arr.dtype
380+
assert all(x is pd.NA for x in result)

0 commit comments

Comments
 (0)