初始化数据
import pandas as pd
df = pd.DataFrame({
'name': ['xiaoming', 'xiaoming', 'xiaoming', 'xiaohong', 'xiaohong', 'xiaohong', 'xiaohua', 'xiaohua', 'xiaohua'],
'course': ['Chinese', 'Math', 'English', 'Chinese', 'Math', 'English', 'Chinese', 'Math', 'English'],
'score': [78, 88, 98, 67, 92, 95, 82, 62, 87]
})
数据展示
name course score
0 xiaoming Chinese 78
1 xiaoming Math 88
2 xiaoming English 98
3 xiaohong Chinese 67
4 xiaohong Math 92
5 xiaohong English 95
6 xiaohua Chinese 82
7 xiaohua Math 62
8 xiaohua English 87
df_new = df.pivot_table(values='score', index='name', columns='course')
course Chinese English Math
name
xiaohong 67 95 92
xiaohua 82 87 62
xiaoming 78 98 88
pd.melt(df_new, id_vars=['name'], var_name='course', value_name='score')
又还原了