Skip to content

Commit 0443427

Browse files
Backport PR #57322 on branch 2.2.x (REGR: Fix astype conversion of ea int to td/dt with missing values) (#57331)
Backport PR #57322: REGR: Fix astype conversion of ea int to td/dt with missing values Co-authored-by: Patrick Hoefler <[email protected]>
1 parent 361b089 commit 0443427

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

pandas/core/arrays/_utils.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,21 @@ def to_numpy_dtype_inference(
3939
dtype = arr.dtype.numpy_dtype # type: ignore[union-attr]
4040
elif dtype is not None:
4141
dtype = np.dtype(dtype)
42-
if na_value is lib.no_default and hasna and dtype.kind == "f":
43-
na_value = np.nan
4442
dtype_given = True
4543
else:
4644
dtype_given = True
4745

4846
if na_value is lib.no_default:
49-
na_value = arr.dtype.na_value
47+
if dtype is None or not hasna:
48+
na_value = arr.dtype.na_value
49+
elif dtype.kind == "f": # type: ignore[union-attr]
50+
na_value = np.nan
51+
elif dtype.kind == "M": # type: ignore[union-attr]
52+
na_value = np.datetime64("nat")
53+
elif dtype.kind == "m": # type: ignore[union-attr]
54+
na_value = np.timedelta64("nat")
55+
else:
56+
na_value = arr.dtype.na_value
5057

5158
if not dtype_given and hasna:
5259
try:

pandas/tests/extension/test_arrow.py

+9
Original file line numberDiff line numberDiff line change
@@ -3305,6 +3305,15 @@ def test_arrow_floordiv_floating_0_divisor(dtype):
33053305
tm.assert_series_equal(result, expected)
33063306

33073307

3308+
@pytest.mark.parametrize("dtype", ["float64", "datetime64[ns]", "timedelta64[ns]"])
3309+
def test_astype_int_with_null_to_numpy_dtype(dtype):
3310+
# GH 57093
3311+
ser = pd.Series([1, None], dtype="int64[pyarrow]")
3312+
result = ser.astype(dtype)
3313+
expected = pd.Series([1, None], dtype=dtype)
3314+
tm.assert_series_equal(result, expected)
3315+
3316+
33083317
@pytest.mark.parametrize("pa_type", tm.ALL_INT_PYARROW_DTYPES)
33093318
def test_arrow_integral_floordiv_large_values(pa_type):
33103319
# GH 56676

pandas/tests/series/methods/test_to_numpy.py

+13
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from pandas import (
77
NA,
88
Series,
9+
Timedelta,
910
)
1011
import pandas._testing as tm
1112

@@ -34,3 +35,15 @@ def test_to_numpy_arrow_dtype_given():
3435
result = ser.to_numpy(dtype="float64")
3536
expected = np.array([1.0, np.nan])
3637
tm.assert_numpy_array_equal(result, expected)
38+
39+
40+
def test_astype_ea_int_to_td_ts():
41+
# GH#57093
42+
ser = Series([1, None], dtype="Int64")
43+
result = ser.astype("m8[ns]")
44+
expected = Series([1, Timedelta("nat")], dtype="m8[ns]")
45+
tm.assert_series_equal(result, expected)
46+
47+
result = ser.astype("M8[ns]")
48+
expected = Series([1, Timedelta("nat")], dtype="M8[ns]")
49+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)