栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

熊猫groupby方法实际上是如何工作的?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

熊猫groupby方法实际上是如何工作的?

当您只使用

df.groupby('A')

你得到一个

GroupBy
对象。此时您尚未对其应用任何功能。在幕后,虽然这个定义可能并不完美,但是您可以将
groupby
对象视为:

  • (组,Dataframe) 对的迭代器,用于Dataframe,或
  • 系列(组,系列) 对的迭代器。

为了显示:

df = Dataframe({'A' : [1, 1, 2, 2], 'B' : [1, 2, 3, 4]})grouped = df.groupby('A')# each `i` is a tuple of (group, Dataframe)# so your output here will be a little messyfor i in grouped:    print(i)(1,    A  B0  1  11  1  2)(2,    A  B2  2  33  2  4)# this version uses multiple counters# in a single loop.  each `group` is a group, each# `df` is its corresponding Dataframefor group, df in grouped:    print('group of A:', group, 'n')    print(df, 'n')group of A: 1   A  B0  1  11  1  2group of A: 2   A  B2  2  33  2  4# and if you just wanted to visualize the groups,# your second counter is a "throwaway"for group, _ in grouped:    print('group of A:', group, 'n')group of A: 1group of A: 2

现在至于

.head
。只需查看该方法的文档即可:

本质上等同于

.apply(lambda x: x.head(n))

所以在这里,您实际上是在对groupby对象的每个组应用一个函数。请记住,每个组

.head(5)
适用
于每个组,因此,由于每个组少于或等于5行,因此可以得到原始的Dataframe。

在上面的示例中考虑这一点。如果使用

.head(1)
,则仅获得每个组的第一行:

print(df.groupby('A').head(1))   A  B0  1  12  2  3


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/441133.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号