Transposing

We wish to transpose a data frame so the index becomes column names and column names become the index of the data frame.

We wish to transpose a data frame so (1) its columns become its rows (2) the column names are converted to a column and (3) the values of a particular column are used as the new column names.

In this example, we wish to transpose the data frame df that has 4 columns and 4 rows.

df_2 = df.set_index('a').T.reset_index(names="A")

Here is how this works:

  • In set_index('a'), we set the column whose values we wish to have as column names of the output data frame as the index, which in this case is column a. If the values that we wish to have as column names of the output data frame are already in the index of the input data frame, we do not need this step.
  • We use the T property of Pandas data frames to transpose the data frame.
  • In reset_index(names="A"), we move the index back into the data frame as a column with the name “A”. If we are okay leaving the column names of the original data frame in the index of the output data frame, we do not need this step.
PYTHON
I/O