How to transpose a dataframe in pandas
Overview
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.
Syntax
Dataframe.transpose(*args, copy=False)
Parameter
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.
Code example
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)
Explanation
Here is a line-by-line explanation of the above code:
- Line 1: The
pandasmodule is imported. - Lines 3–5: We define a dataframe called
df. - Line 7: We obtain the transpose of
dfby invoking thetranspose()method ondf. The result is calleddf_transpose. - Line 9: The transpose of
dfis obtained using.Tattribute ofdf. The result is calleddf_transpose_attr. - Lines 11–18: We print
df,df_transposeanddf_transpose_attr.