Skip to content

Commit 109451d

Browse files
authored
BUG: astype_nansafe with copy=False (#38835)
1 parent bd3f2a4 commit 109451d

File tree

4 files changed

+22
-3
lines changed

4 files changed

+22
-3
lines changed

doc/source/whatsnew/v1.3.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ Sparse
297297
^^^^^^
298298

299299
- Bug in :meth:`DataFrame.sparse.to_coo` raising ``KeyError`` with columns that are a numeric :class:`Index` without a 0 (:issue:`18414`)
300-
-
300+
- Bug in :meth:`SparseArray.astype` with ``copy=False`` producing incorrect results when going from integer dtype to floating dtype (:issue:`34456`)
301301
-
302302

303303
ExtensionArray

pandas/core/dtypes/cast.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1133,11 +1133,11 @@ def astype_nansafe(
11331133
)
11341134
raise ValueError(msg)
11351135

1136-
if copy or is_object_dtype(arr) or is_object_dtype(dtype):
1136+
if copy or is_object_dtype(arr.dtype) or is_object_dtype(dtype):
11371137
# Explicit copy, or required since NumPy can't view from / to object.
11381138
return arr.astype(dtype, copy=True)
11391139

1140-
return arr.view(dtype)
1140+
return arr.astype(dtype, copy=copy)
11411141

11421142

11431143
def soft_convert_objects(

pandas/tests/arrays/sparse/test_array.py

+8
Original file line numberDiff line numberDiff line change
@@ -563,6 +563,14 @@ def test_astype_nan_raises(self):
563563
with pytest.raises(ValueError, match="Cannot convert non-finite"):
564564
arr.astype(int)
565565

566+
def test_astype_copy_false(self):
567+
# GH#34456 bug caused by using .view instead of .astype in astype_nansafe
568+
arr = SparseArray([1, 2, 3])
569+
570+
result = arr.astype(float, copy=False)
571+
expected = SparseArray([1.0, 2.0, 3.0], fill_value=0.0)
572+
tm.assert_sp_array_equal(result, expected)
573+
566574
def test_set_fill_value(self):
567575
arr = SparseArray([1.0, np.nan, 2.0], fill_value=np.nan)
568576
arr.fill_value = 2

pandas/tests/dtypes/test_common.py

+11
Original file line numberDiff line numberDiff line change
@@ -724,6 +724,17 @@ def test_astype_nansafe(val, typ):
724724
astype_nansafe(arr, dtype=typ)
725725

726726

727+
def test_astype_nansafe_copy_false(any_int_dtype):
728+
# GH#34457 use astype, not view
729+
arr = np.array([1, 2, 3], dtype=any_int_dtype)
730+
731+
dtype = np.dtype("float64")
732+
result = astype_nansafe(arr, dtype, copy=False)
733+
734+
expected = np.array([1.0, 2.0, 3.0], dtype=dtype)
735+
tm.assert_numpy_array_equal(result, expected)
736+
737+
727738
@pytest.mark.parametrize("from_type", [np.datetime64, np.timedelta64])
728739
@pytest.mark.parametrize(
729740
"to_type",

0 commit comments

Comments
 (0)