Pandas DataFrame | transpose method
Start your free 7-days trial now!
Pandas DataFrame.transpose(~)
method swaps the rows and columns of the source DataFrame.
The transpose of a DataFrame, whose column(s) contain mixed types, will have columns of type object
. Check out the examples below for clarification.
Parameters
1. copy
| boolean
| optional
Whether or not to create a new copy of the source DataFrame. Note that a copy represents a new DataFrame, that is, modifying the transpose would not mutate the original DataFrame and vice versa. By default, copy=False
.
The source DataFrame is always copied if any of its columns contains mixed types (e.g. a mix of strings and numerics).
Return Value
The transposed DataFrame.
Examples
Basic usage
Consider the following DataFrame:
df
A B0 3 51 4 6
Taking its transpose gives:
df.transpose()
0 1A 3 4B 5 6
Notice how the rows and columns are swapped.
Case when columns contain mixed types
Consider the following DataFrame:
df
A B0 3 True1 4 6
Here, column B
contains mixed-types: a boolean
and a numeric
.
Computing the transpose gives:
df.transpose()
0 1A 3 4B True 6
At first glance, you'd think the new column 1
would be of type numeric. However, this isn't the case:
0 object1 objectdtype: object
We see that column 1
is actually of type object
, instead of int
. This is because the transpose of a DataFrame whose column(s) contain mixed types will have all of its columns as type object
.