diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index d3f256259b15f..1d511dceaa0ee 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -4,6 +4,7 @@ import pytest from pandas import ( + NA, Categorical, CategoricalDtype, DataFrame, @@ -136,6 +137,34 @@ def test_astype_cast_nan_inf_int(self, val, dtype): with pytest.raises(ValueError, match=msg): df.astype(dtype) + @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"]) + @pytest.mark.parametrize("val", [np.nan, NA]) + def test_astype_cast_via_loc_nan_int(self, val, dtype): + # GH31861 + expected = DataFrame({"a": ["foo"], "b": integer_array([val], dtype=dtype)}) + df = DataFrame({"a": ["foo"], "b": [val]}) + df.loc[:, "b"] = df.loc[:, "b"].astype(dtype) + tm.assert_frame_equal(df, expected) + + expected2 = DataFrame( + {"a": ["foo", "foo"], "b": integer_array([val, 1.0], dtype=dtype)} + ) + df2 = DataFrame({"a": ["foo", "foo"], "b": [val, 1.0]}) + df2.loc[:, "b"] = df2.loc[:, "b"].astype(dtype) + tm.assert_frame_equal(df2, expected2) + + expected3 = DataFrame( + {"a": ["foo", "foo"], "b": integer_array([val, val], dtype=dtype)} + ) + df3 = DataFrame({"a": ["foo", "foo"], "b": [val, val]}) + df3.loc[:, "b"] = df3.loc[:, "b"].astype(dtype) + tm.assert_frame_equal(df3, expected3) + + expected4 = DataFrame({"b": integer_array([val], dtype=dtype)}) + df4 = DataFrame({"b": [val]}) + df4.loc[:, "b"] = df4.loc[:, "b"].astype(dtype) + tm.assert_frame_equal(df4, expected4) + def test_astype_str(self): # see GH#9757 a = Series(date_range("2010-01-04", periods=5))