|
12 | 12 | from pandas.compat import u
|
13 | 13 | from pandas import _np_version_under1p14
|
14 | 14 |
|
| 15 | +from pandas.core.arrays import integer_array |
15 | 16 | from pandas.core.dtypes.dtypes import DatetimeTZDtype, CategoricalDtype
|
16 | 17 | from pandas.tests.frame.common import TestData
|
17 | 18 | from pandas.util.testing import (assert_series_equal,
|
@@ -666,6 +667,48 @@ def test_astype_categoricaldtype_class_raises(self, cls):
|
666 | 667 | with tm.assert_raises_regex(TypeError, xpr):
|
667 | 668 | df['A'].astype(cls)
|
668 | 669 |
|
| 670 | + @pytest.mark.parametrize("dtype", ['Int64', 'Int32', 'Int16']) |
| 671 | + def test_astype_extension_dtypes(self, dtype): |
| 672 | + # GH 22578 |
| 673 | + df = pd.DataFrame([[1., 2.], [3., 4.], [5., 6.]], columns=['a', 'b']) |
| 674 | + |
| 675 | + expected1 = pd.DataFrame({'a': integer_array([1, 3, 5], |
| 676 | + dtype=dtype), |
| 677 | + 'b': integer_array([2, 4, 6], |
| 678 | + dtype=dtype)}) |
| 679 | + tm.assert_frame_equal(df.astype(dtype), expected1) |
| 680 | + tm.assert_frame_equal(df.astype('int64').astype(dtype), expected1) |
| 681 | + tm.assert_frame_equal(df.astype(dtype).astype('float64'), df) |
| 682 | + |
| 683 | + df = pd.DataFrame([[1., 2.], [3., 4.], [5., 6.]], columns=['a', 'b']) |
| 684 | + df['b'] = df['b'].astype(dtype) |
| 685 | + expected2 = pd.DataFrame({'a': [1., 3., 5.], |
| 686 | + 'b': integer_array([2, 4, 6], |
| 687 | + dtype=dtype)}) |
| 688 | + tm.assert_frame_equal(df, expected2) |
| 689 | + |
| 690 | + tm.assert_frame_equal(df.astype(dtype), expected1) |
| 691 | + tm.assert_frame_equal(df.astype('int64').astype(dtype), expected1) |
| 692 | + |
| 693 | + @pytest.mark.parametrize("dtype", ['Int64', 'Int32', 'Int16']) |
| 694 | + def test_astype_extension_dtypes_1d(self, dtype): |
| 695 | + # GH 22578 |
| 696 | + df = pd.DataFrame({'a': [1., 2., 3.]}) |
| 697 | + |
| 698 | + expected1 = pd.DataFrame({'a': integer_array([1, 2, 3], |
| 699 | + dtype=dtype)}) |
| 700 | + tm.assert_frame_equal(df.astype(dtype), expected1) |
| 701 | + tm.assert_frame_equal(df.astype('int64').astype(dtype), expected1) |
| 702 | + |
| 703 | + df = pd.DataFrame({'a': [1., 2., 3.]}) |
| 704 | + df['a'] = df['a'].astype(dtype) |
| 705 | + expected2 = pd.DataFrame({'a': integer_array([1, 2, 3], |
| 706 | + dtype=dtype)}) |
| 707 | + tm.assert_frame_equal(df, expected2) |
| 708 | + |
| 709 | + tm.assert_frame_equal(df.astype(dtype), expected1) |
| 710 | + tm.assert_frame_equal(df.astype('int64').astype(dtype), expected1) |
| 711 | + |
669 | 712 | @pytest.mark.parametrize('dtype', [
|
670 | 713 | {100: 'float64', 200: 'uint64'}, 'category', 'float64'])
|
671 | 714 | def test_astype_column_metadata(self, dtype):
|
|
0 commit comments