1import numpy as np
2import pytest
3
4from pandas import DataFrame, Series
5import pandas._testing as tm
6
7
8class TestConvert:
9    def test_convert_objects(self, float_string_frame):
10
11        oops = float_string_frame.T.T
12        converted = oops._convert(datetime=True)
13        tm.assert_frame_equal(converted, float_string_frame)
14        assert converted["A"].dtype == np.float64
15
16        # force numeric conversion
17        float_string_frame["H"] = "1."
18        float_string_frame["I"] = "1"
19
20        # add in some items that will be nan
21        length = len(float_string_frame)
22        float_string_frame["J"] = "1."
23        float_string_frame["K"] = "1"
24        float_string_frame.loc[float_string_frame.index[0:5], ["J", "K"]] = "garbled"
25        converted = float_string_frame._convert(datetime=True, numeric=True)
26        assert converted["H"].dtype == "float64"
27        assert converted["I"].dtype == "int64"
28        assert converted["J"].dtype == "float64"
29        assert converted["K"].dtype == "float64"
30        assert len(converted["J"].dropna()) == length - 5
31        assert len(converted["K"].dropna()) == length - 5
32
33        # via astype
34        converted = float_string_frame.copy()
35        converted["H"] = converted["H"].astype("float64")
36        converted["I"] = converted["I"].astype("int64")
37        assert converted["H"].dtype == "float64"
38        assert converted["I"].dtype == "int64"
39
40        # via astype, but errors
41        converted = float_string_frame.copy()
42        with pytest.raises(ValueError, match="invalid literal"):
43            converted["H"].astype("int32")
44
45        # mixed in a single column
46        df = DataFrame({"s": Series([1, "na", 3, 4])})
47        result = df._convert(datetime=True, numeric=True)
48        expected = DataFrame({"s": Series([1, np.nan, 3, 4])})
49        tm.assert_frame_equal(result, expected)
50
51    def test_convert_objects_no_conversion(self):
52        mixed1 = DataFrame({"a": [1, 2, 3], "b": [4.0, 5, 6], "c": ["x", "y", "z"]})
53        mixed2 = mixed1._convert(datetime=True)
54        tm.assert_frame_equal(mixed1, mixed2)
55