|
| 1 | +from datetime import datetime |
1 | 2 | import decimal |
| 3 | +from functools import partial |
2 | 4 |
|
3 | 5 | import numpy as np |
4 | 6 | from numpy import iinfo |
@@ -902,6 +904,54 @@ def test_to_numeric_dtype_backend_error(dtype_backend): |
902 | 904 | tm.assert_series_equal(result, expected) |
903 | 905 |
|
904 | 906 |
|
| 907 | +@pytest.mark.parametrize( |
| 908 | + "input_value, expected, pd_type", |
| 909 | + [ |
| 910 | + (datetime(2021, 8, 22), 1629590400000000, "scalar"), |
| 911 | + (datetime(2025, 2, 21), 1740096000000000, "scalar"), |
| 912 | + (pd.NaT, np.nan, "scalar"), |
| 913 | + ([datetime(2021, 8, 22)], [1629590400000000], "series"), |
| 914 | + ([datetime(2025, 2, 21)], [1740096000000000], "series"), |
| 915 | + ([pd.NaT], [np.nan], "series"), |
| 916 | + ([datetime(2021, 8, 22), pd.NaT], [float(1629590400000000), np.nan], "series"), |
| 917 | + ([pd.NaT, datetime(2021, 8, 22)], [np.nan, float(1629590400000000)], "series"), |
| 918 | + ( |
| 919 | + ["apple", 1, datetime(2021, 8, 22)], |
| 920 | + [np.nan, float(1.0), float(1629590400000000)], |
| 921 | + "series_coerce", |
| 922 | + ), |
| 923 | + ([pd.NaT], [np.nan], "series_partial"), |
| 924 | + ([datetime(2025, 2, 21)], [1740096000000000], "series_partial"), |
| 925 | + ( |
| 926 | + [pd.NaT, datetime(2025, 2, 21)], |
| 927 | + [np.nan, float(1740096000000000)], |
| 928 | + "series_partial", |
| 929 | + ), |
| 930 | + ], |
| 931 | +) |
| 932 | +def test_to_numeric_datetime(input_value, expected, pd_type): |
| 933 | + """Test converting a scalar datetime to numeric.""" |
| 934 | + if pd_type == "scalar": |
| 935 | + val = to_numeric(input_value) |
| 936 | + # special handling because Nan!=Nan |
| 937 | + if pd.isna(expected): |
| 938 | + assert pd.isna(val) |
| 939 | + else: |
| 940 | + assert val == expected |
| 941 | + |
| 942 | + elif pd_type == "series": |
| 943 | + val = to_numeric(Series(input_value)) |
| 944 | + tm.assert_series_equal(val, Series(expected)) |
| 945 | + |
| 946 | + elif pd_type == "series_coerce": |
| 947 | + val = to_numeric(Series(input_value), errors="coerce") |
| 948 | + tm.assert_series_equal(val, Series(expected)) |
| 949 | + |
| 950 | + elif pd_type == "series_partial": |
| 951 | + val = Series(input_value).apply(partial(to_numeric)) |
| 952 | + tm.assert_series_equal(val, Series(expected)) |
| 953 | + |
| 954 | + |
905 | 955 | def test_invalid_dtype_backend(): |
906 | 956 | ser = Series([1, 2, 3]) |
907 | 957 | msg = ( |
|
0 commit comments