melt()

noun

say it: “MELT” /ˈmɛlt/

A pandas method that reshapes a table with many similar columns into a longer table with one row for each value.

What does melt() do in pandas?

melt() is a pandas method that turns a wide table into a long one. The columns named in id_vars stay as they are, and every other column becomes rows of a name and a value, named with var_name and value_name.

import pandas as pd
wide = pd.DataFrame({"student_id": [101, 102], "quiz1": [88, 92], "quiz2": [90, 85]})
print(wide.melt(id_vars="student_id", var_name="quiz", value_name="score"))
#    student_id   quiz  score
# 0         101  quiz1     88
# 1         102  quiz1     92
# 2         101  quiz2     90
# 3         102  quiz2     85

In a sentence

  • “melt() turned the six quiz columns into one quiz column and one score column.”
  • “After melt(), each student had a row for each quiz.”

Level: Freelancer · More Python terms at this level

Updated