使用 Python Pandas 创建具有多列的透视表
我们可以创建一个有多列的透视表。要创建透视表,请使用 pandas.pivot_table 创建电子表格样式的透视表作为 DataFrame。
首先,导入所需的库 −
import pandas as pd
使用 Team 记录创建一个 DataFrame −
dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})
创建一个有多列的透视表。我们设置了两个以上的列 −
pd.pivot_table(dataFrame, index = ["Team ID", "Team Name", "Team Rank"])
示例
以下是代码 −
import pandas as pd # create DataFrame with Team records dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}}) print("\n... Pivot ...") # multiple columns print(pd.pivot_table(dataFrame, index = ["Team ID", "Team Name", "Team Rank"]))
输出
这会生成以下输出 −
... Pivot ... Team Points Team ID Team Name Team Rank 2 Sri Lanka Three 80 5 India One 95 6 Bangladesh Six 42 7 England Five 55 9 Australia Two 93 11 South Africa Four 60
广告