具有字符串值的数据框数据透视表

Pivot Dataframe with String values

假设我们有一个想要旋转的简单数据框,例如:

d = {"Equipment": ["Gym", "Gym", "Class", "Class", "Office", "Office"],
"Details": ["Barbell", "Ball", "Desk", "Desk", "Chair", "Lamp"],
"Recipient": ["Ben", "Ben", "Ben", "Clara", "Clara", "John"]
}

df = pd.DataFrame.from_dict(d)

我想旋转得到一个 df 以保存到电子表格,结果如下所示:

像这样天真地使用枢轴:df.pivot(index="Recipient", columns=["Equipment", "Details"]) 不起作用,尽管我预计它会做类似的事情:

非常感谢指点或示例!

@Neither所述,答案由pandas.crosstab函数给出。

命令

df = pd.crosstab(index=df["Recipient"], columns=[df["Equipment"],df["Details"]])

输出: