微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pandas怎么实现分组

这篇文章主要讲解了“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怎么实现分组这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程之家,小编将为大家推送更多相关知识点的文章,欢迎关注!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐