理解Python中的groupby()

2024-06-02 09:16:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解groupby()操作。仅仅了解grouby分组数据是不够的,因为这只是第一步,我们在这方面做了很多工作:

df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], 
                   'Max Speed': [380., 370., 24., 26.],  
                   'Class': ['Prey', 'Prey', 'Not Prey', 'Not Prey']}) 

In [7]: df                                                                                                                                                                                                   
Out[7]: 
   Animal  Max Speed     Class
0  Falcon      380.0      Prey
1  Falcon      370.0      Prey
2  Parrot       24.0  Not Prey
3  Parrot       26.0  Not Prey

我知道groupby()不会对原始数据集进行操作,而是对副本进行操作。我无法理解的是,执行此操作后,代码会是什么样子:

df.groupby('Class') 

我能从视觉上理解它吗?我可以理解原始数据帧,因为我可以看到它是一个表,因此可以想象操作将如何进行。那么,当我们执行上述grouoby()时会发生什么?它是否创建一个新系列或两个新列,其中一个是“Classs”,另一个是包含所有其他值的字符串

我试着查看OfficeDocs用户指南(https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html),但这无助于理解grouby()在运行后的样子


Tags: 数据pandasdf原始数据notmaxclassparrot
1条回答
网友
1楼 · 发布于 2024-06-02 09:16:07

我想你可以查一下this

按对象分组

The groupby() function returns a GroupBy object but essentially describes how the rows of the original dataset have been split. The GroupBy object groups variable is a dictionary whose keys are the computed unique groups and corresponding values being the axis labels belonging to each group.

If you simply run df.groupby('column_for_grouping') you will get a Python object that will look similar to . You may want to know how DataFrameGroupBy object looks internally. So lets print groups split by continent within our DataFrameGroupBy object by iterating through groups.

相关问题 更多 >