|
1 |
| -import re |
2 |
| - |
3 | 1 | import numpy as np
|
4 | 2 | import pytest
|
5 | 3 |
|
6 |
| -from pandas.core.dtypes.common import pandas_dtype |
7 |
| - |
8 |
| -from pandas import Index |
| 4 | +from pandas import ( |
| 5 | + Index, |
| 6 | + to_datetime, |
| 7 | + to_timedelta, |
| 8 | +) |
9 | 9 | import pandas._testing as tm
|
10 | 10 |
|
11 | 11 |
|
@@ -66,15 +66,22 @@ def test_astype_float64_to_float_dtype(self, dtype):
|
66 | 66 | tm.assert_index_equal(result, expected, exact=True)
|
67 | 67 |
|
68 | 68 | @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
|
69 |
| - def test_cannot_cast_to_datetimelike(self, dtype): |
| 69 | + def test_astype_float_to_datetimelike(self, dtype): |
| 70 | + # GH#49660 pre-2.0 Index.astype from floating to M8/m8/Period raised, |
| 71 | + # inconsistent with Series.astype |
70 | 72 | idx = Index([0, 1.1, 2], dtype=np.float64)
|
71 | 73 |
|
72 |
| - msg = ( |
73 |
| - f"Cannot convert dtype=float64 to dtype {pandas_dtype(dtype)}; " |
74 |
| - f"integer values are required for conversion" |
75 |
| - ) |
76 |
| - with pytest.raises(TypeError, match=re.escape(msg)): |
77 |
| - idx.astype(dtype) |
| 74 | + result = idx.astype(dtype) |
| 75 | + if dtype[0] == "M": |
| 76 | + expected = to_datetime(idx.values) |
| 77 | + else: |
| 78 | + expected = to_timedelta(idx.values) |
| 79 | + tm.assert_index_equal(result, expected) |
| 80 | + |
| 81 | + # check that we match Series behavior |
| 82 | + result = idx.to_series().set_axis(range(3)).astype(dtype) |
| 83 | + expected = expected.to_series().set_axis(range(3)) |
| 84 | + tm.assert_series_equal(result, expected) |
78 | 85 |
|
79 | 86 | @pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"])
|
80 | 87 | @pytest.mark.parametrize("non_finite", [np.inf, np.nan])
|
|
0 commit comments