How to transpose a dataframe

In this post, you will learn how to transpose a dataframe in Pandas.

For those who don’t know what transpose is, I explain that it’s a swap of rows and columns.

Transpose is needed when you need a different view of the data being analyzed, or you want to compute metrics for data that happens to be in rows in your dataframe.

How to transpose a dataframe in Pandas

Transposing data in Pandas is easy because there is a dedicated transpose function that swaps rows and columns with just one line of code.

import pandas as pd

my_df = pd.DataFrame({'Id1': [1, 2, 3, 7],
                      'Id2': [2, 5, None, 46],
                      'Id3': [12, None, 5, 22]})

print(f'This is my dataframe \n{my_df}')

my_df = my_df.transpose()

print(f'This is my transposed dataframe \n{my_df}')

how to transpose a dataframe

As you can see the rows and columns have been swapped.

See also:
Documentation of transpose method

This Post Has One Comment

Leave a Reply