你可以使用下面的基本语法将一个pandas DataFrame从长格式转换为宽格式。
df = pd.pivot(df, index='col1', columns='col2', values='col3')
在这种情况下,col1将成为索引,col2将成为列,而col3将被用作DataFrame内部的值。
下面的例子展示了如何在实践中使用这种语法。
例子:将潘达斯数据框架从长形重塑为宽形
假设我们有下面这个长格式的pandas DataFrame:
import pandas as pd
#create DataFrame in long format
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'player': [1, 2, 3, 4, 1, 2, 3, 4],
'points': [11, 8, 10, 6, 12, 5, 9, 4]})
#view DataFrame
df
team player points
0 A 1 11
1 A 2 8
2 A 3 10
3 A 4 6
4 B 1 12
5 B 2 5
6 B 3 9
7 B 4 4
我们可以使用下面的语法将这个DataFrame从长格式重塑为宽格式:
#reshape DataFrame from long format to wide format
df = pd.pivot(df, index='team', columns='player', values='points')
#view updated DataFrame
df
player 1 2 3 4
team
A 11 8 10 6
B 12 5 9 4
现在的DataFrame是宽格式的。
我们使用'team'作为索引列,'player'作为列,'point'作为DataFrame里面的值。
注意,如果我们愿意的话,我们可以使用'球员'作为索引列,'球队'作为列:
#reshape DataFrame from long format to wide format
df = pd.pivot(df, index='player', columns='team', values='points')
#view updated DataFrame
df
team A B
player
1 11 12
2 8 5
3 10 9
4 6 4
这个DataFrame也是宽格式的。
注意:你可以在这里找到pandaspivot()函数的完整文档。
其他资源
下面的教程解释了如何在Python中执行其他常见的操作:
Pandas:如何将数据框架从宽格式重塑为长格式
如何向Pandas数据框架添加行
如何向Pandas数据框架添加列
如何计算Pandas数据框架中特定值的出现次数