千家信息网

Pandas怎么实现分组

发表于:2025-02-04 作者:千家信息网编辑
千家信息网最后更新 2025年02月04日,这篇文章主要讲解了"Pandas怎么实现分组",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"Pandas怎么实现分组"吧!创建测试数据框import p
千家信息网最后更新 2025年02月04日Pandas怎么实现分组

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

创建测试数据框

import pandas as pddf = 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  6y  3  7

多列分组

gb=df.groupby([df["c"],df["d"]])print(gb)#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  two3  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  61  3  72  2  63  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  NaNy  NaN    NaN  6.0

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

0