Pandas 分组groupby

创建测试数据框

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

转载于:https://my.oschina.net/u/3473376/blog/895319

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值