将数据透视表创建为 DataFrame – Python Pandas
要创建数据透视表,请使用 将电子表格样式的数据透视表创建为 DataFrame。pandas.pivot_table()
首先,导入所需的库 -
import pandas as pd
使用团队记录创建一个 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"])
示例
以下是代码 -
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"DataFrame...\n",dataFrame
print"\n... Pivot ..."
print(pd.pivot_table(dataFrame, index = ["Team ID"]))
这将产生以下输出 -
DataFrame...Team ID Team Name Team Points Team Rank
0 5 India 95 One
1 9 Australia 93 Two
2 6 Bangladesh 42 Six
3 11 South Africa 60 Four
4 2 Sri Lanka 80 Three
5 7 England 55 Five
... Pivot ...
Team Points
Team ID
2 80
5 95
6 42
7 55
9 93
11 60
以上是 将数据透视表创建为 DataFrame – Python Pandas 的全部内容, 来源链接: utcz.com/z/353576.html