How to Convert Columns to Rows in Pandas
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:
- Keep the
name
andarea
headers (id_vars
) - Create a new header
year
that uses the remaining headers as row values (var_name
) - 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")