diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 372f991d96a22..26d96dda9e2e2 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -797,6 +797,7 @@ Reshaping - Improved error message when creating a :class:`DataFrame` column from a multi-dimensional :class:`numpy.ndarray` (:issue:`42463`) - :func:`concat` creating :class:`MultiIndex` with duplicate level entries when concatenating a :class:`DataFrame` with duplicates in :class:`Index` and multiple keys (:issue:`42651`) - Bug in :meth:`pandas.cut` on :class:`Series` with duplicate indices (:issue:`42185`) and non-exact :meth:`pandas.CategoricalIndex` (:issue:`42425`) +- Bug in :meth:`DataFrame.transpose`, where mixed dtypes were cast to ``object`` (:issue:`43337`) - Bug in :meth:`DataFrame.append` failing to retain dtypes when appended columns do not match (:issue:`43392`) - Bug in :func:`concat` of ``bool`` and ``boolean`` dtypes resulting in ``object`` dtype instead of ``boolean`` dtype (:issue:`42800`) - Bug in :func:`crosstab` when inputs are are categorical Series, there are categories that are not present in one or both of the Series, and ``margins=True``. Previously the margin value for missing categories was ``NaN``. It is now correctly reported as 0 (:issue:`43505`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index fa5e9dc51419a..2ba8e66858ffd 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3397,9 +3397,13 @@ def transpose(self, *args, copy: bool = False) -> DataFrame: else: new_arr = self.values.T - if copy: - new_arr = new_arr.copy() - result = self._constructor(new_arr, index=self.columns, columns=self.index) + common_dtype = find_common_type(dtypes) if len(dtypes) > 0 else None + result = self._constructor( + new_arr, + index=self.columns, + columns=self.index, + dtype=common_dtype, + ) return result.__finalize__(self, method="transpose") diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index 7fca752f2a21e..f09d2c1be0ac1 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -116,3 +116,10 @@ def test_transpose_get_view_dt64tzget_view(self): rtrip = result._mgr.blocks[0].values assert np.shares_memory(arr._ndarray, rtrip._ndarray) + + def test_transpose_mixed_dtypes(self): + # GH#43337 + df = DataFrame({"a": [1], "b": [2]}).astype({"b": "Int64"}) + result = df.T + expected = DataFrame([1, 2], index=["a", "b"], dtype="Int64") + tm.assert_frame_equal(result, expected)