温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pandas怎么实现分组

发布时间:2021-08-17 20:24:18 来源:亿速云 阅读:98 作者:chen 栏目:云计算

这篇文章主要讲解了“Pandas怎么实现分组”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Pandas怎么实现分组”吧!

创建测试数据框

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    d0  1  5  x  one1  2  6  y  two2  3  7  x  three3  4  8  y  two

计算以c列分组的,每组的平均值,非数值列将会被自动忽略

print(df.groupby(df["c"]).mean())
   a  bc      
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 d0  1  5  x  one('x', 'three') ----------- a b c d2  3  7  x  three('y', 'two') ----------- a b c d1  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    maxc                            
x   1   3   5   7  one  threey   2   4   6   8  two    two

将结果返回到数据框transform

print(df.groupby('c').transform('mean'))
   a  b0  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  twoc                 
x  1.0    3.0  NaN
y  NaN    NaN  6.0

感谢各位的阅读,以上就是“Pandas怎么实现分组”的内容了,经过本文的学习后,相信大家对Pandas怎么实现分组这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI