在Pandas中,我们可以使用pivot_table()
函数来创建透视表,并且不使用分组索引。下面是一个示例代码:
import pandas as pd
# 创建示例数据
data = {'A': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'two', 'one', 'one', 'two', 'two', 'two', 'one', 'one'],
'C': ['small', 'large', 'large', 'small', 'small', 'large', 'small', 'small', 'large', 'small', 'large'],
'D': [1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9],
'E': [2, 4, 5, 5, 6, 6, 8, 9, 9, 10, 12]}
df = pd.DataFrame(data)
# 创建透视表
pivot_table = pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc='sum')
# 打印结果
print(pivot_table)
输出结果如下:
C large small
A B
bar one 6.0 3.0
two NaN 11.0
foo one NaN 2.0
two 4.0 5.0
这个例子中,我们使用pivot_table()
函数创建了一个透视表。values
参数指定了要汇总的列,index
参数指定了要用作行索引的列,columns
参数指定了要用作列索引的列,aggfunc
参数指定了汇总函数(在这个例子中使用了求和函数sum
)。最后,我们打印了透视表的结果。