How to Convert Columns to Rows in Pandas

Published Dec 5, 2021  ∙  Updated May 2, 2022

How can we convert columns into rows in a Pandas DataFrame?

Example scenario

Suppose we’re dealing with a DataFrame df that looks something like this.

name    area    2019    2020    2021
A       B       0       2       4
C       D       1       3       5

We want to transform the DataFrame to look like this.

name    area    year    value
A       B       2019    0
C       D       2019    1
A       B       2020    2
C       D       2020    3
A       B       2021    4
C       D       2021    5

Transform using melt()

We want to do a few things:

  1. Keep the name and area headers (id_vars)
  2. Create a new header year that uses the remaining headers as row values (var_name)
  3. Create a new header value that uses the remaining row values as row values (value_name)
df.melt(id_vars=["name", "area"], 
        var_name="year", 
        value_name="value")