Unpivot a Dataframe (Melt)

Convert a dataframe from wide format to long format.

Why Unpivot

Unpivoting is useful when you have a dataset in a wide format that you are looking to convert to a long format. Practically, this means that you have columns where you want to maintain their values, but turn them into rows. This is known as a melt in Pandas.

For example, imagine you have a dataset with a product id column, as well as one column per month for a fiscal year: Jan, Feb, etc. The first row in the Jan column contains the quantity of the first product sold in Jan, the second row contains the quantity of the second product sold in Jan, etc.

Unpivoting this dataset would allow you to create a dataframe with three columns: one for the product id, one for the month, and one for the number of that product id sold in that month. This, dataset would make it easier for you to filter down to a specific product and compare the quantity sold across months.

How to Unpivot

Access the Unpivot Taskpane by selecting the Insert tab and then selecting the Unpivot button.

  1. Select the dataframe to Unpivot.

  2. Select the ID Variables. These columns will be present in the unpivoted dataframe. In our example, you would select the product_id column.

  3. Select the Values. Each column header will go in the variables column, and the column values will go in the values column. In our example, you would select all the month columns.

Last updated