The transpose
method is used to transpose the pandas dataframe. This method reflects the dataframe over its main diagonal by inter-changing rows as columns and vice-versa.
The attribute T
on the dataframe object is an accessor to the transpose
method.
Note: Refer to What is pandas in Python to learn more about pandas.
Dataframe.transpose(*args, copy=False)
The copy
parameter indicates whether to copy the data after transposing. If True
, the data is copied. Otherwise, it isn’t. The default value is False
.
import pandas as pddata = {'col1': [1, 2], 'col2': [3, 4]}df = pd.DataFrame(data)df_transpose = df.transpose()df_transpose_attr = df.Tprint("Dataframe:")print(df)print("Transpose using transpose() method:")print(df_transpose)print("Transpose using 'T'")print(df_transpose_attr)
Here is a line-by-line explanation of the above code:
pandas
module is imported.df
.df
by invoking the transpose()
method on df
. The result is called df_transpose
.df
is obtained using .T
attribute of df
. The result is called df_transpose_attr
.df
, df_transpose
and df_transpose_attr
.