创建测试数据框
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7,8],'c': ['x', 'y', 'x','y'],'d':["one","two","three","two"]})
print(df)
a b c d
0 1 5 x one
1 2 6 y two
2 3 7 x three
3 4 8 y two
计算以c列分组的,每组的平均值,非数值列将会被自动忽略
print(df.groupby(df["c"]).mean())
a b
c
x 2 6
y 3 7
多列分组
gb=df.groupby([df["c"],df["d"]])
print(gb)
<pandas.core.groupby.DataFrameGroupBy object at 0x0000000004A1DEB8>#groupby存储的是分组信息,而不是分组的数据
for i,j in gb:
print(i)
print('-----------')
print(j)
('x', 'one') -----------
a b c d
0 1 5 x one
('x', 'three') -----------
a b c d
2 3 7 x three
('y', 'two') -----------
a b c d
1 2 6 y two
3 4 8 y two
聚合函数agg()
print(df.groupby(df["c"]).agg(['min','max']))
a b d
min max min max min max
c
x 1 3 5 7 one three
y 2 4 6 8 two two
将结果返回到数据框transform
print(df.groupby('c').transform('mean'))
a b
0 2 6
1 3 7
2 2 6
3 3 7
数据透视表
table =pd.pivot_table(df, values='a', index=['c'],columns=['d'], aggfunc=np.sum)
d one three two
c
x 1.0 3.0 NaN
y NaN NaN 6.0