pivot()

noun

say it: “PIV-ut” /ˈpɪvət/

A pandas method that reshapes a long table into a wide one, turning one column's values into column headers.

What does pivot() do in pandas?

pivot() is a pandas method that turns a long table into a wide one: index names the rows, columns the column headers and values what fills the cells. If two rows would fill the same cell, it stops with an error instead of combining them; combining is pivot_table()'s job.

import pandas as pd
long = pd.DataFrame({"student_id": [101, 101, 102], "quiz": ["quiz1", "quiz2", "quiz1"], "score": [88, 90, 92]})
print(long.pivot(index="student_id", columns="quiz", values="score"))
# quiz        quiz1  quiz2
# student_id
# 101          88.0   90.0
# 102          92.0    NaN

In a sentence

  • “pivot() stopped with an error because one student had two scores for the same quiz.”
  • “pivot() turned the long scores back into one row per student and a column per quiz.”

Level: Freelancer · More Python terms at this level

Updated