diff --git a/doc/source/whatsnew/v1.3.1.rst b/doc/source/whatsnew/v1.3.1.rst index 65719a11243f8..82b4d2def0b5c 100644 --- a/doc/source/whatsnew/v1.3.1.rst +++ b/doc/source/whatsnew/v1.3.1.rst @@ -25,7 +25,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -- +-Bug in :meth:`pandas.DataFrame.astype` (:issue:`42396`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 15a18d5027274..651df62623fd2 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1099,6 +1099,9 @@ def astype_nansafe( flat = arr.ravel("K") result = astype_nansafe(flat, dtype, copy=copy, skipna=skipna) order: Literal["C", "F"] = "F" if flags.f_contiguous else "C" + order: Literal["C", "F"] = ( + "F" if (not flags.f_contiguous and not flags.c_contiguous) else order + ) # error: Item "ExtensionArray" of "Union[ExtensionArray, ndarray]" has no # attribute "reshape" return result.reshape(arr.shape, order=order) # type: ignore[union-attr] diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index abb29ce66fd34..ae3f85a7f1272 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -1095,3 +1095,16 @@ def test_period_dtype_compare_to_string(): dtype = PeriodDtype(freq="M") assert (dtype == "period[M]") is True assert (dtype != "period[M]") is False + + +@pytest.mark.parametrize( + "dtype", ["int_", "int8", "int16", "int32", "uint16", "uint32", "uint64"] +) +def test_dtype_frame_order_astype(dtype): + + # GH 42396 + npa = np.random.RandomState(0).randint(100, size=(20, 8)) + df = pd.DataFrame(npa, columns=[f"c{i}" for i in range(8)]) + expected = df.iloc[:6, :3] + result = df.iloc[:6, :3].astype(dtype) + tm.assert_almost_equal(expected, result, check_dtype=False)