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 pd
data = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data)
df_transpose = df.transpose()
df_transpose_attr = df.T
print("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 pandas module is imported.
  • Lines 3–5: We define a dataframe called df.
  • Line 7: We obtain the transpose of df by invoking the transpose() method on df. The result is called df_transpose.
  • Line 9: The transpose of df is obtained using .T attribute of df. The result is called df_transpose_attr.
  • Lines 11–18: We print df, df_transpose and df_transpose_attr.

Free Resources