Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: df.astype changes order of dataframe #42457

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Fixed regressions

Bug fixes
~~~~~~~~~
-
-Bug in :meth:`pandas.DataFrame.astype` (:issue:`42396`)
-

.. ---------------------------------------------------------------------------
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/dtypes/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)