Pandas中的groupby可以分成split-apply-combine来理解:
1,Split the data into groups
2,Apply a function to each group independently
3,Combine the results into a data structure
其中第一步就是由groupby方法实现的。
例如将dataframe按照性别分组。
>>> file.groupby("Sex") # file是一个DataFrame
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7ffb7eab3df0>
# 可以看到groupby方法返回了一个DataFrameGroupBy对象。
这个对象可以理解为按照groupby划分出来的多个DataFrame。例如按照性别分组,则DataFrameGroupBy对象就代表了两个DataFrame,一个是性别为female的DataFrame,另一个是性别为male的DataFrame。使用get_group()可以得到对应的DataFrame:
>>> type(file.groupby("Sex").get_group("female"))
<class 'pandas.core.frame.DataFrame'> # 可以看到g