Search code examples
pythonpandasdataframetranspose

How Can I Reorganize my Pandas DataFrame so that column names become column values?


I currently have a dataframe that looks like this:

Movie 1 Movie 2
1st choice 2nd choice
2nd choice 1st choice

I would like to have a dataframe that looks like this:

1st Choice 2nd Choice
Movie 1 Movie 2
Movie 2 Movie 1

I can't find a way to reorganize my dataframe so that it swaps the column names and column values like this.

I've tried iterating through the rows and creating lists that match the column names to their values and orders appropriately, but it doesn't seem to work correctly

I've also tried just creating a new columns for first choice, second choice, etc which grab the column names and use those as the column values, but I keep getting errors.


Solution

  • melt with ignore_index=False and pivot without specifying the index:

    out = (df.melt(ignore_index=False)
             .pivot(columns='value', values='variable')
             .rename_axis(index=None, columns=None)  # optional
          )
    

    More classical/verbose alternative:

    out = (df.reset_index().melt('index')
             .pivot(index='index', columns='value', values='variable')
             .rename_axis(index=None, columns=None)
           )
    

    Output:

      1st choice 2nd choice
    0    Movie 1    Movie 2
    1    Movie 2    Movie 1