|
5 | 5 |
|
6 | 6 | import pandas.util._test_decorators as td
|
7 | 7 |
|
| 8 | +from pandas.core.dtypes.cast import astype_nansafe |
8 | 9 | import pandas.core.dtypes.common as com
|
9 | 10 | from pandas.core.dtypes.dtypes import (
|
10 | 11 | CategoricalDtype,
|
|
13 | 14 | IntervalDtype,
|
14 | 15 | PeriodDtype,
|
15 | 16 | )
|
| 17 | +from pandas.core.dtypes.missing import isna |
16 | 18 |
|
17 | 19 | import pandas as pd
|
18 | 20 | from pandas.conftest import (
|
@@ -709,3 +711,42 @@ def test__get_dtype_fails(input_param, expected_error_message):
|
709 | 711 | )
|
710 | 712 | def test__is_dtype_type(input_param, result):
|
711 | 713 | assert com._is_dtype_type(input_param, lambda tipo: tipo == result)
|
| 714 | + |
| 715 | + |
| 716 | +@pytest.mark.parametrize("val", [np.datetime64("NaT"), np.timedelta64("NaT")]) |
| 717 | +@pytest.mark.parametrize("typ", [np.int64]) |
| 718 | +def test_astype_nansafe(val, typ): |
| 719 | + arr = np.array([val]) |
| 720 | + |
| 721 | + msg = "Cannot convert NaT values to integer" |
| 722 | + with pytest.raises(ValueError, match=msg): |
| 723 | + astype_nansafe(arr, dtype=typ) |
| 724 | + |
| 725 | + |
| 726 | +@pytest.mark.parametrize("from_type", [np.datetime64, np.timedelta64]) |
| 727 | +@pytest.mark.parametrize( |
| 728 | + "to_type", |
| 729 | + [ |
| 730 | + np.uint8, |
| 731 | + np.uint16, |
| 732 | + np.uint32, |
| 733 | + np.int8, |
| 734 | + np.int16, |
| 735 | + np.int32, |
| 736 | + np.float16, |
| 737 | + np.float32, |
| 738 | + ], |
| 739 | +) |
| 740 | +def test_astype_datetime64_bad_dtype_raises(from_type, to_type): |
| 741 | + arr = np.array([from_type("2018")]) |
| 742 | + |
| 743 | + with pytest.raises(TypeError, match="cannot astype"): |
| 744 | + astype_nansafe(arr, dtype=to_type) |
| 745 | + |
| 746 | + |
| 747 | +@pytest.mark.parametrize("from_type", [np.datetime64, np.timedelta64]) |
| 748 | +def test_astype_object_preserves_datetime_na(from_type): |
| 749 | + arr = np.array([from_type("NaT")]) |
| 750 | + result = astype_nansafe(arr, dtype="object") |
| 751 | + |
| 752 | + assert isna(result)[0] |
0 commit comments