全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
1207 0
2020-05-12

Group By:split-apply-combine¶

By “group by” we are referring to a process involving one ormore of the following steps:


一般使用group by我们是指以下的一个过程,该过程包含下列一步或几步


·        Splittingthe data into groups based on some criteria.


·        基本特定规则把数据分割割成多个组。


·        Applyinga function to each group independently.


·        对于每个组独立的使用某个函数


·        Combiningthe results into a data structure.


·        把使用后的结果再联结成一个新的数据结构


Out of these, the split step is the most straightforward. Infact, in many situations, we may wish to split the data set into groups and dosomething with those groups. In the apply step, we might wish to do one of thefollowing:


除以此外,这个分割的步骤是最直接的。事实上在许多场景中,我们可能希望分割数据集成为多个组,并且同时对这些组做某些事情。在应用的步骤中,我们可能会希望做以下几种中的一个:


·        Aggregation:compute a summary statistic (or statistics) for each group. Some examples:汇总:计算一个总计的统计量或统计量数对于每个组。某些例子:计算组总和或组平均;计算组规模或组计数。


o    Computegroup sums or means.


o    Computegroup sizes / counts.


·        Transformation:perform some group-specific computations and return a like-indexed object. Someexamples:变形:进行一些组内具体计算并且返回一个像index一样的对象。举例:对一组进行标准化处理,zscore;把一组内的缺失值全部用来自于每组的数据填补。


o    Standardizedata (zscore) within a group.


o    FillingNAs within groups with a value derived from each group.


·        Filtration:discard some groups, according to a group-wise computation that evaluates Trueor False. Some examples:过滤:根据组内计算的结果,抛弃一些组拥有Trueor False的值。例子:抛弃一些数据,这些数据仅拥有少量的members;过滤数据基于组总和或组平均值。


o    Discarddata that belongs to groups with only a few members.


o    Filterout data based on the group sum or mean.


·        Some combination of the above:GroupBy will examine the results of the apply step and try to return a sensiblycombined result if it doesn’t fit into either of the above two categories.以上这些内容的combination:GroupBY函数会检查应用步骤的结果,尝试返回一个有意义的联合结果,如果它对以上两种类型都不合适的话,则不返回结果。


Since the set of object instance methods on pandas datastructures are generally rich and expressive, we often simply want to invoke,say, a DataFrame function on each group. The name GroupBy should be quitefamiliar to those who have used a SQL-based tool (or itertools),in which you can write code like:因为一系列的对象举例方法在pandas数据结构中是一般富有和另人印象深刻 的,我们通常想要invoke或者说每组的DataFrame函数,这个GroupBy的名字应该对于这些经常使用的SQL基本工具的人所熟悉,因此你可以写出如下的代码:


SELECTColumn1, Column2, mean(Column3),sum(Column4)


FROMSomeTable


GROUP BY Column1, Column2


对象在python中可以是字典、列表、序列和表格

We aim to make operations like this natural and easy to expressusing pandas. We’ll address each area of GroupBy functionality then providesome non-trivial examples / use cases.我们的目标是让操作像这个一样自然,并且更加容易的使用pandas。我们将会解决GroupBy函数每个区域,然后提供某些非trivial的例子。

See the cookbook for some advanced strategies.可以看cookbook去看更高级的策略。


Splitting an object intogroups¶

pandas objects can be split on any of their axes. The abstractdefinition of grouping is to provide a mapping of labels to group names. Tocreate a GroupBy object (more on what the GroupBy object is later), you may dothe following:


把一个目标分为多个组,pandas的对象可以被根据他们的任意axes轴进行分割,这个抽象分组定义将会提供对于组名map的标签,为了创建一个groupby的目标(也可以是多个,我们之后会提到),你可能需要做剩下的步骤。


默认轴是0


df = pd.DataFrame([('S', 'Spain', 65000),


  ...:                    ('A','England', 75000),


  ...:                    ('A','England', 80000),


  ...:                    ('S','England', 90000),


  ...:                    ('S','Germany',95000)],


  ...:                  index=['Barcelona', 'Arsenal', 'Manchester United', 'Livepool', 'FCBayern München'],


  ...:                  columns=('class', 'Nation', 'Seating'))


grouped = df.groupby('class')


grouped= df.groupby('order', axis='columns')


The mapping can be specified many different ways:


·        A Python function, to be calledon each of the axis labels.


·        A list or NumPy array of the samelength as the selected axis.


·        A dict or Series,providing a label -> group name mapping.


·        For DataFrameobjects, a string indicating a column to be used to group. Of course df.groupby('A') is just syntactic sugarfor df.groupby(df['A']), but itmakes life simpler.


·        For DataFrameobjects, a string indicating an index level to be used to group.


·        A list of any of the abovethings.


Mapping可以用以下多种方法来进行


一个python函数,可以应用于每一个轴标签


一个list或一个numpy array与被选中的轴有同样的长度


一个字典或序列,提供一个标签对应组名的mapping


对于一个DataFrame的对象,一个字串可以展示被用于分组的一列,当然df.groupby


A就仅仅是一个syntacticsugar对于 df.groupby(df['A'])来说,他只是让生活更简单了。


对于一个DataFrame的对象,一个字串可以展示被用于分组的index序列


由以上任一组成 的list


Collectively we refer to the grouping objects as the keys. For example,consider the following DataFrame:


一般的,我们把分组的对象认为是关键词,例如,考虑到如下的一个DataFrame




Note


A string passed to groupby may refer to either a column or anindex level. If a string matches both a column name and an index level name, a ValueError will be raised.


一个字串被传入groupby可能同时指向列或序列,如果一个字串同时匹配一个列名和一个index索引序列名,一个ValueError会发生。



On a DataFrame, we obtain a GroupBy object by calling groupby(). Wecould naturally group by either the Aor B columns, or both:


在一个DF中,我们可以获得groupby的对象通过召唤groupby函数,我们也可以自然的用A或B列来进行分组,或者两个都用


If we also have a MultiIndex on columns Aand B, we can group by all but thespecified columns


如果我们也使用A和B列的多重索引,我们可以用他们一起分组,也可以单独分组




These will split the DataFrame on its index (rows). We couldalso split by the columns:


这个将会划分DF按照他的索引或行来划分 ,我们也可以按照列来划分


原文链接https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群