转载于知乎:
import pandas as pd
df = pd.DataFrame({
'name':['小明','小明','小明','小红','小红','小红','小兰','小兰','小兰'],
'subject':['语文','数学','英语','语文','数学','英语','语文','数学','英语'],
'score': [78,86,99,80,83,85,90,68,88]
})
tt = df.set_index(['name', 'subject'])['score']
tt = tt.unstack()
result = tt.reset_index()
##第二种方法:pivot透视表
tt = pd.pivot(df, index='name', columns='subject', values='score')
result = tt.reset_index()